Agent review pass.

This commit is contained in:
hjozwiak committed 2026-11-24 11:12:17 -05:00
1 parent e9b2e9508b
commit 64ee749a8e
105 files changed
+2098 -320

No files matched your search

+13 -1
View File
@@ -79,6 +79,10 @@ type documentPlace struct {
// child's index and count under that generation-checked parent.
parent, parentPrevious, parentNext atspi.ObjectReference
parentChildIndex, parentChildCount int
// parentChildRole is the saved child's role under that parent. Generic
// replacement recovery must match it, so a slot cannot transfer the
// place to an unrelated kind of object.
parentChildRole string
// Bounded surviving ancestry is a navigation fallback, never an action target.
recoveryParents []atspi.ObjectReference
}
@@ -131,7 +135,15 @@ func (cursor *DocumentCursor) captureAnchor(focus atspi.ObjectID) (atspi.ObjectI
if len(cursor.places) == 0 {
return atspi.ObjectID{}, false
}
document := cursor.places[len(cursor.places)-1].document.ID()
place := cursor.places[len(cursor.places)-1]
document := place.document.ID()
// Only the saved place's own focus or object being reported dead means
// the page destroyed the anchor. Any other same-bus focus (for example
// focus that legitimately left the document) must not pull a recapture
// back into the saved document.
if focus != place.focus.ID() && focus != place.object.ID() {
return atspi.ObjectID{}, false
}
if !document.Valid() || document.BusName != focus.BusName || document == focus {
return atspi.ObjectID{}, false
}
+9 -2
View File
@@ -120,7 +120,10 @@ func (cursor *DocumentCursor) MoveCaret(ctx context.Context, reader DocumentCare
}
indices := cursor.caretRanges
if len(indices) == 0 {
if err := cursor.tree.ValidateDocumentCaretRange(ctx, doc, 0, len(doc.Nodes)-1); err != nil {
// No captured range exists to read live, so staleness here is the
// only signal that text appeared after capture. Strict validation
// runs once and forces one recapture instead of reporting empty.
if err := cursor.tree.ValidateDocumentRange(ctx, doc, 0, len(doc.Nodes)-1); err != nil {
return DocumentCaretMove{}, err
}
return DocumentCaretMove{Position: documentPosition(doc, *place)}, nil
@@ -162,7 +165,11 @@ func (cursor *DocumentCursor) MoveCaret(ctx context.Context, reader DocumentCare
if command == CaretPreviousCharacter || command == CaretPreviousWord || command == CaretPreviousLine || command == CaretDocumentStart {
boundary = 0
}
if err := cursor.tree.ValidateDocumentCaretRange(ctx, doc, current, boundary); err != nil {
// Strict here, unlike the live-read paths above: this check exists
// precisely to catch insertions past the boundary, which tolerant
// validation would wave through. It runs once at the boundary, so
// ticking pages cannot turn it into a recapture loop.
if err := cursor.tree.ValidateDocumentRange(ctx, doc, current, boundary); err != nil {
return DocumentCaretMove{}, err
}
}
+34
View File
@@ -633,3 +633,37 @@ func TestDocumentCaretContinuesFromStructuralLinkedHeading(t *testing.T) {
t.Fatalf("Up after linked heading = %+v, %v", line, err)
}
}
// Text inserted past the caret boundary after capture (signalled by text
// invalidation of a node that had no captured caret range) must report
// staleness at the boundary instead of silently reporting "end of
// document" forever. The live-read move itself stays tolerant.
func TestDocumentCaretBoundaryReportsInsertionPastBoundary(t *testing.T) {
ctx := context.Background()
reader := caretTextReader{webID("/text"): "Only line"}
cursor := newCaretTextCursor(t, reader)
if move, err := cursor.MoveCaret(ctx, reader, CaretNextLine); err != nil || move.Moved {
t.Fatalf("clean boundary = %+v, %v; want unmoved without error", move, err)
}
cursor.tree.InvalidateText(webID("/next"))
move, err := cursor.MoveCaret(ctx, reader, CaretNextLine)
if !errors.Is(err, atspi.ErrStaleText) || move.Moved {
t.Fatalf("boundary after insertion = %+v, %v; want stale text error for recapture", move, err)
}
}
// The same applies when the captured document has no caret ranges at all:
// text appearing after capture must not keep reporting an empty document.
func TestDocumentCaretEmptyRangesReportInsertedText(t *testing.T) {
ctx := context.Background()
reader := caretTextReader{}
cursor := newCaretTextCursor(t, reader)
if move, err := cursor.MoveCaret(ctx, reader, CaretNextLine); err != nil || move.Moved {
t.Fatalf("clean empty document = %+v, %v; want unmoved without error", move, err)
}
cursor.tree.InvalidateText(webID("/next"))
move, err := cursor.MoveCaret(ctx, reader, CaretNextLine)
if !errors.Is(err, atspi.ErrStaleText) || move.Moved {
t.Fatalf("empty document after insertion = %+v, %v; want stale text error for recapture", move, err)
}
}
+20 -7
View File
@@ -21,11 +21,13 @@ func rememberTextParent(doc atspi.DocumentSnapshot, place *documentPlace) {
place.parent = atspi.ObjectReference{}
place.parentPrevious, place.parentNext = atspi.ObjectReference{}, atspi.ObjectReference{}
place.parentChildIndex, place.parentChildCount = 0, 0
place.parentChildRole = ""
place.recoveryParents = nil
node, ok := doc.Node(place.object.ID())
if !ok || node.Reference != place.object {
return
}
place.parentChildRole = node.Snapshot.Role
plainText := replacementTextLeaf(node)
firstParent := true
for parentID := node.Parent; parentID.Valid(); {
@@ -201,14 +203,18 @@ func replacementChildNode(doc atspi.DocumentSnapshot, saved documentPlace) (atsp
byID[node.Reference.ID()] = node
}
parent, ok := doc.Node(saved.parent.ID())
if !ok || parent.Reference != saved.parent || len(parent.Children) == 0 ||
// The document root itself is never a bounded recovery parent: its
// children are the whole page, so an index there identifies nothing.
if !ok || parent.Reference != saved.parent || parent.Reference == saved.document ||
atspi.IsWebDocumentRole(parent.Snapshot.Role) || len(parent.Children) == 0 ||
parent.Hidden || parent.ParentEditable || parent.Snapshot.Editable ||
parent.Snapshot.Focusable || parent.Snapshot.SupportsClick {
return atspi.DocumentNode{}, "", false
}
usable := func(child *atspi.DocumentNode) bool {
return child != nil && !child.Hidden && !child.ParentEditable && !child.Snapshot.Editable &&
child.Snapshot.Role != "password text"
child.Snapshot.Role != "password text" &&
saved.parentChildRole != "" && child.Snapshot.Role == saved.parentChildRole
}
for index, id := range parent.Children {
var previous, next atspi.ObjectReference
@@ -226,20 +232,27 @@ func replacementChildNode(doc atspi.DocumentSnapshot, saved documentPlace) (atsp
}
next = sibling.Reference
}
if child := byID[id]; previous == saved.parentPrevious && next == saved.parentNext && usable(child) {
// Boundary evidence needs at least one saved boundary: with neither
// sibling retained (a sole child) every sole child would match.
if child := byID[id]; (saved.parentPrevious.Valid() || saved.parentNext.Valid()) &&
previous == saved.parentPrevious && next == saved.parentNext && usable(child) {
return *child, "replaced-child", true
}
}
siblingsRetired := true
// The index path needs positive evidence of recreation: at least one
// saved sibling, and every saved sibling actually retired. A sole child
// has no siblings to retire, so its index alone proves nothing.
savedSiblings, retiredSiblings := 0, 0
for _, sibling := range []atspi.ObjectReference{saved.parentPrevious, saved.parentNext} {
if !sibling.Valid() {
continue
}
if node, ok := byID[sibling.ID()]; ok && node.Reference == sibling {
siblingsRetired = false
savedSiblings++
if node, ok := byID[sibling.ID()]; !ok || node.Reference != sibling {
retiredSiblings++
}
}
if siblingsRetired && saved.parentChildCount > 0 && len(parent.Children) == saved.parentChildCount &&
if savedSiblings > 0 && retiredSiblings == savedSiblings && saved.parentChildCount > 0 && len(parent.Children) == saved.parentChildCount &&
saved.parentChildIndex >= 0 && saved.parentChildIndex < len(parent.Children) {
if child := byID[parent.Children[saved.parentChildIndex]]; usable(child) {
return *child, "replaced-child-index", true
@@ -305,3 +305,85 @@ func TestDocumentRecoveryUsesSurvivingContainerWithoutTransferringOffset(t *test
})
}
}
// Generic child-slot recovery needs positive evidence of recreation. A
// sole child has no sibling that retired (and a role-changed child is a
// different kind of object), so the place must fall back to the surviving
// container instead of transferring onto the unrelated replacement.
func TestDocumentCaretDoesNotRecoverUnrelatedChildByIndex(t *testing.T) {
ctx := context.Background()
reader := caretTextReader{}
node := func(path, role, name string, children ...atspi.ObjectID) atspi.TreeNode {
snapshot := atspi.Snapshot{BusName: webID(path).BusName, Path: path, Role: role, Name: name}
if role == "button" {
snapshot.Focusable = true
}
return atspi.TreeNode{Snapshot: snapshot, Children: children}
}
for _, test := range []struct {
name string
generation func(suffix string) []atspi.TreeNode
landOn string
notOn string
}{
{
name: "sole child",
generation: func(suffix string) []atspi.TreeNode {
return []atspi.TreeNode{
node("/doc", "document web", "", webID("/section")),
node("/section", "section", "", webID("/only"+suffix)),
node("/only"+suffix, "button", "Buy"),
}
},
landOn: "/onlya", notOn: "/onlyb",
},
{
name: "role change",
generation: func(suffix string) []atspi.TreeNode {
middle := node("/b2"+suffix, "button", "Buy two")
if suffix == "b" {
middle = node("/b2b", "check box", "Buy two")
}
return []atspi.TreeNode{
node("/doc", "document web", "", webID("/section")),
node("/section", "section", "", webID("/b1"+suffix), webID("/b2"+suffix), webID("/b3"+suffix)),
node("/b1"+suffix, "button", "Buy one"), middle, node("/b3"+suffix, "button", "Buy three"),
}
},
landOn: "/b2a", notOn: "/b2b",
},
} {
t.Run(test.name, func(t *testing.T) {
tree, err := atspi.NewAccessibleTree(webID("/doc"), test.generation("a"))
if err != nil {
t.Fatal(err)
}
cursor, _ := NewDocumentCursor(tree)
if _, err := cursor.SyncFocus(ctx, webID("/doc")); err != nil {
t.Fatal(err)
}
for {
move, err := cursor.MoveCaret(ctx, reader, CaretNextLine)
if err != nil || !move.Moved {
t.Fatalf("move onto %s = %+v, %v", test.landOn, move, err)
}
if move.Position.Object.ID() == webID(test.landOn) {
break
}
}
if err := tree.Replace(webID("/doc"), test.generation("b")); err != nil {
t.Fatal(err)
}
position, recovery, err := cursor.syncFocus(ctx, webID("/doc"))
if err != nil {
t.Fatal(err)
}
if recovery == "replaced-child" || recovery == "replaced-child-index" || position.Object.ID() == webID(test.notOn) {
t.Fatalf("recovery = %q onto %v; place transferred to unrelated child %s", recovery, position.Object.ID(), test.notOn)
}
if position.Object.ID() != webID("/section") {
t.Fatalf("recovery = %q onto %v, want surviving container /section", recovery, position.Object.ID())
}
})
}
}
+4 -1
View File
@@ -25,7 +25,10 @@ func (cursor *DocumentCursor) moveTable(ctx context.Context, doc atspi.DocumentS
}
table := doc.Nodes[tableIndex]
tableEnd := doc.SubtreeEnd(tableIndex)
if err := cursor.tree.ValidateDocumentCaretRange(ctx, doc, tableIndex, tableEnd); err != nil {
// Table moves consume only captured snapshot coordinates and cell
// order; nothing is read live. Strict validation must therefore force
// a recapture when the table changed since capture.
if err := cursor.tree.ValidateDocumentRange(ctx, doc, tableIndex, tableEnd); err != nil {
return DocumentCaretMove{}, err
}
var current atspi.DocumentNode
+36
View File
@@ -177,3 +177,39 @@ func TestTableNavigationSkipsHolesAndKeepsLocalDependencies(t *testing.T) {
t.Fatal("failed move changed table position")
}
}
// Table moves consume only captured snapshot data, so a cell whose text
// was invalidated after capture must force a stale error (and recapture)
// instead of navigating the old coordinates.
func TestTableNavigationReportsTextInvalidatedTable(t *testing.T) {
node := func(path, role string, children ...string) atspi.TreeNode {
s := atspi.NewSnapshot(path, path, role, "", "")
s.BusName = webID(path).BusName
n := atspi.TreeNode{Snapshot: s}
for _, child := range children {
n.Children = append(n.Children, webID(child))
}
return n
}
table := node("/table", "table", "/a", "/b")
table.Snapshot.TableRowCount, table.Snapshot.TableColumnCount = 1, 2
a, b := node("/a", "table cell"), node("/b", "table cell")
for _, cell := range []*atspi.TreeNode{&a, &b} {
cell.Snapshot.TablePositionKnown = true
cell.Snapshot.TableRowSpan, cell.Snapshot.TableColumnSpan = 1, 1
}
b.Snapshot.TableColumnIndex = 1
tree, err := atspi.NewAccessibleTree(webID("/doc"), []atspi.TreeNode{node("/doc", "document web", "/table"), table, a, b})
if err != nil {
t.Fatal(err)
}
cursor, _ := NewDocumentCursor(tree)
if _, err := cursor.SyncFocus(context.Background(), webID("/a")); err != nil {
t.Fatal(err)
}
tree.InvalidateText(webID("/b"))
move, err := cursor.MoveCaret(context.Background(), caretTextReader{}, TableRight)
if !errors.Is(err, atspi.ErrStaleText) || move.Moved {
t.Fatalf("text-invalidated table move = %+v, %v; want stale text error for recapture", move, err)
}
}
+12 -4
View File
@@ -211,6 +211,11 @@ func (worker *Worker) moveDocumentRepeated(ctx context.Context, cursor *Document
result.Err = ErrNoCurrent
return result, cursor
}
// Completed steps live outside the move closure, keyed by cursor: a
// recapture-retry of the same cursor resumes only the remaining steps
// from its already-advanced place, while a trial on a different
// retained cursor still starts its own count from zero.
completedSteps := make(map[*DocumentCursor]int)
move := func() (moveErr error) {
attempt := DocumentAttempt{Focus: result.DocumentFocus, Before: cursor.diagnosticState(), Stage: "focus"}
defer func() { result.recordDocumentAttempt(cursor, attempt, moveErr) }()
@@ -224,11 +229,14 @@ func (worker *Worker) moveDocumentRepeated(ctx context.Context, cursor *Document
return err
}
attempt.Stage = "move"
moved := false
for range repeat {
for completedSteps[cursor] < repeat {
move, err := cursor.Move(ctx, target, level, backwards)
if err != nil {
if moved {
// A capture-worthy failure after some steps must surface
// so the recapture below can resume the remaining ones;
// masking it would silently drop those keypresses. Other
// failures keep the partial progress already made.
if completedSteps[cursor] > 0 && !documentNeedsCapture(err) {
return nil
}
return err
@@ -239,7 +247,7 @@ func (worker *Worker) moveDocumentRepeated(ctx context.Context, cursor *Document
if !move.Moved {
break
}
moved = true
completedSteps[cursor]++
}
return nil
}
+111
View File
@@ -1322,3 +1322,114 @@ func TestDocumentWorkerUsesSeparateCaptureDeadline(t *testing.T) {
t.Fatalf("capture was not canceled: %v", call.ctx.Err())
}
}
// refreshingTreeCapturer recaptures by replacing the same tree with fresh
// nodes under the same identities, like a production capture that
// refreshes the retained tree in place.
type refreshingTreeCapturer struct {
tree *atspi.AccessibleTree
nodes func() []atspi.TreeNode
captures int
placements []atspi.ObjectID
}
func (capturer *refreshingTreeCapturer) CaptureDocument(_ context.Context, _ atspi.ObjectID) (*atspi.AccessibleTree, error) {
capturer.captures++
if err := capturer.tree.Replace(webID("/doc"), capturer.nodes()); err != nil {
return nil, err
}
return capturer.tree, nil
}
func (capturer *refreshingTreeCapturer) CaptureDocumentText(ctx context.Context, focus atspi.ObjectID) (*atspi.AccessibleTree, error) {
return capturer.CaptureDocument(ctx, focus)
}
func (capturer *refreshingTreeCapturer) CaptureReviewWindow(ctx context.Context, focus atspi.ObjectID) (*atspi.AccessibleTree, error) {
return capturer.CaptureDocument(ctx, focus)
}
func (capturer *refreshingTreeCapturer) CaptureDesktop(context.Context) (*atspi.AccessibleTree, error) {
return nil, atspi.ErrObjectNotFound
}
func (capturer *refreshingTreeCapturer) SetDocumentPosition(_ context.Context, position atspi.ObjectReference, _ atspi.ObjectID) error {
capturer.placements = append(capturer.placements, position.ID())
return nil
}
// Three coalesced heading presses where the second step goes stale must
// recapture and resume the remaining steps from the first heading,
// landing on the third instead of silently dropping two presses.
func TestWorkerCoalescedMoveResumesRemainingStepsAfterRecapture(t *testing.T) {
nodes := func() []atspi.TreeNode {
node := func(path, role string, children ...string) atspi.TreeNode {
snapshot := atspi.NewSnapshot(path, path, role, "", "")
snapshot.BusName = webID(path).BusName
if role == "heading" {
snapshot.HeadingLevel = 2
}
result := atspi.TreeNode{Snapshot: snapshot}
for _, child := range children {
result.Children = append(result.Children, webID(child))
}
return result
}
return []atspi.TreeNode{
node("/doc", "document web", "/h1", "/mid", "/h2", "/h3"),
node("/h1", "heading"), node("/mid", "paragraph"), node("/h2", "heading"), node("/h3", "heading"),
}
}
tree, err := atspi.NewAccessibleTree(webID("/doc"), nodes())
if err != nil {
t.Fatal(err)
}
cursor, _ := NewDocumentCursor(tree)
ctx := context.Background()
if _, err := cursor.SyncFocus(ctx, webID("/doc")); err != nil {
t.Fatal(err)
}
// The paragraph between the first and second headings goes stale after
// capture: step one commits, step two must demand a recapture.
tree.InvalidateText(webID("/mid"))
capturer := &refreshingTreeCapturer{tree: tree, nodes: nodes}
worker, err := NewWorker(capturer, time.Second)
if err != nil {
t.Fatal(err)
}
worker.SyncFocus(webID("/doc"))
result, _ := worker.moveDocumentRepeated(ctx, cursor, DocumentHeading, 0, false, 0, 0, 3)
if result.Err != nil || !result.Moved || result.DocumentPosition.Object.ID() != webID("/h3") {
t.Fatalf("coalesced move = %+v, want third heading /h3 after recapture", result)
}
if capturer.captures != 1 {
t.Fatalf("captures = %d, want exactly one recapture", capturer.captures)
}
}
// The saved-document capture fallback is only for a dead anchor that is
// the saved place's own focus or object. Focus that legitimately left
// the document (same bus, unrelated object) must not use it.
func TestCaptureAnchorRequiresSavedPlaceIdentity(t *testing.T) {
_, cursor := webCursor(t)
ctx := context.Background()
if _, err := cursor.SyncFocus(ctx, webID("/first")); err != nil {
t.Fatal(err)
}
if anchor, ok := cursor.captureAnchor(webID("/first")); !ok || anchor != webID("/doc") {
t.Fatalf("dead saved focus anchor = %v, %v; want /doc", anchor, ok)
}
if _, ok := cursor.captureAnchor(webID("/chrome")); ok {
t.Fatal("capture anchor fired for focus that legitimately left the document")
}
move, err := cursor.Move(ctx, DocumentHeading, 0, false)
if err != nil || move.Position.Object.ID() != webID("/second") {
t.Fatalf("heading move = %+v, %v", move, err)
}
if anchor, ok := cursor.captureAnchor(webID("/second")); !ok || anchor != webID("/doc") {
t.Fatalf("dead saved object anchor = %v, %v; want /doc", anchor, ok)
}
if _, ok := cursor.captureAnchor(webID("/link")); ok {
t.Fatal("capture anchor fired for an unrelated same-bus object")
}
}