From 069cc7e22e1d1cf88c637b569b6b1d58ace4e6fc Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sun, 8 Nov 2026 10:57:42 -0800 Subject: [PATCH 01/23] test: remove 10 low-value mobile test cases (#39927) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../mobile-native-chat-render-data.test.ts | 185 ------------------ ...leNativeChatMessage.status-notices.test.ts | 15 +- 2 files changed, 2 insertions(+), 198 deletions(-) diff --git a/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts b/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts index 48c20ffab96..05e017fb0e4 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts @@ -21,120 +21,7 @@ function user(id: string, text: string): NativeChatMessage { const fold = (messages: NativeChatMessage[]) => foldMobileNativeChatMessages(messages, 'claude') -function build( - messages: NativeChatMessage[], - streaming: string | null, - pending: Parameters[0]['pending'] -): NativeChatMessage[] { - return buildMobileNativeChatTransientData({ - folded: fold(messages), - streaming, - pending - }).data -} - describe('buildMobileNativeChatTransientData', () => { - it('places an idle send before the streaming reply it caused', () => { - const data = build([assistant('a1', 'Earlier answer')], 'Starting the tests', [ - { id: 'p1', text: 'Run the tests', sentAt: 100 } - ]) - expect(data.map((message) => message.id)).toEqual(['a1', 'p1', 'streaming']) - }) - - it('folds transcript image marker turns into image-ref blocks (desktop parity)', () => { - const data = build( - [ - user('u1', '[Image: source: /tmp/a.png]'), - user('u2', '[Image #1] look at this'), - assistant('a1', 'nice photo') - ], - null, - [] - ) - const merged = data.find((message) => message.role === 'user') - expect(merged?.blocks).toEqual([ - { type: 'image-ref', path: '/tmp/a.png' }, - { type: 'text', text: 'look at this' } - ]) - }) - - it('folds a trailing-marker image echo into one user bubble', () => { - const data = build( - [user('u1', '[Image: source: /tmp/a.png]'), user('u2', 'look at this[Image #1]')], - null, - [] - ) - - expect(data).toHaveLength(1) - expect(data[0]?.blocks).toEqual([ - { type: 'image-ref', path: '/tmp/a.png' }, - { type: 'text', text: 'look at this' } - ]) - }) - - it('leaves out an unrecognised provider event with no words, but keeps failures and sentences', () => { - const frameRow = ( - id: string, - kind: string, - text: string, - tone?: string - ): NativeChatMessage => ({ - id, - role: 'system', - timestamp: 0, - source: 'transcript', - blocks: [ - { - type: 'text', - text, - ...(tone ? { tone } : {}), - providerFrame: { - provider: 'codex', - kind, - payload: { head: '{}', byteLength: 2, digest: 'digest', truncated: false } - } - } - ] - }) - const folded = fold([ - frameRow('wordless', 'notification:future/event', 'codex · notification:future/event'), - frameRow( - 'failure', - 'notification:future/failure', - 'codex · notification:future/failure', - 'error' - ), - frameRow('sentence', 'notification:warning', 'Sandbox is degraded.'), - assistant('a1', 'done') - ]) - expect(folded.map((message) => message.id)).toEqual(['failure', 'sentence', 'a1']) - }) - - it('draws a turn’s subagents, each written as its own row, as one roster row', () => { - const own = (id: string): NativeChatMessage => ({ - id: `subagent:${id}`, - role: 'system', - blocks: [ - { type: 'text', text: `Kicked off subagent ${id}` }, - { type: 'subagent', id, label: id, state: 'working', groupId: 'turn-1' } - ], - timestamp: 0, - source: 'transcript' - }) - const folded = fold([user('u1', 'audit'), own('a'), assistant('a1', 'started'), own('b')]) - expect(folded.map((message) => message.id)).toEqual(['u1', 'subagent:a', 'a1']) - expect(folded[1]?.blocks).toEqual([ - { - type: 'subagent-group', - groupId: 'turn-1', - agents: [ - { id: 'a', label: 'a', state: 'working' }, - { id: 'b', label: 'b', state: 'working' } - ] - } - ]) - }) - it('keeps the phone-local image visible when the transcript replaces its optimistic echo', () => { const folded = fold([ user('source', '[Image: source: /tmp/a.png]'), @@ -164,14 +51,6 @@ describe('buildMobileNativeChatTransientData', () => { expect(result.data[0]?.blocks).toEqual([{ type: 'image-ref', url: 'file:///phone-photo.jpg' }]) }) - - it('keeps a queued follow-up after the current streaming reply', () => { - const data = build([user('u1', 'hi')], 'thinking out loud', [ - { id: 'p1', text: 'queued', pendingSend: 'queued' } - ]) - expect(data.map((message) => message.id)).toEqual(['u1', 'streaming', 'p1']) - expect(data[1].blocks).toEqual([{ type: 'text', text: 'thinking out loud' }]) - }) }) describe('foldMobileNativeChatMessages', () => { @@ -195,16 +74,6 @@ describe('foldMobileNativeChatMessages', () => { } } - // Read windows may begin after tool_use; leading orphan results must not become raw-output bubbles. - it('drops a leading tool result whose call is older than the read window', () => { - const folded = fold([ - toolResult('orphan', 'Exit code 1\norca-ide not found'), - assistant('a1', 'Falling back to the installed binary.') - ]) - - expect(folded.map((message) => message.id)).toEqual(['a1']) - }) - function planFrame(head: string): NativeChatMessage { return { id: 'plan', @@ -240,60 +109,6 @@ describe('foldMobileNativeChatMessages', () => { blocks: [{ type: 'tool-call', name: 'update_plan', state: 'completed' }] }) }) - - it('still folds a result whose call is inside the window', () => { - const folded = fold([ - assistant('a1', 'Checking which binary is on PATH.'), - toolCall('c1'), - toolResult('r1', 'orca-ide not found') - ]) - - expect(folded).toHaveLength(1) - expect(folded[0]?.blocks.map((block) => block.type)).toEqual([ - 'text', - 'tool-call', - 'tool-result' - ]) - }) - - it('keeps a mixed Claude tool result with a harness sidecar paired', () => { - const folded = fold([ - toolCall('c1'), - { - id: 'mixed', - role: 'user', - blocks: [ - { type: 'tool-result', output: 'important output' }, - { type: 'text', text: 'continue' } - ], - timestamp: 0, - source: 'transcript' - } - ]) - - expect(folded[0]?.blocks).toEqual([ - { type: 'tool-call', name: 'Bash', input: { command: 'command -v orca-ide' } }, - { type: 'tool-result', output: 'important output' } - ]) - }) - - it('draws a skill command the user ran as their message, as desktop does', () => { - const folded = fold([ - { - ...user( - 'd7306d00', - 'hello\n/hello\nKelvin' - ), - parentId: 'f615a2bf' - }, - { ...assistant('0d3481c0', 'Hello, Kelvin!'), parentId: 'fa9d5ee6' } - ]) - - expect(folded.map((message) => [message.role, message.blocks])).toEqual([ - ['user', [{ type: 'text', text: '/hello Kelvin' }]], - ['assistant', [{ type: 'text', text: 'Hello, Kelvin!' }]] - ]) - }) }) // Claude may consume queued commands without a user record; unmatched echoes must stay at their send position rather than trail every later turn. diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts index ef5a04f9c39..31f565395c6 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts @@ -164,7 +164,7 @@ describe('MobileNativeChatMessage status notices', () => { ]) }) - it.each(['without reset', 'with reset', 'from an old host'] as const)( + it.each(['with reset', 'from an old host'] as const)( 'draws an OpenCode usage warning %s', (source) => { const hasReset = source === 'with reset' @@ -221,12 +221,9 @@ describe('MobileNativeChatMessage status notices', () => { ) it.each([ - ['Claude', 'system', 'claude auth login'], ['Claude', 'managed', 'claude auth login'], ['Codex', 'system', 'codex login --device-auth'], - ['Codex', 'managed', null], - ['Grok', undefined, 'grok login --device-auth'], - ['Antigravity', undefined, null] + ['Codex', 'managed', null] ] as const)( 'offers %s (%s account) sign-in in a host terminal', (agentName, account, command) => { @@ -263,14 +260,6 @@ describe('MobileNativeChatMessage status notices', () => { 'Codex reported a safety review warning. View details.', 'Codex a signalé un avertissement de sécurité. Voir les détails.', colors.statusAmber - ], - [ - 'claude', - 'message:system:permission_denied', - 'error', - 'Claude denied permission. View details.', - 'Claude a refusé la permission. Voir les détails.', - colors.statusRed ] ] as const)( 'discloses the entire available %s notice without tool-output clipping or recovery', From 8781bcb6be31f7c83651d5349fb151e8e29b8e66 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:58:00 -0800 Subject: [PATCH 02/23] Reduce the maximum height of the model picker (#39774) --- .../session/options/controls/NativeChatModelCombobox.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/renderer/src/components/native-chat/session/options/controls/NativeChatModelCombobox.tsx b/src/renderer/src/components/native-chat/session/options/controls/NativeChatModelCombobox.tsx index e8ab21fcaf7..48720846a6a 100644 --- a/src/renderer/src/components/native-chat/session/options/controls/NativeChatModelCombobox.tsx +++ b/src/renderer/src/components/native-chat/session/options/controls/NativeChatModelCombobox.tsx @@ -61,6 +61,7 @@ export function NativeChatModelCombobox({ ) : null} Date: Sun, 8 Nov 2026 19:12:26 +0000 Subject: [PATCH 03/23] feat(runtime): tell phones which settings changed (#39718) * feat(runtime): tell phones which settings changed * test(mobile): re-record Source Control goldens for the settings stream --- ...-git.changes-load-git.branchcompare-1.json | 226 +++++++-------- .../matrix-git.changes-load-git.status-1.json | 266 +++++++++--------- .../matrix-git.changes-load-repo.list-1.json | 226 +++++++-------- ...trix-git.changes-load-worktree.show-1.json | 226 +++++++-------- .../goldens/sc-changes-loaded.json | 142 +++++----- .../sc-changes-return-from-memory.json | 98 +++---- .../goldens/sc-changes-write-reads-live.json | 104 +++---- mobile/src/query/host-event-router.test.ts | 166 +++++++++++ mobile/src/query/host-event-router.ts | 150 +++++++--- mobile/src/query/host-query.ts | 11 +- mobile/src/query/settings-change-signal.ts | 35 +++ .../mobile-agent-launch-queries.ts | 13 +- .../use-mobile-new-tab-agent-options.ts | 8 +- ...bile-source-control-settings-operations.ts | 14 +- .../mobile-source-control-settings.ts | 8 +- .../runtime-settings-change-events.test.ts | 46 +++ .../runtime-settings-change-events.ts | 25 ++ src/main/runtime/orca-runtime.ts | 2 + src/shared/host-runtime-capabilities.ts | 4 + src/shared/runtime-client-events.ts | 2 + 20 files changed, 1083 insertions(+), 689 deletions(-) create mode 100644 mobile/src/query/host-event-router.test.ts create mode 100644 mobile/src/query/settings-change-signal.ts create mode 100644 src/main/runtime/client/settings/runtime-settings-change-events.test.ts create mode 100644 src/main/runtime/client/settings/runtime-settings-change-events.ts diff --git a/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.branchcompare-1.json b/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.branchcompare-1.json index b7969499141..1a61e065e8a 100644 --- a/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.branchcompare-1.json +++ b/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.branchcompare-1.json @@ -252,6 +252,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "4533fb49ac71": { "branchCompareState": { "kind": "error", @@ -342,38 +374,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "6a0cb0684d8b": { "name": "git.branchCompare#1", "ordinal": 10, @@ -592,32 +592,6 @@ } } }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8fda864c66d6": { "branchCompareState": { "kind": "loading" @@ -823,6 +797,32 @@ } } }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "bd638c43a536": { "name": "git.branchCompare#1", "ordinal": 10, @@ -933,11 +933,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -946,6 +941,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "fa79ca4a1a0d": { "name": "git.branchCompare#1", "ordinal": 10, @@ -1052,8 +1052,8 @@ { "id": "sc-changes-loaded.prelude:status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1064,9 +1064,9 @@ { "id": "sc-changes-loaded.prelude:compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1083,14 +1083,14 @@ "id": "sc-changes-loaded.prelude:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "b7127d77e6aa" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1108,14 +1108,14 @@ "id": "sc-changes-loaded.normal:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1133,14 +1133,14 @@ "id": "sc-changes-loaded.normal:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1158,14 +1158,14 @@ "id": "sc-changes-loaded.result-absent:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "fa79ca4a1a0d" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1183,14 +1183,14 @@ "id": "sc-changes-loaded.result-absent:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "fa79ca4a1a0d" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1208,14 +1208,14 @@ "id": "sc-changes-loaded.result-null:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "86eb3bc4e90c" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1233,14 +1233,14 @@ "id": "sc-changes-loaded.result-null:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "86eb3bc4e90c" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1258,14 +1258,14 @@ "id": "sc-changes-loaded.inner-ok-missing:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "dc48d55bec67" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1283,14 +1283,14 @@ "id": "sc-changes-loaded.inner-ok-missing:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "dc48d55bec67" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1308,14 +1308,14 @@ "id": "sc-changes-loaded.inner-false-string-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "bd638c43a536" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1333,14 +1333,14 @@ "id": "sc-changes-loaded.inner-false-string-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "bd638c43a536" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1358,14 +1358,14 @@ "id": "sc-changes-loaded.inner-false-object-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "047f0b230543" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1383,14 +1383,14 @@ "id": "sc-changes-loaded.inner-false-object-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "047f0b230543" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1408,14 +1408,14 @@ "id": "sc-changes-loaded.outer-refused:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "97a020d83f3c" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1433,14 +1433,14 @@ "id": "sc-changes-loaded.outer-refused:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "97a020d83f3c" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1458,14 +1458,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "6a0cb0684d8b" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1483,14 +1483,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "6a0cb0684d8b" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1508,14 +1508,14 @@ "id": "sc-changes-loaded.method-not-found:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "7506958819b1" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1533,14 +1533,14 @@ "id": "sc-changes-loaded.method-not-found:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "7506958819b1" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1558,14 +1558,14 @@ "id": "sc-changes-loaded.transport-rejection:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "fdcce09eef21" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1583,14 +1583,14 @@ "id": "sc-changes-loaded.transport-rejection:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "fdcce09eef21" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1608,14 +1608,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "2cca3e7f3f9b" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1633,14 +1633,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "2cca3e7f3f9b" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.status-1.json b/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.status-1.json index 8944f49a991..bf13a7571d4 100644 --- a/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.status-1.json +++ b/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.status-1.json @@ -379,6 +379,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "393d2f9f3485": { "name": "git.status#1", "ordinal": 3, @@ -484,38 +516,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "6d2d788a9e84": { "name": "git.status#1", "ordinal": 3, @@ -629,32 +629,6 @@ } ] }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8fda864c66d6": { "branchCompareState": { "kind": "loading" @@ -866,6 +840,32 @@ } ] }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "cb462f8b50a3": { "name": "worktree.show#1", "ordinal": 8, @@ -882,11 +882,6 @@ } ] }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -895,6 +890,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "f0896523e780": { "name": "git.status#2", "ordinal": 6, @@ -959,8 +959,8 @@ { "id": "sc-changes-loaded.prelude:status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -971,8 +971,8 @@ { "id": "sc-changes-loaded.prelude:cleanup", "observation": { - "sender": ["63bc0796d81c", "1dbb1f085bde"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "1dbb1f085bde"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -983,9 +983,9 @@ { "id": "sc-changes-loaded.normal:compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1002,14 +1002,14 @@ "id": "sc-changes-loaded.normal:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1027,14 +1027,14 @@ "id": "sc-changes-loaded.normal:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1051,8 +1051,8 @@ { "id": "sc-changes-loaded.result-absent:compare-pending", "observation": { - "sender": ["891438a18444", "f186683ccf2d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "f186683ccf2d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1063,8 +1063,8 @@ { "id": "sc-changes-loaded.result-absent:settled", "observation": { - "sender": ["891438a18444", "f186683ccf2d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "f186683ccf2d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1075,8 +1075,8 @@ { "id": "sc-changes-loaded.result-absent:cleanup", "observation": { - "sender": ["63bc0796d81c", "f186683ccf2d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "f186683ccf2d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1087,8 +1087,8 @@ { "id": "sc-changes-loaded.result-null:compare-pending", "observation": { - "sender": ["891438a18444", "9ae4367a6ff8"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "9ae4367a6ff8"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1099,8 +1099,8 @@ { "id": "sc-changes-loaded.result-null:settled", "observation": { - "sender": ["891438a18444", "9ae4367a6ff8"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "9ae4367a6ff8"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1111,8 +1111,8 @@ { "id": "sc-changes-loaded.result-null:cleanup", "observation": { - "sender": ["63bc0796d81c", "9ae4367a6ff8"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "9ae4367a6ff8"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1123,8 +1123,8 @@ { "id": "sc-changes-loaded.inner-ok-missing:compare-pending", "observation": { - "sender": ["891438a18444", "19fff093880d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "19fff093880d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1135,8 +1135,8 @@ { "id": "sc-changes-loaded.inner-ok-missing:settled", "observation": { - "sender": ["891438a18444", "19fff093880d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "19fff093880d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1147,8 +1147,8 @@ { "id": "sc-changes-loaded.inner-ok-missing:cleanup", "observation": { - "sender": ["63bc0796d81c", "19fff093880d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "19fff093880d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1159,8 +1159,8 @@ { "id": "sc-changes-loaded.inner-false-string-error:compare-pending", "observation": { - "sender": ["891438a18444", "393d2f9f3485"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "393d2f9f3485"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1171,8 +1171,8 @@ { "id": "sc-changes-loaded.inner-false-string-error:settled", "observation": { - "sender": ["891438a18444", "393d2f9f3485"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "393d2f9f3485"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1183,8 +1183,8 @@ { "id": "sc-changes-loaded.inner-false-string-error:cleanup", "observation": { - "sender": ["63bc0796d81c", "393d2f9f3485"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "393d2f9f3485"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1195,8 +1195,8 @@ { "id": "sc-changes-loaded.inner-false-object-error:compare-pending", "observation": { - "sender": ["891438a18444", "1940948b426c"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "1940948b426c"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1207,8 +1207,8 @@ { "id": "sc-changes-loaded.inner-false-object-error:settled", "observation": { - "sender": ["891438a18444", "1940948b426c"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "1940948b426c"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1219,8 +1219,8 @@ { "id": "sc-changes-loaded.inner-false-object-error:cleanup", "observation": { - "sender": ["63bc0796d81c", "1940948b426c"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "1940948b426c"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1231,8 +1231,8 @@ { "id": "sc-changes-loaded.outer-refused:compare-pending", "observation": { - "sender": ["891438a18444", "085b756c7623"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "085b756c7623"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1243,8 +1243,8 @@ { "id": "sc-changes-loaded.outer-refused:settled", "observation": { - "sender": ["891438a18444", "085b756c7623"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "085b756c7623"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1255,8 +1255,8 @@ { "id": "sc-changes-loaded.outer-refused:cleanup", "observation": { - "sender": ["63bc0796d81c", "085b756c7623"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "085b756c7623"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1267,8 +1267,8 @@ { "id": "sc-changes-loaded.outer-refused-no-message:compare-pending", "observation": { - "sender": ["891438a18444", "207e0351be0d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "207e0351be0d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1279,8 +1279,8 @@ { "id": "sc-changes-loaded.outer-refused-no-message:settled", "observation": { - "sender": ["891438a18444", "207e0351be0d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "207e0351be0d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1291,8 +1291,8 @@ { "id": "sc-changes-loaded.outer-refused-no-message:cleanup", "observation": { - "sender": ["63bc0796d81c", "207e0351be0d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "207e0351be0d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1303,8 +1303,8 @@ { "id": "sc-changes-loaded.method-not-found:compare-pending", "observation": { - "sender": ["891438a18444", "6d2d788a9e84"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "6d2d788a9e84"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1315,8 +1315,8 @@ { "id": "sc-changes-loaded.method-not-found:settled", "observation": { - "sender": ["891438a18444", "6d2d788a9e84"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "6d2d788a9e84"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1327,8 +1327,8 @@ { "id": "sc-changes-loaded.method-not-found:cleanup", "observation": { - "sender": ["63bc0796d81c", "6d2d788a9e84"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "6d2d788a9e84"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1339,8 +1339,8 @@ { "id": "sc-changes-loaded.transport-rejection:compare-pending", "observation": { - "sender": ["891438a18444", "9778e6b1ca17", "f0896523e780"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["b823fdc0d205", "9778e6b1ca17", "f0896523e780"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1351,8 +1351,8 @@ { "id": "sc-changes-loaded.transport-rejection:settled", "observation": { - "sender": ["891438a18444", "9778e6b1ca17", "f0896523e780"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["b823fdc0d205", "9778e6b1ca17", "f0896523e780"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1363,8 +1363,8 @@ { "id": "sc-changes-loaded.transport-rejection:cleanup", "observation": { - "sender": ["63bc0796d81c", "9778e6b1ca17", "270fa28bd742"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["3088889ce80e", "9778e6b1ca17", "270fa28bd742"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1375,8 +1375,8 @@ { "id": "sc-changes-loaded.transport-rejection-no-message:compare-pending", "observation": { - "sender": ["891438a18444", "953d7e425499", "f0896523e780"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["b823fdc0d205", "953d7e425499", "f0896523e780"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1387,8 +1387,8 @@ { "id": "sc-changes-loaded.transport-rejection-no-message:settled", "observation": { - "sender": ["891438a18444", "953d7e425499", "f0896523e780"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["b823fdc0d205", "953d7e425499", "f0896523e780"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1399,8 +1399,8 @@ { "id": "sc-changes-loaded.transport-rejection-no-message:cleanup", "observation": { - "sender": ["63bc0796d81c", "953d7e425499", "270fa28bd742"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["3088889ce80e", "953d7e425499", "270fa28bd742"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/matrix-git.changes-load-repo.list-1.json b/mobile/rpc-foundation/goldens/matrix-git.changes-load-repo.list-1.json index 9c9744e247e..8253a6d33a4 100644 --- a/mobile/rpc-foundation/goldens/matrix-git.changes-load-repo.list-1.json +++ b/mobile/rpc-foundation/goldens/matrix-git.changes-load-repo.list-1.json @@ -147,6 +147,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "3dcba72c2342": { "name": "streams-registered-at-teardown", "ordinal": 10, @@ -245,38 +277,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "687fc7be7b14": { "name": "repo.list#1", "ordinal": 7, @@ -530,32 +530,6 @@ } } }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8fda864c66d6": { "branchCompareState": { "kind": "loading" @@ -691,6 +665,32 @@ } } }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "c2c26da9df33": { "name": "repo.list#1", "ordinal": 7, @@ -763,11 +763,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "e610fd221300": { "name": "repo.list#1", "ordinal": 7, @@ -808,6 +803,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "f19d3d43b828": { "name": "repo.list#1", "ordinal": 7, @@ -882,8 +882,8 @@ { "id": "sc-changes-loaded.prelude:status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -894,9 +894,9 @@ { "id": "sc-changes-loaded.prelude:compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -913,14 +913,14 @@ "id": "sc-changes-loaded.prelude:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "f802165696e4", "b60e016a0f1e" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -937,14 +937,14 @@ "id": "sc-changes-loaded.normal:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -962,14 +962,14 @@ "id": "sc-changes-loaded.normal:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -987,14 +987,14 @@ "id": "sc-changes-loaded.result-absent:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "4b1217ea83ab", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1012,14 +1012,14 @@ "id": "sc-changes-loaded.result-absent:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "4b1217ea83ab", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1037,14 +1037,14 @@ "id": "sc-changes-loaded.result-null:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "772f9a3bbdd8", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1062,14 +1062,14 @@ "id": "sc-changes-loaded.result-null:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "772f9a3bbdd8", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1087,14 +1087,14 @@ "id": "sc-changes-loaded.inner-ok-missing:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "7eb62de26957", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1112,14 +1112,14 @@ "id": "sc-changes-loaded.inner-ok-missing:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "7eb62de26957", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1137,14 +1137,14 @@ "id": "sc-changes-loaded.inner-false-string-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "d7b92d364b7b", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1162,14 +1162,14 @@ "id": "sc-changes-loaded.inner-false-string-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "d7b92d364b7b", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1187,14 +1187,14 @@ "id": "sc-changes-loaded.inner-false-object-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "6fe24defc416", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1212,14 +1212,14 @@ "id": "sc-changes-loaded.inner-false-object-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "6fe24defc416", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1237,14 +1237,14 @@ "id": "sc-changes-loaded.outer-refused:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "f19d3d43b828", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1262,14 +1262,14 @@ "id": "sc-changes-loaded.outer-refused:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "f19d3d43b828", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1287,14 +1287,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "687fc7be7b14", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1312,14 +1312,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "687fc7be7b14", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1337,14 +1337,14 @@ "id": "sc-changes-loaded.method-not-found:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "75e5bfff5576", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1362,14 +1362,14 @@ "id": "sc-changes-loaded.method-not-found:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "75e5bfff5576", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1387,14 +1387,14 @@ "id": "sc-changes-loaded.transport-rejection:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "e610fd221300", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1412,14 +1412,14 @@ "id": "sc-changes-loaded.transport-rejection:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "e610fd221300", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1437,14 +1437,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "c2c26da9df33", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1462,14 +1462,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "c2c26da9df33", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/matrix-git.changes-load-worktree.show-1.json b/mobile/rpc-foundation/goldens/matrix-git.changes-load-worktree.show-1.json index cebb910d6e1..13bd3cef82b 100644 --- a/mobile/rpc-foundation/goldens/matrix-git.changes-load-worktree.show-1.json +++ b/mobile/rpc-foundation/goldens/matrix-git.changes-load-worktree.show-1.json @@ -248,6 +248,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "3403b59cf439": { "name": "worktree.show#1", "ordinal": 6, @@ -450,38 +482,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "6f4a5d6a5a86": { "name": "worktree.show#1", "ordinal": 6, @@ -560,32 +560,6 @@ } ] }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8989d6980fc9": { "name": "repo.baseRefDefault#1", "ordinal": 10, @@ -782,6 +756,32 @@ } } }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "cb462f8b50a3": { "name": "worktree.show#1", "ordinal": 8, @@ -924,11 +924,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -937,6 +932,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "f802165696e4": { "name": "repo.list#1", "ordinal": 7, @@ -976,8 +976,8 @@ { "id": "sc-changes-loaded.prelude:status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -988,9 +988,9 @@ { "id": "sc-changes-loaded.prelude:compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1007,14 +1007,14 @@ "id": "sc-changes-loaded.prelude:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "da80647539b5", "f802165696e4", "99df70fb15d8" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1031,14 +1031,14 @@ "id": "sc-changes-loaded.normal:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1056,14 +1056,14 @@ "id": "sc-changes-loaded.normal:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1081,14 +1081,14 @@ "id": "sc-changes-loaded.result-absent:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "b1f1cf609f1a", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1106,14 +1106,14 @@ "id": "sc-changes-loaded.result-absent:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "b1f1cf609f1a", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1131,14 +1131,14 @@ "id": "sc-changes-loaded.result-null:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "3fa278bfc300", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1156,14 +1156,14 @@ "id": "sc-changes-loaded.result-null:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "3fa278bfc300", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1181,14 +1181,14 @@ "id": "sc-changes-loaded.inner-ok-missing:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "12cda398ef1c", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1206,14 +1206,14 @@ "id": "sc-changes-loaded.inner-ok-missing:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "12cda398ef1c", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1231,14 +1231,14 @@ "id": "sc-changes-loaded.inner-false-string-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "cbba4d974cd2", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1256,14 +1256,14 @@ "id": "sc-changes-loaded.inner-false-string-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "cbba4d974cd2", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1281,14 +1281,14 @@ "id": "sc-changes-loaded.inner-false-object-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "3403b59cf439", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1306,14 +1306,14 @@ "id": "sc-changes-loaded.inner-false-object-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "3403b59cf439", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1331,14 +1331,14 @@ "id": "sc-changes-loaded.outer-refused:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "db7a4d8e637e", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1356,14 +1356,14 @@ "id": "sc-changes-loaded.outer-refused:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "db7a4d8e637e", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1381,14 +1381,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "1266df2a91af", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1406,14 +1406,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "1266df2a91af", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1431,14 +1431,14 @@ "id": "sc-changes-loaded.method-not-found:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "d67ff8e687bf", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1456,14 +1456,14 @@ "id": "sc-changes-loaded.method-not-found:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "d67ff8e687bf", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1481,14 +1481,14 @@ "id": "sc-changes-loaded.transport-rejection:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "5782be802edd", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1506,14 +1506,14 @@ "id": "sc-changes-loaded.transport-rejection:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "5782be802edd", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1531,14 +1531,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "1ff055d43072", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1556,14 +1556,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "1ff055d43072", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/sc-changes-loaded.json b/mobile/rpc-foundation/goldens/sc-changes-loaded.json index a170eba82de..ed045bdb30b 100644 --- a/mobile/rpc-foundation/goldens/sc-changes-loaded.json +++ b/mobile/rpc-foundation/goldens/sc-changes-loaded.json @@ -147,6 +147,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "5d30d477f0d5": { "name": "git.branchCompare#1", "ordinal": 10, @@ -203,38 +235,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "6f4a5d6a5a86": { "name": "worktree.show#1", "ordinal": 6, @@ -313,32 +313,6 @@ } ] }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8fda864c66d6": { "branchCompareState": { "kind": "loading" @@ -441,16 +415,37 @@ "kind": "loading" } }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "cb462f8b50a3": { "name": "worktree.show#1", "ordinal": 8, "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -458,6 +453,11 @@ "value": { "$rpc": "undefined" } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" } }, "recording": { @@ -466,8 +466,8 @@ { "id": "status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -478,9 +478,9 @@ { "id": "compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -497,14 +497,14 @@ "id": "settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -522,14 +522,14 @@ "id": "cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/sc-changes-return-from-memory.json b/mobile/rpc-foundation/goldens/sc-changes-return-from-memory.json index fb6db7f022d..3e3e22cf70a 100644 --- a/mobile/rpc-foundation/goldens/sc-changes-return-from-memory.json +++ b/mobile/rpc-foundation/goldens/sc-changes-return-from-memory.json @@ -127,6 +127,38 @@ "$rpc": "undefined" } }, + "22bf66c852bb": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 3001, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "2ca33da4d135": { "name": "repo.list#1", "ordinal": 7, @@ -411,32 +443,6 @@ "ordinal": 17, "json": "{\"id\":\"frame-9\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "92a577a15fcc": { "name": "git.status#1", "ordinal": 5, @@ -540,9 +546,9 @@ } ] }, - "ade0dae5eee8": { + "b823fdc0d205": { "name": "settings.get#1", - "ordinal": 1, + "ordinal": 2, "args": [ { "name": "method", @@ -562,14 +568,8 @@ } ], "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 3001, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } + "status": "pending", + "startedAt": 0 } }, "cb462f8b50a3": { @@ -646,11 +646,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -658,6 +653,11 @@ "value": { "$rpc": "undefined" } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" } }, "recording": { @@ -667,14 +667,14 @@ "id": "loaded", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -692,7 +692,7 @@ "id": "rows-while-revalidating", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", @@ -700,7 +700,7 @@ "7d368b32d250" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -722,7 +722,7 @@ "id": "revalidated", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", @@ -732,7 +732,7 @@ "a6d51875b1b0" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -756,7 +756,7 @@ "id": "cleanup", "observation": { "sender": [ - "ade0dae5eee8", + "22bf66c852bb", "962f91336a50", "74d102469d68", "2ca33da4d135", @@ -767,7 +767,7 @@ "d29ae612a0e8" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/sc-changes-write-reads-live.json b/mobile/rpc-foundation/goldens/sc-changes-write-reads-live.json index adb6c27e5c8..712bfcbf5d9 100644 --- a/mobile/rpc-foundation/goldens/sc-changes-write-reads-live.json +++ b/mobile/rpc-foundation/goldens/sc-changes-write-reads-live.json @@ -203,6 +203,38 @@ } } }, + "22bf66c852bb": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 3001, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "334b41f87c41": { "name": "worktree.show#1", "ordinal": 6, @@ -380,32 +412,6 @@ "ordinal": 17, "json": "{\"id\":\"frame-9\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "92a577a15fcc": { "name": "git.status#1", "ordinal": 5, @@ -562,9 +568,14 @@ "startedAt": 3001 } }, - "ade0dae5eee8": { + "b06ca46466ca": { + "name": "git.status#3", + "ordinal": 14, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"git.status\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" + }, + "b823fdc0d205": { "name": "settings.get#1", - "ordinal": 1, + "ordinal": 2, "args": [ { "name": "method", @@ -584,21 +595,10 @@ } ], "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 3001, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } + "status": "pending", + "startedAt": 0 } }, - "b06ca46466ca": { - "name": "git.status#3", - "ordinal": 14, - "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"git.status\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" - }, "bf019629baab": { "name": "repo.list#1", "ordinal": 7, @@ -673,11 +673,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -686,6 +681,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "f0a6f14b92e4": { "name": "source-control.status-load-success", "ordinal": 20, @@ -699,7 +699,7 @@ "id": "post-write-status", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a", @@ -709,7 +709,7 @@ "a6d51875b1b0" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -734,7 +734,7 @@ "id": "superseded-revalidation-ignored", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a", @@ -744,7 +744,7 @@ "a6d51875b1b0" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -769,7 +769,7 @@ "id": "cleanup", "observation": { "sender": [ - "ade0dae5eee8", + "22bf66c852bb", "962f91336a50", "334b41f87c41", "bf019629baab", @@ -781,7 +781,7 @@ "1a6e003b2d53" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/src/query/host-event-router.test.ts b/mobile/src/query/host-event-router.test.ts new file mode 100644 index 00000000000..e79d112c587 --- /dev/null +++ b/mobile/src/query/host-event-router.test.ts @@ -0,0 +1,166 @@ +import { createElement } from 'react' +import { focusManager, QueryClientProvider, type QueryClient } from '@tanstack/react-query' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { settleQueryNotifications } from '../test-support/rpc-recording/hook-mount' +import { stubRpcClient } from '../transport/rpc/rpc-client-test-stub' +import type { RpcResponse } from '../transport/rpc/rpc-wire-types' +import { useHostEventRouter, useHostEventStreamReady } from './host-event-router' +import { defineHostQuery, useHostQuery } from './host-query' +import { hostQueryKey } from './host-query-key' +import { createOrcaQueryClient } from './orca-query-client' +import { settingsSignal } from './settings-change-signal' + +const NO_INPUT = {} + +const rowsQuery = defineHostQuery({ + family: 'test.rows', + fetch: async (client, _target, _input: typeof NO_INPUT) => { + const reply = await client.sendRequest('test.rows') + return reply.ok ? String(reply.result) : 'refused' + }, + signal: { events: ['worktreesChanged'] } +}) + +let renderer: ReactTestRenderer | null = null + +afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + focusManager.setFocused(undefined) + vi.useRealTimers() +}) + +function desktop() { + let emit: (event: unknown) => void = () => {} + const replies: ((rows: string) => void)[] = [] + const stateListeners = new Set<(state: 'connected' | 'disconnected') => void>() + const client = stubRpcClient({ + getLastConnectedAt: () => 1, + onStateChange: (listener) => { + stateListeners.add(listener) + return () => stateListeners.delete(listener) + }, + subscribe: (_method, _params, onData) => { + emit = onData + return () => {} + }, + sendRequest: () => + new Promise((resolve) => { + replies.push((rows) => resolve({ id: 'r', ok: true, result: rows })) + }) + }) + return { + client, + emit: (event: unknown) => emit(event), + replies, + setState: (state: 'connected' | 'disconnected') => stateListeners.forEach((l) => l(state)) + } +} + +// Holds its answer while the event stream is live, as a settings family on a host with settingsChanged does. +const groupOrderQuery = defineHostQuery({ + family: 'test.settings', + fetch: rowsQuery.fetch, + staleTime: 0, + signal: settingsSignal(['sourceControlGroupOrder']) +}) +const groupOrderKey = hostQueryKey('host-1', groupOrderQuery.family, { exec: 'local' }, NO_INPUT) + +async function mountList( + host: ReturnType, + options: { query?: typeof rowsQuery; queryClient?: QueryClient } = {} +): Promise<() => string | undefined> { + let rows: string | undefined + function List(): null { + useHostEventRouter('host-1', host.client) + const live = useHostEventStreamReady('host-1', host.client) + rows = useHostQuery( + options.query ?? rowsQuery, + { hostId: 'host-1', client: host.client }, + { exec: 'local' }, + NO_INPUT, + { staleTime: options.query === groupOrderQuery && live ? Infinity : undefined } + ).data + return null + } + const queryClient = options.queryClient ?? createOrcaQueryClient() + await act(async () => { + renderer = create( + createElement(QueryClientProvider, { client: queryClient }, createElement(List)) + ) + }) + await settleQueryNotifications() + return () => rows +} + +it('re-reads a settings family only for a settingsChanged naming a setting it reads', async () => { + const host = desktop() + await mountList(host, { query: groupOrderQuery }) + await act(async () => host.replies[0]('changes-first')) + host.emit({ type: 'ready', subscriptionId: 'events-1' }) + + host.emit({ type: 'settingsChanged', keys: ['terminalFontSize'] }) + await settleQueryNotifications() + expect(host.replies).toHaveLength(1) + + host.emit({ type: 'settingsChanged', keys: ['terminalFontSize', 'sourceControlGroupOrder'] }) + await settleQueryNotifications() + expect(host.replies).toHaveLength(2) +}) + +it('reads a settings family again on its next mount, since no stream heard the host meanwhile', async () => { + const host = desktop() + const queryClient = createOrcaQueryClient() + await mountList(host, { query: groupOrderQuery, queryClient }) + await act(async () => host.replies[0]('changes-first')) + host.emit({ type: 'ready', subscriptionId: 'events-1' }) + await act(async () => renderer?.unmount()) + + await mountList(host, { query: groupOrderQuery, queryClient }) + expect(host.replies).toHaveLength(2) +}) + +it('keeps a settings answer stale when the change arrives during a read the page is not watching', async () => { + const host = desktop() + const queryClient = createOrcaQueryClient() + await mountList(host, { query: groupOrderQuery, queryClient }) + await act(async () => host.replies[0]('changes-first')) + host.emit({ type: 'ready', subscriptionId: 'events-1' }) + focusManager.setFocused(false) + void queryClient.refetchQueries({ queryKey: groupOrderKey }) + await settleQueryNotifications() + + host.emit({ type: 'settingsChanged', keys: ['sourceControlGroupOrder'] }) + // This answer was read before the change. + await act(async () => host.replies[1]('changes-first')) + await settleQueryNotifications() + expect(queryClient.getQueryState(groupOrderKey)?.isInvalidated).toBe(true) +}) + +it('reads a settings answer cached before the router started, once its stream is live', async () => { + const host = desktop() + const queryClient = createOrcaQueryClient() + await mountList(host, { query: groupOrderQuery, queryClient }) + await act(async () => host.replies[0]('changes-first')) + host.emit({ type: 'ready', subscriptionId: 'events-1' }) + await act(async () => renderer?.unmount()) + + // Another screen starts the router later; its stream goes live before Changes opens. + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(Date.now() + 60_000) + function Holder(): null { + useHostEventRouter('host-1', host.client) + return null + } + let holder: ReactTestRenderer | null = null + await act(async () => { + holder = create( + createElement(QueryClientProvider, { client: queryClient }, createElement(Holder)) + ) + }) + host.emit({ type: 'ready', subscriptionId: 'events-2' }) + await mountList(host, { query: groupOrderQuery, queryClient }) + expect(host.replies).toHaveLength(2) + act(() => holder?.unmount()) +}) diff --git a/mobile/src/query/host-event-router.ts b/mobile/src/query/host-event-router.ts index 183abafd797..f26fb5f360a 100644 --- a/mobile/src/query/host-event-router.ts +++ b/mobile/src/query/host-event-router.ts @@ -1,4 +1,4 @@ -import { useEffect } from 'react' +import { useCallback, useEffect, useSyncExternalStore } from 'react' import { focusManager, useQueryClient, type Query, type QueryClient } from '@tanstack/react-query' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { @@ -18,23 +18,48 @@ function targetOf(query: Query): HostQueryKey[3] { return (query.queryKey as HostQueryKey)[3] } -const trailingReads = new WeakMap>() +// What to do once a read already out settles: read again, or only mark the answer stale. +type AfterRead = 'refetch' | 'stale' -function trailingReadsOf(queryClient: QueryClient): Set { - const existing = trailingReads.get(queryClient) +const afterReads = new WeakMap>() + +function afterReadsOf(queryClient: QueryClient): Map { + const existing = afterReads.get(queryClient) if (existing) { return existing } - const hashes = new Set() - trailingReads.set(queryClient, hashes) + const pending = new Map() + afterReads.set(queryClient, pending) // One cache listener per world, for as long as the world's client lives. queryClient.getQueryCache().subscribe(({ type, query }) => { - if (type === 'updated' && hashes.has(query.queryHash) && query.state.fetchStatus === 'idle') { - hashes.delete(query.queryHash) - refetchHostQueryAfterInFlight(queryClient, query) + const after = pending.get(query.queryHash) + if (type === 'updated' && after && query.state.fetchStatus === 'idle') { + pending.delete(query.queryHash) + if (after === 'refetch') { + refetchHostQueryAfterInFlight(queryClient, query) + } else { + void markStale(queryClient, query) + } } }) - return hashes + return pending +} + +function markStale(queryClient: QueryClient, query: Query): Promise { + return queryClient.invalidateQueries({ + queryKey: query.queryKey, + exact: true, + refetchType: 'none' + }) +} + +// A read already out may predate the change, and its answer would clear the mark; mark again once it lands. +function markStaleAfterInFlight(queryClient: QueryClient, query: Query): void { + void markStale(queryClient, query) + const pending = afterReadsOf(queryClient) + if (query.state.fetchStatus === 'fetching' && !pending.has(query.queryHash)) { + pending.set(query.queryHash, 'stale') + } } /** @@ -43,7 +68,7 @@ function trailingReadsOf(queryClient: QueryClient): Set { */ export function refetchHostQueryAfterInFlight(queryClient: QueryClient, query: Query): void { if (query.state.fetchStatus === 'fetching') { - trailingReadsOf(queryClient).add(query.queryHash) + afterReadsOf(queryClient).set(query.queryHash, 'refetch') return } void queryClient.refetchQueries( @@ -52,12 +77,28 @@ export function refetchHostQueryAfterInFlight(queryClient: QueryClient, query: Q ) } +type RouterHandle = { + stop: () => void + isReady: () => boolean + onReadyChange: (listener: () => void) => () => void +} + function startHostEventRouter( queryClient: QueryClient, hostId: string, client: RpcClient -): () => void { - // When the stream last said it was live; a replayed ready may have missed events since. +): RouterHandle { + const startedAt = Date.now() + // Whether the stream is live now, i.e. a change on the host would reach this router. + let ready = false + const readyListeners = new Set<() => void>() + const setReady = (next: boolean): void => { + if (next !== ready) { + ready = next + readyListeners.forEach((listener) => listener()) + } + } + // When the stream last said it was live (0: never); a replayed ready may have missed events since. let readyAt = 0 const floorTimers = new Map>() const signalledQueries = (matches: (signal: HostQuerySignal, query: Query) => boolean): Query[] => @@ -68,13 +109,11 @@ function startHostEventRouter( return signal !== undefined && matches(signal, query) } }) - const markStale = (query: Query): Promise => - queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true, refetchType: 'none' }) // Unobserved or hidden: stale only, so the next mount or foreground reads it. const readsNow = (query: Query): boolean => query.isActive() && focusManager.isFocused() const onChange = (query: Query): void => { - void markStale(query) + markStaleAfterInFlight(queryClient, query) if (!readsNow(query) || floorTimers.has(query.queryHash)) { return } @@ -97,10 +136,8 @@ function startHostEventRouter( ) } - const onReplayedReady = (missedSince: number): void => { - // After a reconnect, the connected edge already re-read every observed query; a replay with no reconnect (a path switch) did not. - const connectedAt = client.getLastConnectedAt() ?? 0 - const readSince = connectedAt > missedSince ? connectedAt : Infinity + // Reads again (or marks stale, when no one watches) every answer older than `readSince`. + const catchUp = (readSince: number): void => { for (const query of signalledQueries(() => true)) { if (query.state.fetchStatus === 'fetching' || query.state.dataUpdatedAt >= readSince) { continue @@ -108,22 +145,33 @@ function startHostEventRouter( if (readsNow(query)) { void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }) } else { - void markStale(query) + void markStale(queryClient, query) } } } + const onReplayedReady = (missedSince: number): void => { + // After a reconnect, the connected edge already re-read every observed query; a replay with no reconnect (a path switch) did not. + const connectedAt = client.getLastConnectedAt() ?? 0 + catchUp(connectedAt > missedSince ? connectedAt : Infinity) + } + const onEvent = (event: SharedClientEvent): void => { if (event.type === 'ready') { // Events are not queued while disconnected or between a stream's end and its reopen. if ('replayed' in event) { onReplayedReady(readyAt) + } else if (readyAt === 0) { + // Answers cached before this router started were read while nothing heard the host. + catchUp(startedAt) } readyAt = Date.now() + setReady(true) return } if (event.type === 'end' || event.type === 'error') { // The shared stream opens again by itself; its next ready re-reads what was missed. + setReady(false) return } const signalled: HostSignalEvent = event @@ -136,16 +184,24 @@ function startHostEventRouter( } const stopStream = subscribeSharedClientEvents(client, onEvent) - return () => { - stopStream() - for (const timer of floorTimers.values()) { - clearTimeout(timer) + return { + stop: () => { + stopStream() + for (const timer of floorTimers.values()) { + clearTimeout(timer) + } + floorTimers.clear() + readyListeners.clear() + }, + isReady: () => ready, + onReadyChange: (listener) => { + readyListeners.add(listener) + return () => readyListeners.delete(listener) } - floorTimers.clear() } } -type Router = { holders: number; stop: () => void } +type Router = { holders: number; handle: RouterHandle } const routers = new WeakMap>() @@ -154,7 +210,7 @@ function retainHostEventRouter( queryClient: QueryClient, hostId: string, client: RpcClient -): () => void { +): { handle: RouterHandle; release: () => void } { let byClient = routers.get(queryClient) if (!byClient) { byClient = new Map() @@ -163,25 +219,55 @@ function retainHostEventRouter( const clients = byClient let router = clients.get(client) if (!router) { - router = { holders: 0, stop: startHostEventRouter(queryClient, hostId, client) } + router = { holders: 0, handle: startHostEventRouter(queryClient, hostId, client) } clients.set(client, router) } const held = router held.holders += 1 - return () => { + const release = (): void => { held.holders -= 1 if (held.holders === 0) { - held.stop() + held.handle.stop() clients.delete(client) } } + return { handle: held.handle, release } } /** Keeps the host's event-signalled families (see HostQuery `signal`) fresh while a screen reads them. */ export function useHostEventRouter(hostId: string | undefined, client: RpcClient | null): void { const queryClient = useQueryClient() useEffect( - () => (client && hostId ? retainHostEventRouter(queryClient, hostId, client) : undefined), + () => + client && hostId ? retainHostEventRouter(queryClient, hostId, client).release : undefined, [queryClient, hostId, client] ) } + +/** + * Keeps the host's event router running, like useHostEventRouter, and says whether its event stream + * is live. Only while it is can a family hold its answer until an event marks it stale. + */ +export function useHostEventStreamReady( + hostId: string | undefined, + client: RpcClient | null +): boolean { + const queryClient = useQueryClient() + const subscribe = useCallback( + (onChange: () => void) => { + if (!client || !hostId) { + return () => {} + } + const { handle, release } = retainHostEventRouter(queryClient, hostId, client) + const stopListening = handle.onReadyChange(onChange) + return () => { + stopListening() + release() + } + }, + [queryClient, hostId, client] + ) + return useSyncExternalStore(subscribe, () => + client && hostId ? (routers.get(queryClient)?.get(client)?.handle.isReady() ?? false) : false + ) +} diff --git a/mobile/src/query/host-query.ts b/mobile/src/query/host-query.ts index 8eedacead2d..4d65785430e 100644 --- a/mobile/src/query/host-query.ts +++ b/mobile/src/query/host-query.ts @@ -34,7 +34,7 @@ export type HostQuery = { fetch?: HostQueryFetch staleTime?: StaleTimeFunction gcTime?: number - // Only for families the desktop sends no change signal for. + // Reads a stale answer on foreground: one with no change signal, or one an event marked while hidden. refetchOnWindowFocus?: boolean // For a screen that offers its own Retry, so a lost read is reported instead of sent again. retry?: false @@ -177,7 +177,13 @@ export function useHostQuery( host: { hostId: string; client: RpcClient | null }, target: HostQueryTarget, input: TInput, - options?: { enabled?: boolean; subscribed?: boolean; refetchInterval?: number | false } + options?: { + enabled?: boolean + subscribed?: boolean + refetchInterval?: number | false + // Replaces the family's own, e.g. once the host is known to signal every change. + staleTime?: number + } ): UseQueryResult { const { hostId, client } = host const enabled = client !== null && options?.enabled !== false @@ -194,6 +200,7 @@ export function useHostQuery( }, [query, client, hostId, keyHash, enabled]) return useQuery({ ...queryOptions, + ...(options?.staleTime === undefined ? {} : { staleTime: options.staleTime }), subscribed: options?.subscribed, refetchInterval: options?.refetchInterval }) diff --git a/mobile/src/query/settings-change-signal.ts b/mobile/src/query/settings-change-signal.ts new file mode 100644 index 00000000000..e99fc42c077 --- /dev/null +++ b/mobile/src/query/settings-change-signal.ts @@ -0,0 +1,35 @@ +import { SETTINGS_CHANGED_EVENT_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' +import { useOptionalHostProtocolGates } from '../components/host-protocol-gates-context' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { useRouteRelaysCapability } from '../worktree/workspace-server-context' +import { useHostEventStreamReady } from './host-event-router' +import type { HostQuerySignal } from './host-query' + +/** + * Whether a settings family can hold its answer until a settingsChanged event marks it stale: the + * route's host publishes the event and this page's event stream from it is live. Otherwise (older + * hosts, a stream that ended, screens outside a host route) the family keeps its own rereads. + */ +export function useHostSettingsChangeSignal(hostId: string, client: RpcClient | null): boolean { + const hostCapabilities = useOptionalHostProtocolGates()?.hostCapabilities + const relayed = useRouteRelaysCapability(SETTINGS_CHANGED_EVENT_RUNTIME_CAPABILITY) + const published = + hostCapabilities?.includes(SETTINGS_CHANGED_EVENT_RUNTIME_CAPABILITY) === true && relayed + const streamReady = useHostEventStreamReady( + published ? hostId : undefined, + published ? client : null + ) + return published && streamReady +} + +/** The signal of a family that reads only `keys` of the host's settings. */ +export function settingsSignal(keys: readonly string[]): HostQuerySignal { + return { + events: ['settingsChanged'], + // An event without a key list (malformed) could name anything. + matches: (event) => + event.type !== 'settingsChanged' || + !Array.isArray(event.keys) || + event.keys.some((key) => keys.includes(key)) + } +} diff --git a/mobile/src/session/agent-launch/mobile-agent-launch-queries.ts b/mobile/src/session/agent-launch/mobile-agent-launch-queries.ts index ae3c10c09cf..a4e86c7ec93 100644 --- a/mobile/src/session/agent-launch/mobile-agent-launch-queries.ts +++ b/mobile/src/session/agent-launch/mobile-agent-launch-queries.ts @@ -9,6 +9,7 @@ import { type HostQueryTarget } from '../../query/host-query-key' import { hostReadClient } from '../../query/host-read-client' +import { useHostSettingsChangeSignal } from '../../query/settings-change-signal' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import { newTabSettingsRead } from './mobile-new-tab-settings-operations' import { @@ -75,16 +76,18 @@ export async function refreshDetectedAgents( const NO_INPUT = {} +// The launch reads the whole settings object, so any settingsChanged makes it stale. const newTabSettingsQuery = defineHostQuery({ family: 'settings.newTab', staleTime: 60_000, gcTime: 30 * 60_000, + signal: { events: ['settingsChanged'] }, fetch: async (client, _target, _input: typeof NO_INPUT) => ({ settings: newTabSettingsRead.interpret(await newTabSettingsRead.request(client))() }) }) -// Settings are read again on every sheet open; the cached ones paint meanwhile. +// A host without settingsChanged gets a reread on every sheet open; the cached ones paint meanwhile. export function reloadNewTabSettings( queryClient: QueryClient, hostId: string, @@ -101,6 +104,8 @@ type MobileAgentLaunchQueries = { settings: UseQueryResult<{ settings: unknown }> target: HostQueryTarget input: DetectionInput + // The host tells this page when settings change, so a sheet open need not read them again. + settingsSignalled: boolean } // One agent list per workspace and document, shared by the "+" sheet and the "Fix with" labels. @@ -130,11 +135,13 @@ export function useMobileAgentLaunchQueries(args: { enabled, subscribed: observed(detectedAgentsQuery.family, target, input) }) + const settingsSignalled = useHostSettingsChangeSignal(hostId, client) const settings = useHostQuery(newTabSettingsQuery, { hostId, client }, settingsTarget, NO_INPUT, { enabled, - subscribed: observed(newTabSettingsQuery.family, settingsTarget, NO_INPUT) + subscribed: observed(newTabSettingsQuery.family, settingsTarget, NO_INPUT), + staleTime: settingsSignalled ? Infinity : undefined }) - return { detection, settings, target, input } + return { detection, settings, target, input, settingsSignalled } } export function agentLaunchContextOf({ diff --git a/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.ts b/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.ts index 24fb782b3ec..20636bce0fa 100644 --- a/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.ts +++ b/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.ts @@ -43,7 +43,7 @@ export function useMobileNewTabAgentOptions(args: { const { client, connState, hostId, open } = args const queryClient = useQueryClient() const connected = client !== null && connState === 'connected' - const { detection, settings, target, input } = useMobileAgentLaunchQueries({ + const { detection, settings, target, input, settingsSignalled } = useMobileAgentLaunchQueries({ hostId, client, worktreeId: args.worktreeId, @@ -58,7 +58,9 @@ export function useMobileNewTabAgentOptions(args: { if (!open || !client || connState !== 'connected') { return } - reloadNewTabSettings(queryClient, hostId, target.exec) + if (!settingsSignalled) { + reloadNewTabSettings(queryClient, hostId, target.exec) + } const queryKey = hostQueryKey(hostId, detectedAgentsQuery.family, target, input) const cached = queryClient.getQueryState(queryKey) const refreshed = refreshedThisConnection(client) @@ -92,7 +94,7 @@ export function useMobileNewTabAgentOptions(args: { refreshed.delete(targetKey) } }) - }, [client, connState, hostId, input, mountedAt, open, queryClient, target]) + }, [client, connState, hostId, input, mountedAt, open, queryClient, settingsSignalled, target]) const detected = detection.data const loadState: MobileNewTabAgentLoadState = !connected diff --git a/mobile/src/source-control/mobile-source-control-settings-operations.ts b/mobile/src/source-control/mobile-source-control-settings-operations.ts index 1a4f2afa3ce..7bd2839f597 100644 --- a/mobile/src/source-control/mobile-source-control-settings-operations.ts +++ b/mobile/src/source-control/mobile-source-control-settings-operations.ts @@ -10,6 +10,14 @@ export type MobileSourceControlSettings = { diffShowWhitespace: boolean } +const SOURCE_CONTROL_SETTING = { + groupOrder: 'sourceControlGroupOrder', + compareAgainstUpstream: 'sourceControlCompareAgainstUpstream', + diffShowWhitespace: 'diffShowWhitespace' +} as const + +export const SOURCE_CONTROL_SETTINGS_KEYS: readonly string[] = Object.values(SOURCE_CONTROL_SETTING) + // Older hosts omit these settings; absence reads as desktop's defaults. const sourceControlSettingsReader: RpcCompatibleReader< unknown, @@ -22,9 +30,9 @@ const sourceControlSettingsReader: RpcCompatibleReader< compatible: true, variant: 'source-control-settings', value: { - groupOrder: normalizeSourceControlGroupOrder(field('sourceControlGroupOrder')), - compareAgainstUpstream: field('sourceControlCompareAgainstUpstream') === true, - diffShowWhitespace: field('diffShowWhitespace') === true + groupOrder: normalizeSourceControlGroupOrder(field(SOURCE_CONTROL_SETTING.groupOrder)), + compareAgainstUpstream: field(SOURCE_CONTROL_SETTING.compareAgainstUpstream) === true, + diffShowWhitespace: field(SOURCE_CONTROL_SETTING.diffShowWhitespace) === true }, salvage: { droppedPaths: [], droppedCount: 0 } } diff --git a/mobile/src/source-control/mobile-source-control-settings.ts b/mobile/src/source-control/mobile-source-control-settings.ts index b0bc9b6b326..4355ad1f9eb 100644 --- a/mobile/src/source-control/mobile-source-control-settings.ts +++ b/mobile/src/source-control/mobile-source-control-settings.ts @@ -4,7 +4,9 @@ import { DEFAULT_SOURCE_CONTROL_GROUP_ORDER } from '../../../src/shared/source-c import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host' import { defineHostQuery, useHostQuery } from '../query/host-query' import { hostQueryKey } from '../query/host-query-key' +import { settingsSignal, useHostSettingsChangeSignal } from '../query/settings-change-signal' import { + SOURCE_CONTROL_SETTINGS_KEYS, sourceControlSettingsRead, type MobileSourceControlSettings } from './mobile-source-control-settings-operations' @@ -19,12 +21,13 @@ const DESKTOP_DEFAULTS: MobileSourceControlSettings = { const NO_INPUT = {} -// The desktop sends no settings change signal, so every mount and foreground rereads behind the cached copy. +// A host without settingsChanged gets a reread on every mount and foreground, behind the cached copy. const sourceControlSettingsQuery = defineHostQuery({ family: 'settings.sourceControl', staleTime: 0, refetchOnWindowFocus: true, gcTime: 30 * 60_000, + signal: settingsSignal(SOURCE_CONTROL_SETTINGS_KEYS), fetch: async ( client, _target, @@ -46,12 +49,13 @@ export function useMobileSourceControlSettings( ): { settings: MobileSourceControlSettings; reload: () => void } { const queryClient = useQueryClient() const exec = useWorkspaceExecutionHost() ?? 'local' + const signalled = useHostSettingsChangeSignal(hostId, client) const { data } = useHostQuery( sourceControlSettingsQuery, { hostId, client }, { exec }, NO_INPUT, - { enabled: connState === 'connected' } + { enabled: connState === 'connected', staleTime: signalled ? Infinity : undefined } ) const reload = useCallback(() => { void queryClient.invalidateQueries({ diff --git a/src/main/runtime/client/settings/runtime-settings-change-events.test.ts b/src/main/runtime/client/settings/runtime-settings-change-events.test.ts new file mode 100644 index 00000000000..ddaee15f4b7 --- /dev/null +++ b/src/main/runtime/client/settings/runtime-settings-change-events.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { getDefaultSettings } from '../../../../shared/constants' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import { publishSettingsChanges } from './runtime-settings-change-events' + +type Listener = (updates: Partial, settings: GlobalSettings) => void + +function settingsStore(initial: GlobalSettings) { + let settings = initial + const listeners = new Set() + return { + getSettings: () => settings, + onSettingsChanged: (listener: Listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + // Like the real store: replace the object, then pass listeners what the writer sent. + update: (updates: Partial) => { + settings = { ...settings, ...updates } + for (const listener of listeners) { + listener(updates, settings) + } + } + } +} + +describe('publishSettingsChanges', () => { + it('names only the settings whose values changed', () => { + const store = settingsStore({ + ...getDefaultSettings('/home/me'), + prBotAuthorOverrides: ['renovate'], + diffShowWhitespace: false + }) + const events: RuntimeClientEvent[] = [] + publishSettingsChanges(store, (event) => events.push(event)) + + store.update({ + prBotAuthorOverrides: ['renovate'], + diffShowWhitespace: true + }) + store.update({ diffShowWhitespace: true }) + + expect(events).toEqual([{ type: 'settingsChanged', keys: ['diffShowWhitespace'] }]) + }) +}) diff --git a/src/main/runtime/client/settings/runtime-settings-change-events.ts b/src/main/runtime/client/settings/runtime-settings-change-events.ts new file mode 100644 index 00000000000..37e49ae92f7 --- /dev/null +++ b/src/main/runtime/client/settings/runtime-settings-change-events.ts @@ -0,0 +1,25 @@ +import { isDeepStrictEqual } from 'node:util' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import type { RuntimeStore } from '../../construction/runtime-store-contract' + +/** Tells clients which top-level settings changed, so a phone re-reads only what it shows. */ +export function publishSettingsChanges( + store: Pick | null, + emit: (event: RuntimeClientEvent) => void +): void { + if (!store?.getSettings || !store.onSettingsChanged) { + return + } + let previous = new Map(Object.entries(store.getSettings())) + store.onSettingsChanged((updates, settings) => { + const next = new Map(Object.entries(settings)) + // A writer may resend a value it did not change, as an equal but new object. + const keys = Object.keys(updates).filter( + (key) => !isDeepStrictEqual(previous.get(key), next.get(key)) + ) + previous = next + if (keys.length > 0) { + emit({ type: 'settingsChanged', keys }) + } + }) +} diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 5c30d7579a0..8c28e659ffb 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -3,6 +3,7 @@ import { conversationRecordReader } from './orchestration/addressing/session-lin import type { RuntimeLinearCommandSurface } from './integrations/linear/runtime-linear-command-surface' import { installRuntimeLinearCommandSurface } from './integrations/linear/runtime-linear-command-surface' import { publishNativeChatPreferenceChanges } from './agent-session/launch/runtime-native-chat-preference-events' +import { publishSettingsChanges } from './client/settings/runtime-settings-change-events' import { publishWorkspaceViewChanges } from './sidebar-inputs/runtime-workspace-view-change-events' import { OrcaRuntimeWithSidebarTemporal, @@ -175,6 +176,7 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { registerWorktreeChangeInvalidator((repoId) => this.invalidateWorktreeCatalog(repoId)) publishWorkspaceViewChanges(this.store, (event) => this.emitClientEvent(event)) publishNativeChatPreferenceChanges(this.store, (event) => this.emitClientEvent(event)) + publishSettingsChanges(this.store, (event) => this.emitClientEvent(event)) } private structuredAgentAvailability?: ReturnType diff --git a/src/shared/host-runtime-capabilities.ts b/src/shared/host-runtime-capabilities.ts index debd2b0d710..2469c5f9952 100644 --- a/src/shared/host-runtime-capabilities.ts +++ b/src/shared/host-runtime-capabilities.ts @@ -13,6 +13,9 @@ export const RUNTIME_AUTOMATIC_WORK_RUNTIME_CAPABILITY = 'runtime.automatic-work // Hosts without this capability ignore a request's expectedRuntimeSource; the CLI's pre-send probe // is then the only fence. export const RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY = 'runtime-source-fence.v1' as const +// Hosts with this capability publish settingsChanged, so a client keeps settings until it says otherwise. +export const SETTINGS_CHANGED_EVENT_RUNTIME_CAPABILITY = + 'runtime.settings-changed-event.v1' as const // The paired host itself: status, environments, control, updates and the servers it manages. export const HOST_RUNTIME_CAPABILITIES = [ @@ -24,5 +27,6 @@ export const HOST_RUNTIME_CAPABILITIES = [ MANAGED_RUNTIME_INSTALL_RUNTIME_CAPABILITY, MANAGED_RUNTIME_REMOVE_RUNTIME_CAPABILITY, RUNTIME_SOURCE_FENCE_RUNTIME_CAPABILITY, + SETTINGS_CHANGED_EVENT_RUNTIME_CAPABILITY, SSH_TARGET_MANAGEMENT_RUNTIME_CAPABILITY ] as const diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts index 9ff9664b4c8..0c03f46106d 100644 --- a/src/shared/runtime-client-events.ts +++ b/src/shared/runtime-client-events.ts @@ -25,6 +25,8 @@ export type RuntimeClientEvent = | { type: 'workspaceViewChanged' } // Index, HEAD or refs moved in a watched local repo; without `worktreeIds` any of its checkouts may have changed. | { type: 'gitStatusChanged'; repoId: string; worktreeIds?: string[] } + /** Top-level settings whose values changed; a phone re-reads only the settings it shows. */ + | { type: 'settingsChanged'; keys: string[] } | { type: 'worktreesChanged' repoId: string From 4e70998609c50b5656ab13632016578536bce199 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sun, 8 Nov 2026 11:23:56 -0800 Subject: [PATCH 04/23] test: remove 8 low-value test cases (#39934) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- config/reliability-gates.jsonc | 35 ++++++----- .../src/components/AgentLaunchNotice.test.tsx | 62 ------------------- .../mobile-new-tab-agent-options.test.ts | 9 +-- ...obile-native-chat-image-attachment.test.ts | 30 --------- .../session/tabs/active-session-tab.test.ts | 34 ---------- .../branches/BranchPicker.test.tsx | 35 ----------- 6 files changed, 21 insertions(+), 184 deletions(-) delete mode 100644 mobile/src/components/AgentLaunchNotice.test.tsx diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index e8637632070..fee52a30d05 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -4235,10 +4235,10 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", "motivatingLinks": ["tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts"], "invariant": "Every renderer-held runtime subscription receives exactly one terminal close event when its transport is retired, including when the retirement advanced the transport generation first, and a single failing teardown never abandons that environment's remaining subscriptions nor escapes into the transport that reported the close. Payload frames from a retired transport stay suppressed. A revealed remote terminal therefore reattaches over a live multiplex connection: its buffer restores, typed input reaches the host PTY, the echo paints without a tab flip, and the PTY converges on the revealed pane grid.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -4321,7 +4321,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed." ], "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." }, @@ -8591,13 +8592,13 @@ "providers": ["paired-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8652", "https://github.com/stablyai/orca/pull/10625" ], "invariant": "A host advertising terminal.paired-parking.v1 keeps the PTY and bounded authoritative history alive while an ordinary hidden-view park destroys the client xterm and releases its raw per-PTY stream. Reveal must restore up to the requested 5,000 rows, parked-time side effects/output, the same PTY identity, and continued input/output. Parked watcher synchronization compares parking semantics rather than fresh object identity, owns setup and cleanup across StrictMode replay, reconciles real PTY/layout changes, and performs no terminal-state scan when nothing is parked. After a host main-process relaunch, unknown local delivery-sync state must not be treated as proof that a surviving daemon PTY is already foregrounded. An empty headed session-tab inventory is authoritative only after the current renderer graph generation publishes a complete inventory and every execution host answers the PTY census; unpublished, resync-pending, transport-failed, and partially scoped inventories remain unverifiable, while genuinely authoritative empty and non-empty inventories settle and a scope-less legacy empty keeps its pre-authority best-effort settle so outdated hosts retain agent auto-resume. The unpublished-empty regression must keep the resume dispatch parked with exactly one daemon process/writer; restoring unconditional empty hydration must release one dispatch and create two live writers. If subscription precedes provider readiness, authoritative inventory must reconsider that existing subscriber without spawning, resizing, or changing reconnect state. A snapshot without an output high-water must keep it unknown rather than borrowing a layout version that can suppress newer live output. Hosts without the capability must gate hidden raw output before xterm scheduling and repaint from the authoritative snapshot on reveal while retaining the existing limit/TTL force-parking fallback. After the first semantic title state, decorative spinner frequency must add zero paired client-event frames and zero full session-tabs work between status-freshness leases regardless of hidden worktree count. Continuous working or permission evidence may refresh each affected worktree once per 15 minutes through one globally spaced FIFO so current and legacy viewers do not decay before 30 minutes; sibling PTYs share that worktree refresh, while local title animation, raw output, and semantic title, status, bell, completion, and query facts remain intact. A paired terminal stream whose delivery credits stop progressing must replace only that stream; command silence first probes authoritative state and replaces the stream if the probe times out or proves the PTY advanced beyond the client's delivered output sequence. When no comparable delivery high-water exists, the first sequenced probe establishes a baseline and only later advancement proves staleness. A same-sequence snapshot remains valid proof of a responsive silent command. A successful status probe may replace a pre-ready shared-control socket without rejecting or duplicating calls already waiting for that transport. Manual disconnect must retain pairing while preventing queued or passive calls and subscriptions from recreating transport until explicit Connect. A paired pane reconnecting to a relaunched host that has not yet published its window graph (an unpublished frame, bare or client-projected) must stay in recovery rather than retire, and the host's first published snapshot carrying the surface must reattach it; a published frame lacking the surface still retires it. The placeholder is only ever sent before the host's graph first publishes; afterwards a worktree with no tabs gets a real empty answer, pushed once to any client that asked during startup, so a paired client opening a never-opened host worktree still gets its first terminal.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -9067,7 +9068,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed." ], "demotionRule": "Keep experimental or demote to protection none if decorative title frequency changes paired client-event or session-tabs publication volume after convergence, a semantic fact is dropped, paired first paint is blank, passive work reconnects after manual disconnect, a capable hidden paired manager survives ordinary parking, a legacy hidden pane schedules raw xterm output or bypasses its fallback, reveal loses requested bounded history or live PTY identity, retained buffer cells do not fall, or either headed/headless scenario flakes." }, @@ -9245,7 +9247,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["ssh"], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6836", "https://github.com/stablyai/orca/pull/6858", @@ -9253,7 +9255,7 @@ "https://github.com/stablyai/orca/pull/7054" ], "invariant": "High-volume terminal output must stay bounded across daemon socket writes, SSH relay writer/decoder/source retention/reconnect, main model and projection admission, runtime metadata, detectors, and tail checks, main-to-renderer in-flight bytes, renderer scheduler queues, and hidden-output restore without starving focused input. Every new SSH session offers V1 and every same-build relay supports it; legacy delivery is reachable only when capability negotiation proves the peer cannot use V1. Negotiated SSH spans remain exact and contiguous through activation, exit, cancellation, recovery, desktop projection, and required remote replacement; provisional activation data cannot project, reconnect may release it only into the exact attempt's private recovery quarantine after contract validation, and exit seals that quarantine against later same-token frames until ordered admission or exact cancellation proof. Reconnect checkpoint capture freezes exact provider-generation/PTy admission, cancels queued old work, and waits for the running raw completion before exposing its accepted checkpoint; timeout or failure detaches only that PTy's old model, makes the checkpoint unavailable, and releases the bounded fence without closing the shared provider, while the same failure outside an active exact migration remains generation-fatal and overlapping reconnects preserve any earlier outstanding fence. Pending renderer projection IDs are capped and compacted across split remainders, exit preparation owns its renderer fence through finalization, exit-time cancellation transfers published projections before proof commit, generation close fences late proof while draining exact projection waiters, closed-generation identity compacts without weakening stale rejection, canceled source-delivery retirement retains at most one ordered token per PTY, and pause/resume targets only the exact provider generation. Additional subscribers cannot stall the owner, while the required legacy primary retains backpressure.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", @@ -9405,7 +9407,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed." ], "demotionRule": "Cannot promote without metric artifacts and bounded-byte assertions." }, @@ -12835,14 +12838,14 @@ "providers": ["local", "remote-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "remote-runtime", "ssh"], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/5308", "https://github.com/stablyai/orca/issues/7547", "https://github.com/stablyai/orca/issues/8212" ], "invariant": "Local runtime and SSH relay roots share one watcher child per host process while healthy and use at most four quarantine children after shard failure; native desktop, paired-runtime, and direct WSL snapshot children consume the same process-wide eight-child reservation and retry transient exhaustion without permanently disabling a root. Cancellation remains owned by its child generation and settles only after acknowledgement or bounded physical exit; paired-web retains cleanup ownership and can cancel before readiness even while capacity is exhausted, retries a failed unwatch after already-resolved or late physical exit without duplicating stream termination, replacements never overlap a still-retiring generation, and aborted or timed-out callers detach immediately even while queued behind same-root relay teardown. Destructive local and SSH cleanup holds one containment-aware watcher/terminal removal fence through descendant watcher and PTY physical exit plus parent Git/filesystem deletion; daemon and relay kill requests retain ownership until the actual subprocess exit callback or an equivalent positive dead-PID proof and propagate rejected signals or a bounded failure otherwise. A crash-fused shared shard moves affected roots into the bounded quarantine pool, a second fused quarantine ends those watch lifetimes, interrupted setup emits overflow after recovery, metadata work stays bounded, and the SSH relay, PTYs, Git, and other filesystem operations never load the watcher native addon or share its fault boundary.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", @@ -13258,7 +13261,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed." ], "demotionRule": "Demote or quarantine if the fault harness flakes without a product or harness bug, if healthy operation exceeds one runtime watcher child, if total physical operation exceeds eight children including retiring generations, if quarantine children outlive their roots or repeat after fusing, if event delivery becomes unbounded, or if metadata/stat work returns to the serve process." }, @@ -14502,10 +14506,10 @@ "providers": ["paired-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": ["paired-runtime"], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/34069063016"], "invariant": "A paired client and host without client-hosted browser capabilities retain server-hosted browser placement across supported version skew.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", "commands": [ "gh workflow run packaged-browser-e2e.yml", "pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0", @@ -14569,7 +14573,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed." ], "demotionRule": "Keep experimental if any direction skips or fails; do not extend timeouts or retry to green." }, diff --git a/mobile/src/components/AgentLaunchNotice.test.tsx b/mobile/src/components/AgentLaunchNotice.test.tsx deleted file mode 100644 index 90305675274..00000000000 --- a/mobile/src/components/AgentLaunchNotice.test.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('react-native', async () => { - const React = await import('react') - return { - Pressable: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Pressable', props, children), - Text: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Text', props, children), - View: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('View', props, children), - StyleSheet: { create: (styles: unknown) => styles } - } -}) -vi.mock('../platform/clipboard', () => ({ - useClipboardWriter: () => ({ writeText: async () => {} }) -})) - -import { AgentLaunchNotice } from './AgentLaunchNotice' - -import type { MobileAgentLaunchAvailability } from '../session/agent-launch/mobile-agent-launch-availability' - -const ERROR_STYLE = { color: 'red' } - -describe('AgentLaunchNotice', () => { - let renderer: ReactTestRenderer | null = null - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - function lines(props: { - availability?: MobileAgentLaunchAvailability - success?: string | null - error?: string | null - warning?: string | null - }): { text: string; isError: boolean }[] { - act(() => { - renderer = create( - createElement(AgentLaunchNotice, { - availability: props.availability ?? 'available', - success: props.success ?? null, - error: props.error ?? null, - warning: props.warning ?? null, - undeliveredPrompt: null, - errorStyle: ERROR_STYLE - }) - ) - }) - return (renderer?.root.findAll((node) => String(node.type) === 'Text') ?? []).map((node) => ({ - text: String(node.props.children), - isError: node.props.style === ERROR_STYLE - })) - } - - it('renders nothing with nothing to say', () => { - expect(lines({})).toEqual([]) - }) -}) diff --git a/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts b/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts index 7a30d81b68b..639e76e1828 100644 --- a/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts +++ b/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts @@ -1,9 +1,6 @@ import { describe, expect, it } from 'vitest' -import { - buildMobileNewTabAgentOptions, - orderMobileNewTabAgents -} from './mobile-new-tab-agent-options' +import { orderMobileNewTabAgents } from './mobile-new-tab-agent-options' describe('mobile new-tab agent options', () => { it('orders the enabled detected default first', () => { @@ -12,8 +9,4 @@ describe('mobile new-tab agent options', () => { 'claude' ]) }) - - it('does not show stale presets while detection is pending', () => { - expect(buildMobileNewTabAgentOptions({ defaultTuiAgent: 'codex' }, null)).toEqual([]) - }) }) diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts index 32b623f8481..e296b975b2c 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts @@ -85,34 +85,4 @@ describe('uploadMobileNativeChatImages', () => { 'uploaded:file:///c.jpg' ]) }) - - it('returns an empty array when the picker is cancelled and uploads nothing', async () => { - const client = clientWithResponses([]) - - const result = await uploadMobileNativeChatImages('library', { - client, - getConnectionId: async () => null, - pickImages: vi.fn().mockResolvedValue([]) - }) - - expect(result).toEqual([]) - expect(client.calls).toEqual([]) - }) - - it('falls back to an inline data uri for the preview when the picker omits a uri', async () => { - const client = clientWithResponses([methodNotFound('start'), ok('save', '/tmp/x.png')]) - - const result = await uploadMobileNativeChatImages('files', { - client, - getConnectionId: async () => null, - pickImages: vi.fn().mockResolvedValue([{ base64: 'BBBB' }]) - }) - - expect(result).toEqual([ - { - path: '/tmp/x.png', - previewUri: 'data:image/png;base64,BBBB' - } - ]) - }) }) diff --git a/mobile/src/session/tabs/active-session-tab.test.ts b/mobile/src/session/tabs/active-session-tab.test.ts index e1749467b33..a76e257be33 100644 --- a/mobile/src/session/tabs/active-session-tab.test.ts +++ b/mobile/src/session/tabs/active-session-tab.test.ts @@ -108,38 +108,4 @@ describe('resolveActiveSessionTab', () => { expect(result.activeTab?.id).toBe('agent') expect(result.clearPendingActiveSessionTabId).toBe(true) }) - - it('uses the snapshot when the device has no pick yet', () => { - const result = resolveActiveSessionTab( - [terminalTab('agent', false), browserTab('browser', true)], - { - pendingActiveSessionTabId: null, - selectedSessionTabId: null - } - ) - - expect(result.activeTab?.id).toBe('browser') - expect(result.selectionSource).toBe('snapshot') - }) - - it('opens the chat a create-worktree launch landed on, over the workspace shell', () => { - // A just-created route has no local pick; the host’s launch activation must open its chat. - const result = resolveActiveSessionTab( - [ - { id: 'shell', type: 'terminal', isActive: false }, - { id: 'agent-session:s-1', type: 'agent-session', isActive: true } - ], - { pendingActiveSessionTabId: null, selectedSessionTabId: null } - ) - - expect(result.activeTab?.id).toBe('agent-session:s-1') - expect(result.selectionSource).toBe('snapshot') - }) - - it('returns null for an empty snapshot', () => { - expect( - resolveActiveSessionTab([], { pendingActiveSessionTabId: null, selectedSessionTabId: 'x' }) - .activeTab - ).toBeNull() - }) }) diff --git a/src/renderer/src/components/right-sidebar/source-control/branches/BranchPicker.test.tsx b/src/renderer/src/components/right-sidebar/source-control/branches/BranchPicker.test.tsx index c062266d929..b5654a4f463 100644 --- a/src/renderer/src/components/right-sidebar/source-control/branches/BranchPicker.test.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/branches/BranchPicker.test.tsx @@ -201,38 +201,3 @@ it('delivers the original workspace outcome after the picker unmounts', async () await act(async () => finish?.({ ok: true, branch: 'feature', warning: 'Files left behind.' })) expect(onSwitched).toHaveBeenCalledWith('Files left behind.') }) - -it('reports the picker closing itself after a switch so the next open reads status again', async () => { - vi.mocked(listRuntimeGitBranches).mockResolvedValue({ - current: 'main', - branches: ['main', 'feature'] - }) - vi.mocked(searchRuntimeRemoteBranches).mockResolvedValue({ refs: [], truncated: false }) - vi.mocked(switchRuntimeGitBranch).mockResolvedValueOnce({ ok: true, branch: 'feature' }) - const onOpenChange = vi.fn() - await act(async () => - root.render( - - ) - ) - await act(async () => container.querySelector('button')?.click()) - expect(onOpenChange).toHaveBeenLastCalledWith(true) - await act(async () => - Array.from(container.querySelectorAll('button')) - .find((button) => button.textContent === 'feature') - ?.click() - ) - expect(onOpenChange).toHaveBeenLastCalledWith(false) -}) From e1a20be7ad934e3828e0db189bc04dccdebe38b1 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sun, 8 Nov 2026 11:26:44 -0800 Subject: [PATCH 05/23] test: remove 8 low-value mobile test cases (#39939) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- ...connection-diagnostics-screen-data.test.ts | 10 +--- .../markdown-floating-actions-layout.test.ts | 52 ------------------- .../bridge/bridge-envelope.test.ts | 22 -------- 3 files changed, 1 insertion(+), 83 deletions(-) delete mode 100644 mobile/src/files/session-documents/markdown-floating-actions-layout.test.ts diff --git a/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts b/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts index fd988ad7b72..3a895518657 100644 --- a/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts +++ b/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts @@ -1,8 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - resolveDiagnosticsHostId, - selectDiagnosticsHostId -} from './connection-diagnostics-screen-data' +import { resolveDiagnosticsHostId } from './connection-diagnostics-screen-data' import type { HostProfile } from '../transport/hosts/host-profile' @@ -16,11 +13,6 @@ const host = (id: string): HostProfile => ({ }) describe('connection diagnostics screen data', () => { - it('prefers a valid route host when navigation changes', () => { - expect(selectDiagnosticsHostId([host('a'), host('b')], 'b', 'a')).toBe('b') - expect(selectDiagnosticsHostId([host('a')], 'missing', 'missing')).toBe('a') - }) - it('applies route changes synchronously without discarding a chip choice for the same route', () => { const hosts = [host('a'), host('b')] expect(resolveDiagnosticsHostId(hosts, undefined, null)).toBe('a') diff --git a/mobile/src/files/session-documents/markdown-floating-actions-layout.test.ts b/mobile/src/files/session-documents/markdown-floating-actions-layout.test.ts deleted file mode 100644 index a4e139acc2f..00000000000 --- a/mobile/src/files/session-documents/markdown-floating-actions-layout.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveMarkdownFloatingActionsBottom, - shouldShowMarkdownFloatingActions -} from './markdown-floating-actions-layout' - -describe('resolveMarkdownFloatingActionsBottom', () => { - it('keeps markdown actions at their resting bottom when the keyboard is closed', () => { - expect( - resolveMarkdownFloatingActionsBottom({ - keyboardLift: 0, - restingBottom: 16, - liftedClearance: 12 - }) - ).toBe(16) - }) - - it('raises markdown actions above the keyboard with clearance', () => { - expect( - resolveMarkdownFloatingActionsBottom({ - keyboardLift: 291, - restingBottom: 16, - liftedClearance: 12 - }) - ).toBe(303) - }) -}) - -describe('shouldShowMarkdownFloatingActions', () => { - const idle = { - keyboardLift: 0, - hasStatus: false, - showRefresh: false, - showCopy: false, - showSave: false - } - - it('shows the floating row for keyboard dismissal without document actions', () => { - expect(shouldShowMarkdownFloatingActions({ ...idle, keyboardLift: 291 })).toBe(true) - }) - - it('hides the floating row on a clean document with the keyboard closed', () => { - expect(shouldShowMarkdownFloatingActions(idle)).toBe(false) - }) - - it.each(['hasStatus', 'showRefresh', 'showCopy', 'showSave'] as const)( - 'shows the floating row for %s alone', - (field) => { - expect(shouldShowMarkdownFloatingActions({ ...idle, [field]: true })).toBe(true) - } - ) -}) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts index 32deb95c0b9..160a2128909 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts @@ -1,7 +1,5 @@ import { describe, expect, it } from 'vitest' -import { BRIDGE_MAX_MESSAGE_BYTES } from './bridge-caps' - import { BRIDGE_PROTOCOL_VERSION, readBridgeClientMessage, @@ -29,12 +27,6 @@ function client(fields: Record): Record { return { v: BRIDGE_PROTOCOL_VERSION, ...fields } } -describe('client messages', () => { - it('carries the frame refusal through rather than relabelling it', () => { - expect(readBridgeClientMessage('{')).toEqual({ ok: false, refusal: 'malformed-json' }) - }) -}) - describe('the readers bound their two directions differently', () => { const records = Array.from({ length: 5_000 }, (_, index) => ({ id: index, @@ -63,20 +55,6 @@ describe('the readers bound their two directions differently', () => { readClient(client({ type: 'request', id: ID, method: 'worktree.list', params: { records } })) ).toEqual({ ok: false, refusal: 'too-many-nodes' }) }) - - it('still refuses a host frame one byte over the frame cap', () => { - const envelope = (result: string) => - JSON.stringify({ - v: BRIDGE_PROTOCOL_VERSION, - type: 'reply', - id: ID, - payload: { ...SUCCESS_PAYLOAD, result } - }) - const overhead = new TextEncoder().encode(envelope('')).byteLength - const raw = envelope('x'.repeat(BRIDGE_MAX_MESSAGE_BYTES + 1 - overhead)) - expect(new TextEncoder().encode(raw).byteLength).toBe(BRIDGE_MAX_MESSAGE_BYTES + 1) - expect(readBridgeHostMessage(raw)).toEqual({ ok: false, refusal: 'oversized' }) - }) }) // Pathnames and returned navigation hrefs share one segment rule; disagreement would expose a path through notify. From 9abd095d080b3e16d4f30e6fb6ba2fbfd1902357 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:30:27 +0000 Subject: [PATCH 06/23] feat(agents): send paired phones the desktop Agents list's verdict per agent (#39243) While a phone is paired, the desktop window publishes its own Agents-list classification for each pane (listed, status, unread, clearable, title, worker parent) and worktree.ps attaches it to each agent row, so the phone lists agents exactly as the sidebar does. agentActivity.setRead/clear apply through the sidebar's own Activity actions and resolve once the new verdicts are stored. --- .../events/runtime-notifier-contract.ts | 6 + .../runtime/client/runtime-client-state.ts | 28 ++++ .../rpc/methods/rpc-method-registry.ts | 2 + .../workspaces/agent-activity-methods.ts | 30 ++++ .../runtime-rpc-mobile-method-routing.ts | 3 + ...ntime-worktree-agent-rows-activity.test.ts | 110 ++++++++++++++ .../runtime-worktree-agent-rows.ts | 23 +++ .../workspace-process-listing.ts | 3 +- src/main/window/agent-pane-activity-relay.ts | 29 ++++ .../main-window-service-stubs.test-fixture.ts | 6 +- src/main/window/renderer-reply-request.ts | 65 +++++++++ src/main/window/runtime-window-lifecycle.ts | 23 +++ src/main/window/terminal-pane-reveal-relay.ts | 71 ++-------- src/preload/api/agent-status-api.ts | 3 + src/preload/api/agent-status-bridge.ts | 4 + ...ui-bridge-clipboard-and-window-controls.ts | 13 ++ src/preload/api/ui-command-event-api.ts | 6 + .../src/app-shell/AppBackgroundServices.tsx | 13 ++ src/renderer/src/components/AgentStateDot.tsx | 18 +-- .../activity/activity-paired-client-change.ts | 37 +++++ .../activity/activity-thread-child-agent.ts | 19 ++- .../activity/activity-thread-grouping.ts | 22 +-- .../activity/agent-list-verdict-publisher.ts | 134 ++++++++++++++++++ .../use-agent-pane-thread-store-data.ts | 16 ++- .../activity/use-agent-pane-threads.ts | 126 ++++++++-------- ...vents-agent-status-window-test-fixtures.ts | 1 + .../ipc-events-close-routing-test-harness.ts | 1 + .../agent-pane-activity-ipc-bridge.ts | 19 +++ .../ipc-events/app-lifetime-ipc-bridge.ts | 2 + ...eIpcEvents-cli-worktree-activation.test.ts | 2 + ...Events-close-routing-browser-pages.test.ts | 3 + ...seIpcEvents-ssh-disconnect-cleanup.test.ts | 1 + .../src/web/preload-api/web-ui-api.ts | 2 + .../presentation/agent-list-status.ts | 68 +++++++++ src/shared/host-operation-ownership.ts | 1 + .../rpc-contract/agent-activity-params.ts | 11 ++ .../rpc-params-catalog.generated.ts | 3 + src/shared/runtime-client-events.ts | 2 + src/shared/runtime-worktree-contracts.ts | 3 + 39 files changed, 769 insertions(+), 160 deletions(-) create mode 100644 src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts create mode 100644 src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts create mode 100644 src/main/window/agent-pane-activity-relay.ts create mode 100644 src/main/window/renderer-reply-request.ts create mode 100644 src/renderer/src/components/activity/activity-paired-client-change.ts create mode 100644 src/renderer/src/components/activity/agent-list-verdict-publisher.ts create mode 100644 src/renderer/src/hooks/ipc-events/agent-pane-activity-ipc-bridge.ts create mode 100644 src/shared/agent-status/presentation/agent-list-status.ts create mode 100644 src/shared/rpc-contract/agent-activity-params.ts diff --git a/src/main/runtime/client/events/runtime-notifier-contract.ts b/src/main/runtime/client/events/runtime-notifier-contract.ts index 910e00ed84a..a39b6216384 100644 --- a/src/main/runtime/client/events/runtime-notifier-contract.ts +++ b/src/main/runtime/client/events/runtime-notifier-contract.ts @@ -34,6 +34,10 @@ import type { RuntimeTerminalDriverState } from '../../../../shared/runtime-session-contracts' import type { RuntimeTerminalPresentation } from '../../../../shared/runtime-terminal-contracts' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../../shared/agent-status/presentation/agent-list-status' type DriverState = RuntimeTerminalDriverState @@ -174,6 +178,8 @@ export type RuntimeNotifier = { workspaceSleepChanged?(notice: WorkspaceSleepNotice): void // Only the host renderer owns slept-agent wake records; phones request navigation-free wake through this optional bridge. resumeSleepingAgents?(worktreeId: string): void + /** The window applies a client's Agents-list change with its own actions and answers with the verdicts it leaves. */ + applyAgentPaneActivity?(change: AgentPaneActivityChange): Promise terminalFitOverrideChanged( ptyId: string, mode: 'mobile-fit' | 'remote-desktop-fit' | 'desktop-fit', diff --git a/src/main/runtime/client/runtime-client-state.ts b/src/main/runtime/client/runtime-client-state.ts index 323c1b20c2d..d2e6570e368 100644 --- a/src/main/runtime/client/runtime-client-state.ts +++ b/src/main/runtime/client/runtime-client-state.ts @@ -17,6 +17,11 @@ import { killAllProcessesForWorktree } from '../workspaces/removal/worktree-tear import type { MemorySnapshot, StatsSummary } from '../../../shared/process-stats-types' import { collectMemorySnapshot } from '../../memory/collector' import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +import { isDeepStrictEqual } from 'node:util' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../shared/agent-status/presentation/agent-list-status' import type { FeatureInteractionId } from '../../../shared/feature-interaction-catalog' import type { RuntimeClientSettingsUpdate } from './settings/runtime-client-settings-shape' import type { AgentLaunchSettingsMutation } from '../../../shared/agent-launch/choices/agent-launch-settings' @@ -190,6 +195,29 @@ export abstract class OrcaRuntimeWithPtyForegroundProcessReads extends OrcaRunti return this.store.getUI() } + /** The live desktop window's Agents-list verdicts; null with no window, so worktree.ps claims none. */ + private agentListPublication: AgentListPublication | null = null + + readAgentListPublication(): AgentListPublication | null { + return this.agentListPublication + } + + setAgentListPublication(next: AgentListPublication | null): void { + const changed = !isDeepStrictEqual(this.agentListPublication?.verdicts, next?.verdicts) + this.agentListPublication = next + if (changed) { + this.emitClientEvent({ type: 'agentListChanged' }) + } + } + + /** Applies through the window's own Activity actions and keeps the verdicts it answers with, so the next worktree.ps already shows them. */ + async applyAgentPaneActivity(change: AgentPaneActivityChange): Promise { + if (!this.notifier?.applyAgentPaneActivity) { + throw new Error('agent_activity_needs_desktop_window') + } + this.setAgentListPublication(await this.notifier.applyAgentPaneActivity(change)) + } + recordFeatureInteraction(id: FeatureInteractionId): PersistedUIState { if (!this.store?.recordFeatureInteraction) { throw new Error('runtime_unavailable') diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index bc707050b33..79858ee663a 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -7,6 +7,7 @@ import { AI_VAULT_METHODS } from './history/ai-vault' import { AUTOMATION_METHODS } from './automations/automations' import { REPO_METHODS } from './projects/repo' import { WORKTREE_METHODS } from './workspaces/worktree' +import { AGENT_ACTIVITY_METHODS } from './workspaces/agent-activity-methods' import { REFERENCE_METHODS } from './reference/reference' import { TERMINAL_METHODS } from './terminal/terminal' import { TERMINAL_ORPHAN_METHODS } from './terminal/terminal-orphan' @@ -92,6 +93,7 @@ export const ALL_RPC_METHODS = [ ...AUTOMATION_METHODS, ...REPO_METHODS, ...WORKTREE_METHODS, + ...AGENT_ACTIVITY_METHODS, ...REFERENCE_METHODS, ...AGENT_SESSION_METHODS, ...STRUCTURED_AGENT_SESSION_METHODS, diff --git a/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts b/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts new file mode 100644 index 00000000000..24cfcf523b6 --- /dev/null +++ b/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts @@ -0,0 +1,30 @@ +import { defineMethod } from '../../core' +import { + AgentActivityClearParams, + AgentActivitySetReadParams +} from '../../../../../shared/rpc-contract/agent-activity-params' + +// Desktop Agents-list read and clear for paired clients; the next worktree.ps already reflects them. +export const AGENT_ACTIVITY_METHODS = [ + defineMethod({ + name: 'agentActivity.setRead', + permission: 'workspace', + params: AgentActivitySetReadParams, + handler: async (params, { runtime }) => { + await runtime.applyAgentPaneActivity({ + kind: params.read ? 'read' : 'unread', + paneKeys: params.paneKeys + }) + return { applied: true } + } + }), + defineMethod({ + name: 'agentActivity.clear', + permission: 'workspace', + params: AgentActivityClearParams, + handler: async (params, { runtime }) => { + await runtime.applyAgentPaneActivity({ kind: 'clear', paneKeys: params.paneKeys }) + return { applied: true } + } + }) +] diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts index dfe15ee9d1a..937d3cf7482 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts @@ -11,6 +11,9 @@ export const EXECUTION_HOST_METHODS = [ 'ui.mutateJiraSavedFilters', 'agent.launch', 'agent.launchReplay', + // Read state lives with the host whose worktree.ps reports it. + 'agentActivity.clear', + 'agentActivity.setRead', 'agentTeams.prepareLaunch', 'agentTeams.tmuxCompat', 'automation.list', diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts new file mode 100644 index 00000000000..d19b986cee9 --- /dev/null +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest' +import type { AgentListPublication } from '../../../../shared/agent-status/presentation/agent-list-status' +import type { RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' +import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' +import type { RuntimeWorktreeAgentSource } from './runtime-worktree-agent-source' + +const WORKTREE_ID = 'repo::/work/tree' +const PUBLISHED_AT = 1_800_000_000_000 + +function source(paneKey: string, updatedAt: number): RuntimeWorktreeAgentSource { + return { + paneKey, + worktreeId: WORKTREE_ID, + connectionId: null, + state: 'done', + agentType: 'claude', + prompt: 'fix it', + lastAssistantMessage: null, + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: updatedAt, + updatedAt + } +} + +function listAgents(agentList: AgentListPublication | null) { + const summary: RuntimeWorktreePsSummary = { + worktreeId: WORKTREE_ID, + repoId: 'repo', + repo: 'repo', + path: '/work/tree', + branch: 'main', + isArchived: false, + isMainWorktree: false, + hasHostSidebarActivity: false, + parentWorktreeId: null, + childWorktreeIds: [], + displayName: 'tree', + workspaceStatus: '', + sortOrder: 0, + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + comment: '', + isPinned: false, + isActive: false, + unread: false, + liveTerminalCount: 0, + hasAttachedPty: false, + lastOutputAt: null, + preview: '', + status: 'inactive', + agents: [] + } + const summaries = new Map([[WORKTREE_ID, summary]]) + attachRuntimeWorktreeAgentRows({ + summaries, + rowSources: new Map( + [ + source('tab-1:listed', PUBLISHED_AT - 3), + source('tab-1:session-start', PUBLISHED_AT - 2), + source('tab-1:unknown-old', PUBLISHED_AT - 1), + source('tab-1:unknown-new', PUBLISHED_AT + 1) + ].map((row) => [row.paneKey, row]) + ), + terminalTitleEvidenceByRow: new Map(), + orchestrationByPaneKey: null, + getSummary: (id) => summaries.get(id) ?? null, + agentList + }) + return Object.fromEntries((summary.agents ?? []).map((row) => [row.paneKey, row.activity])) +} + +describe('worktree.ps agent rows and the desktop Agents list', () => { + it('carries each pane’s verdict and holds back only turns newer than the verdicts', () => { + const listed = { + listed: true, + status: 'done', + unread: true, + clearable: true, + sortAt: PUBLISHED_AT - 3, + title: 'Fix the build', + childOf: 'tab-0:coordinator', + foldedChild: true + } as const + expect( + listAgents({ + publishedAt: PUBLISHED_AT, + verdicts: { 'tab-1:listed': listed, 'tab-1:session-start': { listed: false } } + }) + ).toEqual({ + 'tab-1:listed': listed, + 'tab-1:session-start': { listed: false }, + 'tab-1:unknown-old': { listed: false }, + 'tab-1:unknown-new': undefined + }) + }) + + it('claims no verdict when no desktop window has published one', () => { + expect(listAgents(null)).toEqual({ + 'tab-1:listed': undefined, + 'tab-1:session-start': undefined, + 'tab-1:unknown-old': undefined, + 'tab-1:unknown-new': undefined + }) + }) +}) diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts index a306fd80fad..f3ec79e8fcb 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts @@ -7,6 +7,10 @@ import type { RuntimeWorktreeAgentRow, RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' +import type { + AgentListPublication, + AgentListVerdict +} from '../../../../shared/agent-status/presentation/agent-list-status' import { mergeWorktreeSummaryStatus } from './runtime-worktree-status-projection' import { resolveRuntimeWorktreeSidebarStatus, @@ -25,6 +29,19 @@ type OrchestrationDisplay = { parentPaneKey?: string | null } +const UNLISTED: AgentListVerdict = { listed: false } + +/** A pane the window gave no verdict is not in its list, unless it changed after the window last looked. */ +function agentListVerdict( + agentList: AgentListPublication, + source: RuntimeWorktreeAgentSource +): AgentListVerdict | undefined { + return ( + agentList.verdicts[source.paneKey] ?? + (source.updatedAt > agentList.publishedAt ? undefined : UNLISTED) + ) +} + export function attachRuntimeWorktreeAgentRows(args: { summaries: Map rowSources: ReadonlyMap @@ -35,6 +52,8 @@ export function attachRuntimeWorktreeAgentRows(args: { orchestrationByPaneKey: Record | null | undefined getSummary: RuntimeWorktreePsSummaryLookup conversationName?: (source: RuntimeWorktreeAgentSource) => string | null + /** The desktop window's Agents-list verdicts; null when no window has published them. */ + agentList?: AgentListPublication | null }): void { const { rowSources } = args const now = Date.now() @@ -80,6 +99,10 @@ export function attachRuntimeWorktreeAgentRows(args: { if (source.children !== undefined || source.subagents !== undefined) { row.subagentObservation = isAgentStatusFresh(row, now) ? 'live' : 'unverifiable' } + const activity = args.agentList && agentListVerdict(args.agentList, source) + if (activity) { + row.activity = activity + } const rows = rowsBySummary.get(summary) if (rows) { rows.push(row) diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index 8610941e3fe..6334fb8480e 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -135,7 +135,8 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven rowSources, orchestrationByPaneKey: this.agentOrchestrationProjection.buildByPaneKey(), getSummary, - conversationName: this.orchestrationSenderNames.agentRowNamer() + conversationName: this.orchestrationSenderNames.agentRowNamer(), + agentList: this.readAgentListPublication() }) const sorted = [...summaries.values()].sort(compareWorktreePs) diff --git a/src/main/window/agent-pane-activity-relay.ts b/src/main/window/agent-pane-activity-relay.ts new file mode 100644 index 00000000000..a8c33e8231d --- /dev/null +++ b/src/main/window/agent-pane-activity-relay.ts @@ -0,0 +1,29 @@ +import type { BrowserWindow } from 'electron' + +import type { + AgentListPublication, + AgentPaneActivityChange, + AgentPaneActivityReply +} from '../../shared/agent-status/presentation/agent-list-status' +import { requestRendererReply } from './renderer-reply-request' + +// Under the client's call timeout, so the client hears a refusal rather than losing the reply. +const AGENT_PANE_ACTIVITY_TIMEOUT_MS = 10_000 + +/** Asks the window to apply a client's Agents-list change and answer with the verdicts it leaves. */ +export async function requestAgentPaneActivityFromRenderer( + mainWindow: BrowserWindow, + change: AgentPaneActivityChange +): Promise { + const reply = await requestRendererReply(mainWindow, { + requestChannel: 'ui:applyAgentPaneActivity', + replyChannel: 'ui:agentPaneActivityReply', + payload: change, + timeoutMs: AGENT_PANE_ACTIVITY_TIMEOUT_MS, + timeoutError: 'agent_activity_timeout' + }) + if ('error' in reply) { + throw new Error(reply.error) + } + return reply.publication +} diff --git a/src/main/window/main-window-service-stubs.test-fixture.ts b/src/main/window/main-window-service-stubs.test-fixture.ts index 0063c111933..b308406db67 100644 --- a/src/main/window/main-window-service-stubs.test-fixture.ts +++ b/src/main/window/main-window-service-stubs.test-fixture.ts @@ -30,6 +30,8 @@ type RuntimeStub = { markRendererReloadCancelled: MockFn markGraphReloadFailed: MockFn markGraphUnavailable: MockFn + readAgentListPublication: MockFn + setAgentListPublication: MockFn } export function createMainWindowServiceStub( @@ -67,7 +69,9 @@ export function createRuntime(): RuntimeStub { markRendererReloading: vi.fn(), markRendererReloadCancelled: vi.fn(), markGraphReloadFailed: vi.fn(), - markGraphUnavailable: vi.fn() + markGraphUnavailable: vi.fn(), + readAgentListPublication: vi.fn(() => null), + setAgentListPublication: vi.fn() } } diff --git a/src/main/window/renderer-reply-request.ts b/src/main/window/renderer-reply-request.ts new file mode 100644 index 00000000000..80582d8b885 --- /dev/null +++ b/src/main/window/renderer-reply-request.ts @@ -0,0 +1,65 @@ +import { randomUUID } from 'node:crypto' + +import { ipcMain, type BrowserWindow } from 'electron' + +import { addFanoutListener } from '../runtime/events/event-listener-fanout' +import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' + +/** Sends one request to the window and resolves with the reply its own renderer sends; rejects when it goes away or times out. */ +export function requestRendererReply( + mainWindow: BrowserWindow, + options: { + requestChannel: string + replyChannel: string + payload: object + timeoutMs: number + timeoutError: string + } +): Promise { + if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) { + return Promise.reject(new Error('renderer_unavailable')) + } + const webContents = mainWindow.webContents + const requestId = randomUUID() + return new Promise((resolve, reject) => { + let settled = false + const releaseListeners: (() => void)[] = [] + const finish = (error: Error | null, reply?: TReply): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeout) + for (const release of releaseListeners) { + release() + } + if (reply) { + resolve(reply) + } else { + reject(error) + } + } + const onRendererUnavailable = (): void => finish(new Error('renderer_unavailable')) + const timeout = setTimeout(() => finish(new Error(options.timeoutError)), options.timeoutMs) + const onReply = (event: Electron.IpcMainEvent, reply: TReply): void => { + // Visible request IDs confer no authority; only the targeted window can answer. + if (event.sender !== webContents || reply?.requestId !== requestId) { + return + } + finish(null, reply) + } + const lifetime = abortWhenRendererGone(webContents) + lifetime.signal.addEventListener('abort', onRendererUnavailable, { once: true }) + releaseListeners.push( + lifetime.dispose, + () => lifetime.signal.removeEventListener('abort', onRendererUnavailable), + addFanoutListener(mainWindow, 'closed', onRendererUnavailable), + addFanoutListener(ipcMain, options.replyChannel, onReply) + ) + try { + webContents.send(options.requestChannel, { ...options.payload, requestId }) + } catch { + finish(new Error('renderer_unavailable')) + } + }) +} diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 003ba029679..9af8fcb8048 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -8,6 +8,7 @@ import type { RuntimeMobileSessionTabMove } from '../../shared/runtime-types' import type { TerminalTabCreateReply } from '../../shared/workspace-layout/terminal-reveal-identity' import { runWorktreeChangeInvalidators } from '../ipc/worktrees/listing/worktree-change-invalidators' import { requestAgentLaunchTabPublishFromRenderer } from './agent-launch-tab-publish-relay' +import { requestAgentPaneActivityFromRenderer } from './agent-pane-activity-relay' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { registerRendererDocumentNavigation } from './renderer-document-navigation' import { createRuntimeRendererNotificationSender } from './runtime-renderer-notification-sender' @@ -16,6 +17,8 @@ import { requestTerminalPaneMoveFromRenderer } from './terminal-pane-move-reques import { revealTerminalPaneInWindow } from './terminal-pane-reveal-relay' import { requestTerminalTabCloseFromRenderer } from './terminal-tab-close-request-relay' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../shared/sidebar-inputs-switch' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' +import { addFanoutListener } from '../runtime/events/event-listener-fanout' let runtimeNotifierTokenCounter = 0 let activeRuntimeNotifierToken: number | null = null @@ -219,6 +222,7 @@ export function registerRuntimeWindowLifecycle( requestTerminalTabCloseFromRenderer(mainWindow, tabId, options), workspaceSleepChanged: (notice) => send('ui:workspaceSleep', notice), resumeSleepingAgents: (worktreeId) => send('ui:resumeSleepingAgents', { worktreeId }), + applyAgentPaneActivity: (change) => requestAgentPaneActivityFromRenderer(mainWindow, change), terminalFitOverrideChanged: (ptyId, mode, cols, rows) => send('runtime:terminalFitOverrideChanged', { ptyId, mode, cols, rows }), terminalDriverChanged: (ptyId, driver) => @@ -244,13 +248,29 @@ export function registerRuntimeWindowLifecycle( { consumesTerminalSideEffects: false } ) : null + // Only this window's live document speaks for the Agents list; a gone one leaves no verdicts behind. + const releaseAgentListVerdicts = addFanoutListener( + ipcMain, + 'agentStatus:listVerdicts', + (event: Electron.IpcMainEvent, publication: AgentListPublication | null) => { + if (event.sender === mainWebContents && event.senderFrame === mainWebContents.mainFrame) { + runtime.setAgentListPublication(publication) + } + } + ) registerRendererDocumentNavigation(mainWebContents, () => { rendererNotifications.onMainFrameReloadStarted() + const agentListBeforeReload = runtime.readAgentListPublication() + runtime.setAgentListPublication(null) const fence = runtime.markRendererReloading(mainWindow.id) return () => { if (fence && runtime.markRendererReloadCancelled(mainWindow.id, fence)) { rendererNotifications.onMainFrameReloadCancelled() } + // The surviving document only re-sends on change. + if (runtime.readAgentListPublication() === null) { + runtime.setAgentListPublication(agentListBeforeReload) + } } }) mainWebContents.on('did-finish-load', () => { @@ -258,9 +278,12 @@ export function registerRuntimeWindowLifecycle( }) mainWebContents.on('render-process-gone', () => { rendererNotifications.onRendererProcessGone() + runtime.setAgentListPublication(null) }) mainWindow.on('closed', () => { detachSidebarInputsNotices?.() + releaseAgentListVerdicts() + runtime.setAgentListPublication(null) rendererNotifications.close() runtime.markGraphUnavailable(mainWindow.id) if (activeRuntimeNotifierToken === notifierToken) { diff --git a/src/main/window/terminal-pane-reveal-relay.ts b/src/main/window/terminal-pane-reveal-relay.ts index 2238704d08f..837cc459556 100644 --- a/src/main/window/terminal-pane-reveal-relay.ts +++ b/src/main/window/terminal-pane-reveal-relay.ts @@ -1,14 +1,11 @@ -import { randomUUID } from 'node:crypto' - -import { app, ipcMain, type BrowserWindow } from 'electron' +import { app, type BrowserWindow } from 'electron' import type { TerminalPaneRevealReply, TerminalPaneRevealTarget } from '../../shared/workspace-layout/terminal-pane-reveal' -import { addFanoutListener } from '../runtime/events/event-listener-fanout' -import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' import { focusExistingMainWindow } from './focus-existing-window' +import { requestRendererReply } from './renderer-reply-request' const TERMINAL_PANE_REVEAL_TIMEOUT_MS = 10_000 @@ -17,7 +14,14 @@ export async function revealTerminalPaneInWindow( mainWindow: BrowserWindow, target: TerminalPaneRevealTarget ): Promise { - const revealed = await requestTerminalPaneRevealFromRenderer(mainWindow, target) + const reply = await requestRendererReply(mainWindow, { + requestChannel: 'ui:revealTerminalPane', + replyChannel: 'ui:terminalPaneRevealReply', + payload: target, + timeoutMs: TERMINAL_PANE_REVEAL_TIMEOUT_MS, + timeoutError: 'terminal_reveal_timeout' + }) + const revealed = reply.revealed === true if (revealed) { focusExistingMainWindow({ app, @@ -29,58 +33,3 @@ export async function revealTerminalPaneInWindow( } return revealed } - -function requestTerminalPaneRevealFromRenderer( - mainWindow: BrowserWindow, - target: TerminalPaneRevealTarget -): Promise { - if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) { - return Promise.reject(new Error('renderer_unavailable')) - } - const webContents = mainWindow.webContents - const requestId = randomUUID() - return new Promise((resolve, reject) => { - let settled = false - const releaseListeners: (() => void)[] = [] - const finish = (error: Error | null, revealed = false): void => { - if (settled) { - return - } - settled = true - clearTimeout(timeout) - for (const release of releaseListeners) { - release() - } - if (error) { - reject(error) - } else { - resolve(revealed) - } - } - const onRendererUnavailable = (): void => finish(new Error('renderer_unavailable')) - const timeout = setTimeout( - () => finish(new Error('terminal_reveal_timeout')), - TERMINAL_PANE_REVEAL_TIMEOUT_MS - ) - const onReply = (event: Electron.IpcMainEvent, reply: TerminalPaneRevealReply): void => { - // Visible request IDs confer no authority; only the targeted window can answer. - if (event.sender !== webContents || reply.requestId !== requestId) { - return - } - finish(null, reply.revealed === true) - } - const lifetime = abortWhenRendererGone(webContents) - lifetime.signal.addEventListener('abort', onRendererUnavailable, { once: true }) - releaseListeners.push( - lifetime.dispose, - () => lifetime.signal.removeEventListener('abort', onRendererUnavailable), - addFanoutListener(mainWindow, 'closed', onRendererUnavailable), - addFanoutListener(ipcMain, 'ui:terminalPaneRevealReply', onReply) - ) - try { - webContents.send('ui:revealTerminalPane', { ...target, requestId }) - } catch { - finish(new Error('renderer_unavailable')) - } - }) -} diff --git a/src/preload/api/agent-status-api.ts b/src/preload/api/agent-status-api.ts index d34fa917782..5df1f88ef65 100644 --- a/src/preload/api/agent-status-api.ts +++ b/src/preload/api/agent-status-api.ts @@ -7,6 +7,7 @@ import type { import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' import type { ComputerAwakeStatus } from '../../shared/computer-awake-mode' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' export type AgentStatusApi = { /** Listen for agent status updates forwarded from native hook receivers. */ @@ -45,6 +46,8 @@ export type AgentStatusApi = { /** Lift one pane's retirement fence when a live PTY re-attaches to it. Closed tabs stay retired. */ restorePaneAuthority: (paneKey: string) => void transferPaneAuthority: (args: { fromPaneKey: string; toPaneKey: string; ptyId?: string }) => void + /** The Agents list's verdicts, for worktree.ps to show paired clients. Fire-and-forget. */ + publishListVerdicts?: (publication: AgentListPublication | null) => void } export type AgentAwakeApi = { diff --git a/src/preload/api/agent-status-bridge.ts b/src/preload/api/agent-status-bridge.ts index dbf6ebb6f86..1a57c712b49 100644 --- a/src/preload/api/agent-status-bridge.ts +++ b/src/preload/api/agent-status-bridge.ts @@ -7,6 +7,7 @@ import type { } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' import type { PreloadApi } from '../api-types' export const agentStatusApi = { @@ -72,6 +73,9 @@ export const agentStatusApi = { dropPersistedBatch: (identities: readonly AgentStatusCacheIdentity[]): void => { ipcRenderer.send('agentStatus:dropPersistedBatch', identities) }, + publishListVerdicts: (publication: AgentListPublication | null): void => { + ipcRenderer.send('agentStatus:listVerdicts', publication) + }, reconcileEndedProcess: (paneKey: string): void => { ipcRenderer.send('agentStatus:reconcileEndedProcess', paneKey) }, diff --git a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts index b7638093379..ed9e8eb9b0a 100644 --- a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts +++ b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts @@ -11,6 +11,10 @@ import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' import type { TerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surface-close-target' import type { ClipboardImageThumbnail } from '../../shared/clipboard-image' import type { ReadClipboardTextOptions } from '../../shared/clipboard-text' +import type { + AgentPaneActivityReply, + AgentPaneActivityRequest +} from '../../shared/agent-status/presentation/agent-list-status' import type { PreloadApi } from '../api-types' export const uiClipboardAndWindowControlsApi = { @@ -85,6 +89,15 @@ export const uiClipboardAndWindowControlsApi = { ipcRenderer.on('ui:resumeSleepingAgents', listener) return () => ipcRenderer.removeListener('ui:resumeSleepingAgents', listener) }, + onApplyAgentPaneActivity: (callback: (data: AgentPaneActivityRequest) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: AgentPaneActivityRequest) => + callback(data) + ipcRenderer.on('ui:applyAgentPaneActivity', listener) + return () => ipcRenderer.removeListener('ui:applyAgentPaneActivity', listener) + }, + replyAgentPaneActivity: (reply: AgentPaneActivityReply): void => { + ipcRenderer.send('ui:agentPaneActivityReply', reply) + }, onTerminalZoom: (callback: (direction: 'in' | 'out' | 'reset') => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, direction: 'in' | 'out' | 'reset') => callback(direction) diff --git a/src/preload/api/ui-command-event-api.ts b/src/preload/api/ui-command-event-api.ts index cfb796cc184..f9895cec986 100644 --- a/src/preload/api/ui-command-event-api.ts +++ b/src/preload/api/ui-command-event-api.ts @@ -26,6 +26,10 @@ import type { TerminalPaneRevealReply, TerminalPaneRevealRequest } from '../../shared/workspace-layout/terminal-pane-reveal' +import type { + AgentPaneActivityReply, + AgentPaneActivityRequest +} from '../../shared/agent-status/presentation/agent-list-status' import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' import type { ProjectMovePauseRequest, @@ -225,6 +229,8 @@ export type UiCommandEventApi = { onLaunchRecipe: (callback: (data: PaneLaunchRecipe) => void) => () => void onRevealTerminalPane: (callback: (data: TerminalPaneRevealRequest) => void) => () => void replyTerminalPaneReveal: (reply: TerminalPaneRevealReply) => void + onApplyAgentPaneActivity: (callback: (data: AgentPaneActivityRequest) => void) => () => void + replyAgentPaneActivity: (reply: AgentPaneActivityReply) => void onSplitTerminal: ( callback: (data: { tabId: string diff --git a/src/renderer/src/app-shell/AppBackgroundServices.tsx b/src/renderer/src/app-shell/AppBackgroundServices.tsx index d1c9ce9c824..0fa98b6070d 100644 --- a/src/renderer/src/app-shell/AppBackgroundServices.tsx +++ b/src/renderer/src/app-shell/AppBackgroundServices.tsx @@ -12,8 +12,12 @@ import { ActiveWorkspaceSyncGate } from './ActiveWorkspaceSyncGate' import { StructuredAgentSessionAttentionBridge } from '../components/native-chat/session/attention/StructuredAgentSessionAttentionBridge' import { StructuredAgentSessionStatusBridge } from '../components/native-chat/session/status/StructuredAgentSessionStatusBridge' import { NativeChatVisualGuestThemePublisher } from '../components/native-chat/media/visuals/NativeChatVisualGuestThemePublisher' +import { usePairedMobileDevices } from '../components/mobile/paired-mobile-devices' const DashboardPopoutBridge = lazy(() => import('../components/dashboard/DashboardPopoutBridge')) +const AgentListVerdictPublisher = lazy( + () => import('../components/activity/agent-list-verdict-publisher') +) /** Isolate high-churn subscriptions from App rendering; services outlive their consuming surfaces. */ export function AppBackgroundServices(): React.JSX.Element { @@ -21,6 +25,9 @@ export function AppBackgroundServices(): React.JSX.Element { const dashboardPopoutEnabled = useAppStore( (s) => s.settings?.experimentalAgentDashboardPopout === true ) + const canPublishAgentList = Boolean(window.api.agentStatus?.publishListVerdicts) + // The list builds on every agent update, so only a desktop with a paired phone pays for it. + const { hasPairedDevice } = usePairedMobileDevices({ enabled: canPublishAgentList }) return ( <> @@ -40,6 +47,12 @@ export function AppBackgroundServices(): React.JSX.Element { ) : null} + {/* Paired phones list agents with the desktop Agents list's verdicts; web clients have no host to tell. */} + {canPublishAgentList && hasPairedDevice ? ( + + + + ) : null} {/* Background chats have no mounted pane but still need completion attention. */} diff --git a/src/renderer/src/components/AgentStateDot.tsx b/src/renderer/src/components/AgentStateDot.tsx index 1cbc1ca512b..f9449bdfb64 100644 --- a/src/renderer/src/components/AgentStateDot.tsx +++ b/src/renderer/src/components/AgentStateDot.tsx @@ -14,25 +14,11 @@ import { StateIndicatorTooltip, type StateIndicatorTooltipSide } from '@/components/StateIndicatorTooltip' +import type { AgentListStatus } from '../../../shared/agent-status/presentation/agent-list-status' // Share state glyphs across agent surfaces. Keep the agent identity icon separate; completion uses a check while sidebar StatusIndicator uses an emerald dot/tooltip. -export type AgentDotState = - | 'working' - | 'monitoring' - | 'blocked' - | 'waiting' - | 'interrupted' - // Transcript-derived failure is an outcome, distinct from live blocked attention. - | 'failed' - | 'done' - | 'idle' - // A live PTY with stale reporting proves only missing evidence, not idle/work/completion. - | 'unverifiable' - // The turn ended without a proven outcome; use the missing-evidence glyph, never completion. - | 'unconfirmed' - // Sidebar combines blocked/waiting as permission; retain its vocabulary with the shared question glyph/token. - | 'permission' +export type AgentDotState = AgentListStatus /** Return the accessible label shared by every visual agent-state marker. */ export function agentStateLabel(state: AgentDotState): string { diff --git a/src/renderer/src/components/activity/activity-paired-client-change.ts b/src/renderer/src/components/activity/activity-paired-client-change.ts new file mode 100644 index 00000000000..401dcc2d718 --- /dev/null +++ b/src/renderer/src/components/activity/activity-paired-client-change.ts @@ -0,0 +1,37 @@ +import { useAppStore } from '@/store' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../../shared/agent-status/presentation/agent-list-status' +import { clearActivityThread } from './activity-clear-completed' +import { publishAgentListNow, readPublishedAgentPaneThreads } from './agent-list-verdict-publisher' + +/** Applies a paired client's change with the same actions as the Agents list row, then answers with the list it leaves. */ +export function applyPairedClientActivityChange( + change: AgentPaneActivityChange +): Promise { + const state = useAppStore.getState() + const threads = readPublishedAgentPaneThreads() + // Unhydrated maps are empty, and main would persist them over the saved ones. + if (!state.persistedUIReady || !threads) { + throw new Error('agent_activity_not_ready') + } + if (change.kind === 'read') { + state.acknowledgeAgents(change.paneKeys, undefined, 'explicit') + } else if (change.kind === 'unread') { + state.unacknowledgeAgents(change.paneKeys) + } else { + const paneKeys = new Set(change.paneKeys) + let cleared = 0 + for (const thread of threads) { + if (paneKeys.has(thread.paneKey) && clearActivityThread(thread)) { + cleared += 1 + } + } + // Answering success would let the phone drop its guess and show the row again with no word why. + if (cleared === 0) { + throw new Error('agent_activity_not_clearable') + } + } + return publishAgentListNow() +} diff --git a/src/renderer/src/components/activity/activity-thread-child-agent.ts b/src/renderer/src/components/activity/activity-thread-child-agent.ts index 3b6c75339f9..2f2297f3d04 100644 --- a/src/renderer/src/components/activity/activity-thread-child-agent.ts +++ b/src/renderer/src/components/activity/activity-thread-child-agent.ts @@ -46,6 +46,14 @@ function firstReportedTerminalHandle(thread: ChildAgentClassifiableThread): stri export function collectHiddenChildAgentPaneKeys( threads: readonly ChildAgentClassifiableThread[] ): Set { + return classifyChildAgents(threads).hidden +} + +/** Each child's parent and the children a hidden-children view folds away. */ +export function classifyChildAgents(threads: readonly ChildAgentClassifiableThread[]): { + parentPaneKeyByChild: Map + hidden: Set +} { const baseRows: AgentLineageSourceRow[] = threads.map((thread) => ({ paneKey: thread.paneKey, entry: { terminalHandle: firstReportedTerminalHandle(thread) } @@ -83,11 +91,18 @@ export function collectHiddenChildAgentPaneKeys( const livePaneKeys = new Set( threads.filter((thread) => thread.currentAgentState).map((thread) => thread.paneKey) ) + const tree = buildAgentRowLineageTree(rows) + const parentPaneKeyByChild = new Map() + for (const [parentPaneKey, children] of tree.childrenByParentPaneKey) { + for (const child of children) { + parentPaneKeyByChild.set(child.paneKey, parentPaneKey) + } + } const hidden = new Set() - for (const paneKey of buildAgentRowLineageTree(rows).childPaneKeys) { + for (const paneKey of tree.childPaneKeys) { if (!livePaneKeys.has(paneKey)) { hidden.add(paneKey) } } - return hidden + return { parentPaneKeyByChild, hidden } } diff --git a/src/renderer/src/components/activity/activity-thread-grouping.ts b/src/renderer/src/components/activity/activity-thread-grouping.ts index 997a0404437..1fcea62126c 100644 --- a/src/renderer/src/components/activity/activity-thread-grouping.ts +++ b/src/renderer/src/components/activity/activity-thread-grouping.ts @@ -10,30 +10,14 @@ import { agentMeta, agentSummary, agentTitle, - threadAgentStateLabel, - type ActivityThreadStatusId + threadAgentStateLabel } from './activity-thread-presentation' +import { AGENT_LIST_STATUS_RANK } from '../../../../shared/agent-status/presentation/agent-list-status' import type { ActivityGroupBy } from '../../../../shared/agents-view-thread-filters' import type { ActivityThreadGroup, AgentPaneThread } from './activity-thread-types' -// Use exhaustive, unique attention ranks so new states fail typecheck and recency cannot reorder headers. -const ACTIVITY_STATUS_GROUP_RANK: Record = { - waiting: 0, - blocked: 1, - permission: 2, - failed: 3, - unconfirmed: 4, - working: 5, - monitoring: 6, - // A user's Stop is not news, so it follows live work, but it is not a finish either. - interrupted: 7, - unverifiable: 8, - done: 9, - idle: 10 -} - function activityStatusRank(thread: AgentPaneThread): number { - return ACTIVITY_STATUS_GROUP_RANK[activityThreadStatusId(thread)] + return AGENT_LIST_STATUS_RANK[activityThreadStatusId(thread)] } export function getActivityThreadGroup( diff --git a/src/renderer/src/components/activity/agent-list-verdict-publisher.ts b/src/renderer/src/components/activity/agent-list-verdict-publisher.ts new file mode 100644 index 00000000000..862eb825ddf --- /dev/null +++ b/src/renderer/src/components/activity/agent-list-verdict-publisher.ts @@ -0,0 +1,134 @@ +import { useEffect, useMemo, useState } from 'react' +import { useAppStore } from '@/store' +import type { + AgentListPublication, + AgentListVerdict +} from '../../../../shared/agent-status/presentation/agent-list-status' +import { isClearableActivityThread } from './activity-clear-completed' +import { classifyChildAgents } from './activity-thread-child-agent' +import { activityThreadStatusId } from './activity-thread-presentation' +import type { AgentPaneThread } from './activity-thread-types' +import { useAllAgentPaneThreads } from './use-agent-pane-threads' + +const PUBLISH_INTERVAL_MS = 250 + +/** The Agents list's verdict for every pane the window knows; a pane with no thread is unlisted. */ +function buildAgentListVerdicts( + threads: readonly AgentPaneThread[], + knownPaneKeys: readonly string[] +): Record { + const { parentPaneKeyByChild, hidden } = classifyChildAgents(threads) + const verdicts: Record = {} + for (const paneKey of knownPaneKeys) { + verdicts[paneKey] = { listed: false } + } + for (const thread of threads) { + const childOf = parentPaneKeyByChild.get(thread.paneKey) + verdicts[thread.paneKey] = { + listed: true, + status: activityThreadStatusId(thread), + unread: thread.unread, + clearable: isClearableActivityThread(thread), + sortAt: thread.latestTimestamp, + title: thread.paneTitle, + ...(childOf ? { childOf } : {}), + ...(hidden.has(thread.paneKey) ? { foldedChild: true as const } : {}) + } + } + return verdicts +} + +// One publisher per window; a paired client's change reads its threads and waits for its next publish. +let published: { threads: readonly AgentPaneThread[]; publication: AgentListPublication } | null = + null +let requestRender: (() => void) | null = null +let waiters: ((publication: AgentListPublication) => void)[] = [] +let lastSentVerdicts: string | null = null +let lastSentAt = 0 +let timer: ReturnType | null = null + +function send(publication: AgentListPublication): void { + if (timer !== null) { + clearTimeout(timer) + timer = null + } + lastSentAt = Date.now() + const verdicts = JSON.stringify(publication.verdicts) + if (verdicts !== lastSentVerdicts) { + lastSentVerdicts = verdicts + window.api.agentStatus.publishListVerdicts?.(publication) + } +} + +/** The threads behind the last published verdicts; null until the publisher has run. */ +export function readPublishedAgentPaneThreads(): readonly AgentPaneThread[] | null { + return published?.threads ?? null +} + +/** Resolves with the verdicts once the publisher has rendered the store as it is now. */ +export function publishAgentListNow(): Promise { + const render = requestRender + if (!render) { + return Promise.reject(new Error('agent_activity_not_ready')) + } + return new Promise((resolve) => { + waiters.push(resolve) + render() + }) +} + +/** Sends the desktop Agents list's verdicts to main, so worktree.ps shows paired clients the same list. */ +export default function AgentListVerdictPublisher(): null { + const ready = useAppStore((s) => s.persistedUIReady) + // The unscoped list: view filters and the child-agent toggle only narrow what one surface shows. + const { storeData, allThreads } = useAllAgentPaneThreads() + const [renderRequest, setRenderRequest] = useState(0) + useEffect(() => { + requestRender = () => setRenderRequest((count) => count + 1) + return () => { + requestRender = null + published = null + lastSentVerdicts = null + // Unmounted with no phone paired: stale verdicts would hide new agents from a later pairing. + window.api.agentStatus.publishListVerdicts?.(null) + if (timer !== null) { + clearTimeout(timer) + timer = null + } + } + }, []) + const verdicts = useMemo( + () => buildAgentListVerdicts(allThreads, Object.keys(storeData.agentStatusByPaneKey)), + [allThreads, storeData.agentStatusByPaneKey] + ) + useEffect(() => { + // Unhydrated read stamps would mark every agent unread. + if (!ready) { + return + } + const publication = { publishedAt: Date.now(), verdicts } + published = { threads: allThreads, publication } + const pending = waiters + waiters = [] + if (pending.length > 0) { + send(publication) + for (const resolve of pending) { + resolve(publication) + } + return + } + // Each run reschedules from the last send, so a busy store cannot starve the publish. + const scheduled = setTimeout( + () => published && send(published.publication), + Math.max(0, lastSentAt + PUBLISH_INTERVAL_MS - Date.now()) + ) + timer = scheduled + return () => { + clearTimeout(scheduled) + if (timer === scheduled) { + timer = null + } + } + }, [ready, allThreads, verdicts, renderRequest]) + return null +} diff --git a/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts b/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts index 4e647f4f26f..cc2aac04cb3 100644 --- a/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts +++ b/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts @@ -16,7 +16,7 @@ import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' -export type AgentPaneThreadsStoreData = Pick< +export type AllAgentPaneThreadsStoreData = Pick< AppState, | 'agentStatusByPaneKey' | 'runtimeAgentOrchestrationByPaneKey' @@ -39,11 +39,20 @@ export type AgentPaneThreadsStoreData = Pick< worktreeMap: ReturnType repoMap: ReturnType generatedTitlesEnabled: boolean +} + +export type AgentPaneThreadsStoreData = AllAgentPaneThreadsStoreData & { /** Focused-host fallback for hostless worktrees, shared by the scope filter and the row actions. */ defaultHostId: ExecutionHostId } -export function useAgentPaneThreadStoreData(): AgentPaneThreadsStoreData { +/** Focused-host fallback for the scope filter and row actions; the unscoped list never reads it. */ +export function useAgentPaneThreadsDefaultHostId(): ExecutionHostId { + return useAppStore((s) => getSettingsFocusedExecutionHostId(s.settings)) +} + +/** Store inputs for every Activity thread, before any view scope. */ +export function useAllAgentPaneThreadStoreData(): AllAgentPaneThreadsStoreData { // Keep original native tabs for owner-qualified names; preserve terminal projections across focus writes. const tabProjectionRef = useRef<{ raw: AppState['unifiedTabsByWorktree'] | null @@ -77,8 +86,7 @@ export function useAgentPaneThreadStoreData(): AgentPaneThreadsStoreData { activityClearedAtByPaneKey: s.activityClearedAtByPaneKey, acknowledgeAgents: s.acknowledgeAgents, unacknowledgeAgents: s.unacknowledgeAgents, - generatedTitlesEnabled: s.settings?.tabAutoGenerateTitle === true, - defaultHostId: getSettingsFocusedExecutionHostId(s.settings) + generatedTitlesEnabled: s.settings?.tabAutoGenerateTitle === true })) ) } diff --git a/src/renderer/src/components/activity/use-agent-pane-threads.ts b/src/renderer/src/components/activity/use-agent-pane-threads.ts index 32836ff12b8..e32bb3c9ec2 100644 --- a/src/renderer/src/components/activity/use-agent-pane-threads.ts +++ b/src/renderer/src/components/activity/use-agent-pane-threads.ts @@ -4,8 +4,10 @@ import { useStructuredChatTabNames } from '@/runtime/native-chat/naming/structur import { buildActivityEvents, createActivityEventBuildCache } from './activity-event-builder' import { freshActivityLiveAgentState } from './activity-event-state' import { - useAgentPaneThreadStoreData, - type AgentPaneThreadsStoreData + useAgentPaneThreadsDefaultHostId, + useAllAgentPaneThreadStoreData, + type AgentPaneThreadsStoreData, + type AllAgentPaneThreadsStoreData } from './use-agent-pane-thread-store-data' import { buildAgentPaneThreads, createAgentPaneThreadReuseCache } from './activity-thread-builder' import { collectHiddenChildAgentPaneKeys } from './activity-thread-child-agent' @@ -34,56 +36,12 @@ const EMPTY_ACTIVITY_BUILD: ReturnType = { paneEntryByPaneKey: {} } -/** Shared Activity/sidebar pipeline: store data to events, threads, filters and groups. */ -export function useAgentPaneThreads(args: { - query: string - readFilter: ThreadReadFilter - groupBy: ActivityGroupBy - selectedPaneKey: string | null - showChildAgents?: boolean - /** Prepare only live badge rows, omitting list groups and bulk-action sets. */ - badgeOnly?: boolean -}): { - storeData: AgentPaneThreadsStoreData +/** Every Activity thread before any view filter: store data to events and threads. */ +export function useAllAgentPaneThreads({ badgeOnly = false }: { badgeOnly?: boolean } = {}): { + storeData: AllAgentPaneThreadsStoreData allThreads: AgentPaneThread[] - selectedPaneKeyIsLive: boolean - effectiveSelectedPaneKey: string | null - /** Every active view filter applies here; destructive Clear completed must not touch hidden rows. */ - visibleThreads: AgentPaneThread[] - /** Badge-coherent threads after child classification; ignore transient search/scope/read filters so Mark all read can clear the badge. */ - markAllReadThreads: AgentPaneThread[] - visibleThreadGroups: ActivityThreadGroup[] } { - const { - query, - readFilter, - groupBy, - selectedPaneKey, - showChildAgents = false, - badgeOnly = false - } = args - const agentsVisibleHostIds = useAppStore((s) => s.agentsVisibleHostIds) - const agentsFilterRepoIds = useAppStore((s) => s.agentsFilterRepoIds) - const hideWorkspacesFromOtherDevices = useAppStore((s) => s.agentsHideWorkspacesFromOtherDevices) - const hideAutomationGeneratedWorkspaces = useAppStore( - (s) => s.agentsHideAutomationGeneratedWorkspaces - ) - const hideCliCreatedWorkspaces = useAppStore((s) => s.agentsHideCliCreatedWorkspaces) - // Why gated selectors: runtime status churns, and only the other-device filter reads it. - const runtimeEnvironments = useAppStore((s) => - s.agentsHideWorkspacesFromOtherDevices ? s.runtimeEnvironments : null - ) - const runtimeStatusByEnvironmentId = useAppStore((s) => - s.agentsHideWorkspacesFromOtherDevices ? s.runtimeStatusByEnvironmentId : null - ) - const pairedDeviceIdsByEnvironment = useMemo( - () => - runtimeEnvironments && runtimeStatusByEnvironmentId - ? getPairedDeviceIdsByEnvironment(runtimeEnvironments, runtimeStatusByEnvironmentId) - : EMPTY_PAIRED_DEVICE_IDS_BY_ENVIRONMENT, - [runtimeEnvironments, runtimeStatusByEnvironmentId] - ) - const storeData = useAgentPaneThreadStoreData() + const storeData = useAllAgentPaneThreadStoreData() // Why: agentStatusEpoch is a dep (not used in the body) so the memo recomputes when freshness boundaries expire even without new PTY data. const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) const chatNames = useStructuredChatTabNames() @@ -153,6 +111,65 @@ export function useAgentPaneThreads(args: { [allEvents, liveAgentByPaneKey, paneEntryByPaneKey, storeData.generatedTitlesEnabled, badgeOnly] ) + return { storeData, allThreads } +} + +/** Shared Activity/sidebar pipeline: store data to events, threads, filters and groups. */ +export function useAgentPaneThreads(args: { + query: string + readFilter: ThreadReadFilter + groupBy: ActivityGroupBy + selectedPaneKey: string | null + showChildAgents?: boolean + /** Prepare only live badge rows, omitting list groups and bulk-action sets. */ + badgeOnly?: boolean +}): { + storeData: AgentPaneThreadsStoreData + allThreads: AgentPaneThread[] + selectedPaneKeyIsLive: boolean + effectiveSelectedPaneKey: string | null + /** Every active view filter applies here; destructive Clear completed must not touch hidden rows. */ + visibleThreads: AgentPaneThread[] + /** Badge-coherent threads after child classification; ignore transient search/scope/read filters so Mark all read can clear the badge. */ + markAllReadThreads: AgentPaneThread[] + visibleThreadGroups: ActivityThreadGroup[] +} { + const { + query, + readFilter, + groupBy, + selectedPaneKey, + showChildAgents = false, + badgeOnly = false + } = args + const agentsVisibleHostIds = useAppStore((s) => s.agentsVisibleHostIds) + const agentsFilterRepoIds = useAppStore((s) => s.agentsFilterRepoIds) + const hideWorkspacesFromOtherDevices = useAppStore((s) => s.agentsHideWorkspacesFromOtherDevices) + const hideAutomationGeneratedWorkspaces = useAppStore( + (s) => s.agentsHideAutomationGeneratedWorkspaces + ) + const hideCliCreatedWorkspaces = useAppStore((s) => s.agentsHideCliCreatedWorkspaces) + // Why gated selectors: runtime status churns, and only the other-device filter reads it. + const runtimeEnvironments = useAppStore((s) => + s.agentsHideWorkspacesFromOtherDevices ? s.runtimeEnvironments : null + ) + const runtimeStatusByEnvironmentId = useAppStore((s) => + s.agentsHideWorkspacesFromOtherDevices ? s.runtimeStatusByEnvironmentId : null + ) + const pairedDeviceIdsByEnvironment = useMemo( + () => + runtimeEnvironments && runtimeStatusByEnvironmentId + ? getPairedDeviceIdsByEnvironment(runtimeEnvironments, runtimeStatusByEnvironmentId) + : EMPTY_PAIRED_DEVICE_IDS_BY_ENVIRONMENT, + [runtimeEnvironments, runtimeStatusByEnvironmentId] + ) + const { storeData: unscopedStoreData, allThreads } = useAllAgentPaneThreads({ badgeOnly }) + const defaultHostId = useAgentPaneThreadsDefaultHostId() + const storeData = useMemo( + () => ({ ...unscopedStoreData, defaultHostId }), + [unscopedStoreData, defaultHostId] + ) + const selectedPaneKeyIsLive = selectedPaneKey === null || allThreads.some((thread) => thread.paneKey === selectedPaneKey) const effectiveSelectedPaneKey = selectedPaneKeyIsLive ? selectedPaneKey : null @@ -201,7 +218,8 @@ export function useAgentPaneThreads(args: { const normalizedQuery = isActivitySearchQueryTooLarge(deferredQuery) ? null : deferredQuery.trim().toLowerCase() - let matchesSearchQuery: ReturnType | undefined + const matchesSearchQuery = + normalizedQuery === null ? null : createActivityThreadSearchMatcher(normalizedQuery) return scopeVisibleThreads.filter((thread) => { // Why: keep the just-selected thread visible after auto-mark-read flips it to read, else unread-only mode makes the clicked row vanish from the list. if ( @@ -219,11 +237,7 @@ export function useAgentPaneThreads(args: { ) { return false } - if (normalizedQuery === null) { - return false - } - matchesSearchQuery ??= createActivityThreadSearchMatcher(normalizedQuery) - return matchesSearchQuery(thread) + return matchesSearchQuery !== null && matchesSearchQuery(thread) }) }, [ scopeVisibleThreads, diff --git a/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts b/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts index 90b86ec2f4f..6acae390313 100644 --- a/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts +++ b/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts @@ -50,6 +50,7 @@ export function buildWindowApi(args: { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts b/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts index 1b6a6b05fe0..8ee024aecf7 100644 --- a/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts +++ b/src/renderer/src/hooks/ipc-events-close-routing-test-harness.ts @@ -181,6 +181,7 @@ export async function useIpcEventsForCloseRouting({ onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/hooks/ipc-events/agent-pane-activity-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/agent-pane-activity-ipc-bridge.ts new file mode 100644 index 00000000000..4c5a44bcbbd --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/agent-pane-activity-ipc-bridge.ts @@ -0,0 +1,19 @@ +import type { AgentPaneActivityReply } from '../../../../shared/agent-status/presentation/agent-list-status' + +export function registerAgentPaneActivityIpcBridge(unsubs: (() => void)[]): void { + unsubs.push( + window.api.ui.onApplyAgentPaneActivity(({ requestId, ...change }) => { + // Lazy: Activity's clear module binds window listeners on load. Main holds the caller's RPC open until this reply, so a throw must still answer. + void import('@/components/activity/activity-paired-client-change') + .then(({ applyPairedClientActivityChange }) => applyPairedClientActivityChange(change)) + .then( + (publication): AgentPaneActivityReply => ({ requestId, publication }), + (error: unknown): AgentPaneActivityReply => ({ + requestId, + error: error instanceof Error ? error.message : 'agent_activity_failed' + }) + ) + .then((reply) => window.api.ui.replyAgentPaneActivity(reply)) + }) + ) +} diff --git a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts index aeccf75f220..80e83e8e5ad 100644 --- a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts @@ -36,6 +36,7 @@ import { registerPtySourceDisownedIpcBridge } from './pty-source-disowned-ipc-br import { registerTerminalRequestIpcBridge } from './terminal-request-ipc-bridge' import { registerAgentLaunchTabIpcBridge } from './agent-launch-tab-ipc-bridge' import { registerTerminalPaneRevealIpcBridge } from './terminal-pane-reveal-ipc-bridge' +import { registerAgentPaneActivityIpcBridge } from './agent-pane-activity-ipc-bridge' import { registerTerminalUiRoutingIpcBridge } from './terminal-ui-routing-ipc-bridge' import { registerUpdaterStatusIpcBridge } from './updater-status-ipc-bridge' import { createWorktreeEventRuntime } from './worktree-event-runtime' @@ -128,6 +129,7 @@ export function installAppLifetimeIpcEvents(): () => void { registerPtySourceDisownedIpcBridge(unsubs) registerTerminalUiRoutingIpcBridge(unsubs) registerTerminalPaneRevealIpcBridge(unsubs) + registerAgentPaneActivityIpcBridge(unsubs) registerSessionTabIpcBridge(unsubs) registerMobileAndTerminalCloseIpcBridge(unsubs, backgroundWakeDispatcher.request) registerUpdaterStatusIpcBridge(unsubs) diff --git a/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts b/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts index 593243d963d..99f82153e85 100644 --- a/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts @@ -140,6 +140,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, @@ -404,6 +405,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts b/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts index ab86cea6d68..946f333b56c 100644 --- a/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts @@ -143,6 +143,7 @@ describe('useIpcEvents browser tab close routing', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, @@ -374,6 +375,7 @@ describe('useIpcEvents browser tab close routing', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, @@ -600,6 +602,7 @@ describe('useIpcEvents browser tab close routing', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts b/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts index 35c7e61e8cd..920d515265c 100644 --- a/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts @@ -155,6 +155,7 @@ describe('useIpcEvents updater integration', () => { onRequestTerminalCreate: () => () => {}, onPublishAgentLaunchTab: () => () => {}, onRevealTerminalPane: () => () => {}, + onApplyAgentPaneActivity: () => () => {}, onAgentLaunchPaneVerdict: () => () => {}, onLaunchRecipe: () => () => {}, onRequestTerminalTabMount: () => () => {}, diff --git a/src/renderer/src/web/preload-api/web-ui-api.ts b/src/renderer/src/web/preload-api/web-ui-api.ts index 1a8628ee724..5f6b1e2ec31 100644 --- a/src/renderer/src/web/preload-api/web-ui-api.ts +++ b/src/renderer/src/web/preload-api/web-ui-api.ts @@ -250,6 +250,8 @@ export function createWebUiApi(): NonNullable['ui']> { replyAgentLaunchTabPublish: () => {}, onRevealTerminalPane: () => noopUnsubscribe, replyTerminalPaneReveal: () => {}, + onApplyAgentPaneActivity: () => noopUnsubscribe, + replyAgentPaneActivity: () => {}, onSplitTerminal: () => noopUnsubscribe, onRenameTerminal: () => noopUnsubscribe, onSetPaneTitle: () => noopUnsubscribe, diff --git a/src/shared/agent-status/presentation/agent-list-status.ts b/src/shared/agent-status/presentation/agent-list-status.ts new file mode 100644 index 00000000000..dc0d5d8169f --- /dev/null +++ b/src/shared/agent-status/presentation/agent-list-status.ts @@ -0,0 +1,68 @@ +/** A row's status in the desktop Agents list; the renderer's AgentDotState is this union. */ +export type AgentListStatus = + | 'working' + | 'monitoring' + | 'blocked' + | 'waiting' + | 'interrupted' + // Transcript-derived failure is an outcome, distinct from live blocked attention. + | 'failed' + | 'done' + | 'idle' + // A live PTY with stale reporting proves only missing evidence, not idle/work/completion. + | 'unverifiable' + // The turn ended without a proven outcome; use the missing-evidence glyph, never completion. + | 'unconfirmed' + // Sidebar combines blocked/waiting as permission; retain its vocabulary with the shared question glyph/token. + | 'permission' + +// Use exhaustive, unique attention ranks so new states fail typecheck and recency cannot reorder headers. +export const AGENT_LIST_STATUS_RANK: Record = { + waiting: 0, + blocked: 1, + permission: 2, + failed: 3, + unconfirmed: 4, + working: 5, + monitoring: 6, + // A user's Stop is not news, so it follows live work, but it is not a finish either. + interrupted: 7, + unverifiable: 8, + done: 9, + idle: 10 +} + +/** How the desktop Agents list shows one agent pane; unlisted panes are not in the list at all. */ +export type AgentListVerdict = + | { listed: false } + | { + listed: true + status: AgentListStatus + unread: boolean + clearable: boolean + /** The row's recency, newest first within a status. */ + sortAt: number + title: string + /** The coordinator this worker nests under. */ + childOf?: string + /** A finished worker the list hides while child agents are hidden. */ + foldedChild?: true + } + +/** The desktop window's verdicts by pane key, as of `publishedAt`. */ +export type AgentListPublication = { + publishedAt: number + verdicts: Record +} + +/** A paired client's Agents-list change; the desktop window applies it with its own Activity actions. */ +export type AgentPaneActivityChange = { + kind: 'read' | 'unread' | 'clear' + paneKeys: string[] +} + +export type AgentPaneActivityRequest = AgentPaneActivityChange & { requestId: string } + +export type AgentPaneActivityReply = + | { requestId: string; publication: AgentListPublication } + | { requestId: string; error: string } diff --git a/src/shared/host-operation-ownership.ts b/src/shared/host-operation-ownership.ts index 0b6067e2ff8..a73a6b77a91 100644 --- a/src/shared/host-operation-ownership.ts +++ b/src/shared/host-operation-ownership.ts @@ -13,6 +13,7 @@ export type HostOperationOwnership = 'host' | 'credential' | 'client' | 'stream' export const HOST_OPERATION_OWNERSHIP = { accounts: 'host', agent: 'host', + agentActivity: 'host', agentHooks: 'host', agentSession: 'host', agentSessionAttachment: 'host', diff --git a/src/shared/rpc-contract/agent-activity-params.ts b/src/shared/rpc-contract/agent-activity-params.ts new file mode 100644 index 00000000000..b84f73940e5 --- /dev/null +++ b/src/shared/rpc-contract/agent-activity-params.ts @@ -0,0 +1,11 @@ +import { z } from 'zod' + +// Bounded like a worktree.ps page of agent rows; pane keys are `${tabId}:${leafUuid}`. +const AgentActivityPaneKeys = z.array(z.string().min(1).max(512)).min(1).max(500) + +export const AgentActivitySetReadParams = z.object({ + paneKeys: AgentActivityPaneKeys, + read: z.boolean() +}) + +export const AgentActivityClearParams = z.object({ paneKeys: AgentActivityPaneKeys }) diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index d2d44a18829..761f3ca6eb2 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -68,6 +68,7 @@ import { SelectCodexAccountForTargetParams, SelectDataAccountParams } from './accounts-params' +import { AgentActivityClearParams, AgentActivitySetReadParams } from './agent-activity-params' import { PrepareCodexForWslPaneParams } from './agent-hooks-params' import { AgentLaunch, AgentLaunchReplay } from './agent-launch-params' import { AgentLaunchSettingsMutation } from './agent-launch-settings-params' @@ -808,6 +809,8 @@ export const RPC_PARAMS_BY_METHOD = { 'accounts.zcodePlanSaveApiKey': UsageCredentialApiKeyParams, 'agent.launch': AgentLaunch, 'agent.launchReplay': AgentLaunchReplay, + 'agentActivity.clear': AgentActivityClearParams, + 'agentActivity.setRead': AgentActivitySetReadParams, 'agentHooks.prepareCodexForWslPane': PrepareCodexForWslPaneParams, 'agentSession.accountUsage': OptionsParams, 'agentSession.acknowledgeAttention': AcknowledgeAttentionParams, diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts index 0c03f46106d..47e0f41508e 100644 --- a/src/shared/runtime-client-events.ts +++ b/src/shared/runtime-client-events.ts @@ -27,6 +27,8 @@ export type RuntimeClientEvent = | { type: 'gitStatusChanged'; repoId: string; worktreeIds?: string[] } /** Top-level settings whose values changed; a phone re-reads only the settings it shows. */ | { type: 'settingsChanged'; keys: string[] } + /** The desktop Agents list's verdicts changed; worktree.ps carries them. */ + | { type: 'agentListChanged' } | { type: 'worktreesChanged' repoId: string diff --git a/src/shared/runtime-worktree-contracts.ts b/src/shared/runtime-worktree-contracts.ts index 51a7d488806..ca10376ceb8 100644 --- a/src/shared/runtime-worktree-contracts.ts +++ b/src/shared/runtime-worktree-contracts.ts @@ -6,6 +6,7 @@ import type { } from './agent-status/contracts/agent-status-types' import type { AgentMainAgentStatus } from './agent-status/lifecycle/main-agent-status' import type { ProgramStatusFacet } from './program-status/facet' +import type { AgentListVerdict } from './agent-status/presentation/agent-list-status' import type { CheckStatus, ProviderCheckSummary } from './github/pull-request-types' import type { AgentChildWorkView } from './agent-status/child-work/agent-status-child-work-view' import type { AgentSubagentSnapshot } from './agent-status/contracts/agent-status-subagent-snapshot' @@ -63,6 +64,8 @@ export type RuntimeWorktreeAgentRow = { hasLivePty?: true /** The program's own OSC 7501 report; never decides `state`. Optional: old hosts never send it. */ programStatus?: ProgramStatusFacet + /** How the desktop Agents list shows this agent. Omitted with no desktop window, by old hosts, and for a turn newer than the window's last verdicts. */ + activity?: AgentListVerdict } export type RuntimeWorktreePsSummary = { From 96ac06c00f55dd2a3659677a273ad4357704caac Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:31:50 +0000 Subject: [PATCH 07/23] feat(mobile): add an Agents tab listing every agent across your desktops (#39244) * feat(agents): send paired phones the desktop Agents list's verdict per agent While a phone is paired, the desktop window publishes its own Agents-list classification for each pane (listed, status, unread, clearable, title, worker parent) and worktree.ps attaches it to each agent row, so the phone lists agents exactly as the sidebar does. agentActivity.setRead/clear apply through the sidebar's own Activity actions and resolve once the new verdicts are stored. * feat(mobile): add an Agents tab to Home One row per agent across every paired desktop, grouped by status, with a desktop filter, search, group-by, nested workers and a long-press menu. Feed's per-workspace Agents section becomes a short Needs you list, and the needs-you badge moves to the Agents tab. --- ...x-worktree.home-catalog-worktree.ps-1.json | 104 ++--- .../goldens/worktree-home-catalog.json | 90 ++--- mobile/src/agents/MobileAgentListRows.tsx | 276 +++++++++++++ mobile/src/agents/agent-list-model.test.ts | 169 ++++++++ mobile/src/agents/agent-list-model.ts | 343 ++++++++++++++++ mobile/src/agents/agent-list-preferences.ts | 33 ++ mobile/src/agents/agent-list-row-text.ts | 61 +++ .../src/agents/use-agent-list-row-actions.tsx | 88 +++++ mobile/src/home/MobileHomeDesktopRow.tsx | 10 +- mobile/src/home/MobileHomeHostList.tsx | 6 +- mobile/src/home/MobileHomeJumpBackIn.tsx | 171 -------- mobile/src/home/MobileHomeNeedsYou.tsx | 45 +++ mobile/src/home/MobileHomeScreen.tsx | 40 +- mobile/src/home/MobileHomeSectionHeading.tsx | 40 +- mobile/src/home/home-list-styles.ts | 10 +- mobile/src/home/tabs/MobileHomeAgentsTab.tsx | 374 ++++++++++++++++++ mobile/src/home/tabs/MobileHomeFeedTab.tsx | 26 +- mobile/src/home/tabs/MobileHomeHostPill.tsx | 75 ++-- mobile/src/home/tabs/MobileHomeTabBar.tsx | 17 +- mobile/src/home/tabs/MobileHomeTabHeader.tsx | 19 +- mobile/src/home/tabs/home-tabs.ts | 10 +- mobile/src/home/use-mobile-home-data.ts | 66 ++-- .../home/use-mobile-home-host-connections.ts | 4 +- mobile/src/i18n/en-runtime-required.json | 12 + mobile/src/i18n/locales/de.json | 6 - mobile/src/i18n/locales/en.json | 74 +++- mobile/src/i18n/locales/es.json | 6 - mobile/src/i18n/locales/fr.json | 6 - mobile/src/i18n/locales/ja.json | 6 - mobile/src/i18n/locales/ko.json | 6 - mobile/src/i18n/locales/pt.json | 6 - mobile/src/i18n/locales/ru.json | 6 - mobile/src/i18n/locales/tr.json | 6 - mobile/src/i18n/locales/zh-Hant.json | 6 - mobile/src/i18n/locales/zh.json | 6 - .../src/worktree/home-host-worktree-fetch.ts | 6 +- mobile/src/worktree/home-jump-back-in.test.ts | 157 -------- mobile/src/worktree/home-jump-back-in.ts | 171 -------- mobile/src/worktree/home-resume-card.test.ts | 155 -------- mobile/src/worktree/home-resume-card.ts | 87 ---- mobile/src/worktree/home-worktree-info.ts | 53 ++- 41 files changed, 1761 insertions(+), 1091 deletions(-) create mode 100644 mobile/src/agents/MobileAgentListRows.tsx create mode 100644 mobile/src/agents/agent-list-model.test.ts create mode 100644 mobile/src/agents/agent-list-model.ts create mode 100644 mobile/src/agents/agent-list-preferences.ts create mode 100644 mobile/src/agents/agent-list-row-text.ts create mode 100644 mobile/src/agents/use-agent-list-row-actions.tsx delete mode 100644 mobile/src/home/MobileHomeJumpBackIn.tsx create mode 100644 mobile/src/home/MobileHomeNeedsYou.tsx create mode 100644 mobile/src/home/tabs/MobileHomeAgentsTab.tsx delete mode 100644 mobile/src/worktree/home-jump-back-in.test.ts delete mode 100644 mobile/src/worktree/home-jump-back-in.ts delete mode 100644 mobile/src/worktree/home-resume-card.test.ts delete mode 100644 mobile/src/worktree/home-resume-card.ts diff --git a/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json b/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json index 21ea2e4599a..ed5e635fd8f 100644 --- a/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json +++ b/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json @@ -43,41 +43,6 @@ } } }, - "0d02c4637af4": { - "name": "info", - "ordinal": 3, - "value": { - "host-1": { - "activeCount": 2, - "attention": [ - { - "branch": { - "$rpc": "undefined" - }, - "displayName": "One", - "dotStatus": "working", - "lastOutputAt": { - "$rpc": "undefined" - }, - "repo": "Repo", - "workingMode": { - "$rpc": "undefined" - }, - "worktreeId": "w-1" - } - ], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 - } - } - }, "11008b947f78": { "name": "worktree.ps#1", "ordinal": 1, @@ -158,6 +123,21 @@ } } }, + "19a302575563": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "lastActiveWorktree": { + "displayName": "One", + "repo": "Repo", + "status": "working", + "worktreeId": "w-1" + }, + "totalWorktrees": 2 + } + }, "298c6fbd5d42": { "name": "worktree.ps#1", "ordinal": 1, @@ -313,6 +293,25 @@ } } }, + "7858e4e82b0f": { + "name": "info", + "ordinal": 3, + "value": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "lastActiveWorktree": { + "displayName": "One", + "repo": "Repo", + "status": "working", + "worktreeId": "w-1" + }, + "totalWorktrees": 2 + } + } + }, "817623c64ce1": { "name": "worktree.ps#1", "ordinal": 1, @@ -348,37 +347,6 @@ } } }, - "87aae336d391": { - "host-1": { - "activeCount": 2, - "attention": [ - { - "branch": { - "$rpc": "undefined" - }, - "displayName": "One", - "dotStatus": "working", - "lastOutputAt": { - "$rpc": "undefined" - }, - "repo": "Repo", - "workingMode": { - "$rpc": "undefined" - }, - "worktreeId": "w-1" - } - ], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 - } - }, "922cb68379ac": { "name": "worktree.ps#1", "ordinal": 2, @@ -599,8 +567,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "87aae336d391", - "effects": ["0d02c4637af4"] + "state": "19a302575563", + "effects": ["7858e4e82b0f"] } }, { diff --git a/mobile/rpc-foundation/goldens/worktree-home-catalog.json b/mobile/rpc-foundation/goldens/worktree-home-catalog.json index 39c48cc8afa..a8c20584939 100644 --- a/mobile/rpc-foundation/goldens/worktree-home-catalog.json +++ b/mobile/rpc-foundation/goldens/worktree-home-catalog.json @@ -4,39 +4,19 @@ "family": "worktree.home-catalog", "namedDeltas": [], "values": { - "0d02c4637af4": { - "name": "info", - "ordinal": 3, - "value": { - "host-1": { - "activeCount": 2, - "attention": [ - { - "branch": { - "$rpc": "undefined" - }, - "displayName": "One", - "dotStatus": "working", - "lastOutputAt": { - "$rpc": "undefined" - }, - "repo": "Repo", - "workingMode": { - "$rpc": "undefined" - }, - "worktreeId": "w-1" - } - ], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 - } + "19a302575563": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "lastActiveWorktree": { + "displayName": "One", + "repo": "Repo", + "status": "working", + "worktreeId": "w-1" + }, + "totalWorktrees": 2 } }, "34fb08d01b03": { @@ -70,35 +50,23 @@ } }, "44136fa355b3": {}, - "87aae336d391": { - "host-1": { - "activeCount": 2, - "attention": [ - { - "branch": { - "$rpc": "undefined" - }, + "7858e4e82b0f": { + "name": "info", + "ordinal": 3, + "value": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "lastActiveWorktree": { "displayName": "One", - "dotStatus": "working", - "lastOutputAt": { - "$rpc": "undefined" - }, "repo": "Repo", - "workingMode": { - "$rpc": "undefined" - }, + "status": "working", "worktreeId": "w-1" - } - ], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 + }, + "totalWorktrees": 2 + } } }, "922cb68379ac": { @@ -193,8 +161,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "87aae336d391", - "effects": ["0d02c4637af4"] + "state": "19a302575563", + "effects": ["7858e4e82b0f"] } } ] diff --git a/mobile/src/agents/MobileAgentListRows.tsx b/mobile/src/agents/MobileAgentListRows.tsx new file mode 100644 index 00000000000..5a5e84fbe17 --- /dev/null +++ b/mobile/src/agents/MobileAgentListRows.tsx @@ -0,0 +1,276 @@ +import { ChevronDown, ChevronRight } from 'lucide-react-native' +import { Fragment, memo, useCallback, useState } from 'react' +import { Alert, Pressable, Text, View } from 'react-native' +import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' +import type { WorktreeStatus } from '../../../src/shared/worktree-status-rollup' +import { AgentSpinner, agentStatusColors } from '../components/AgentSpinner' +import { MobileAgentIcon } from '../components/MobileAgentIcon' +import { HOME_ROW_TEXT_INSET, homeListStyles } from '../home/home-list-styles' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { triggerMediumImpact } from '../platform/haptics' +import { colors, spacing } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import type { HostProfile } from '../transport/hosts/host-profile' +import { useHostDisplay } from '../transport/hosts/use-host-display' +import { agentStateLabel, formatTimeAgo, type AgentDotState } from '../worktree/agent-row-display' +import { isDisclosureOpen, toggleDisclosure } from '../worktree/agent-child-disclosure' +import { areStructurallyEqual } from '../worktree/structural-equality' +import { agentStatusGroup, type AgentListRow, type AgentListSection } from './agent-list-model' +import { agentListPreview, agentListTitle } from './agent-list-row-text' + +// The Home rollup glyph is the list's size; this maps a per-agent state onto its palette. +const GLYPH_STATUS: Record = { + working: 'working', + monitoring: 'monitoring', + blocked: 'permission', + waiting: 'permission', + failed: 'failed', + done: 'done', + interrupted: 'interrupted', + unconfirmed: 'unconfirmed', + idle: 'inactive', + unverifiable: 'inactive' +} + +const WORKER_INDENT = 22 +const TOGGLE_HIT_SLOP = { top: 10, bottom: 10, left: 12, right: 12 } as const + +const workersKey = (row: AgentListRow) => `agents:workers:${row.key}` + +type ShownRow = { row: AgentListRow; key: string; workersOpen?: boolean } + +export type AgentListRowHandlers = Readonly<{ + onOpen: (row: AgentListRow) => void + onLongPress: (row: AgentListRow) => void +}> + +/** One inset group of agent rows, with each coordinator's workers and an optional idle fold. */ +export function MobileAgentListRows( + props: AgentListRowHandlers & { + rows: readonly AgentListRow[] + idleRows?: readonly AgentListRow[] + footer: AgentListSection['footer'] + nameDesktop: boolean + hosts: readonly HostProfile[] + now: number + /** Remembers the idle fold per list. */ + idleKey?: string + } +) { + const t = useMobileTranslation() + useMobileColorScheme() + // Disclosures live in a module cache so they survive remounts; this only redraws after a toggle. + const [, setRevision] = useState(0) + const toggle = useCallback((key: string) => { + toggleDisclosure(key) + setRevision((revision) => revision + 1) + }, []) + const idleKey = `agents:idle:${props.idleKey ?? ''}` + const idleOpen = isDisclosureOpen(idleKey) + const idleRows = props.idleRows ?? [] + const hostById = new Map(props.hosts.map((host) => [host.id, host])) + const withWorkers = (rows: readonly AgentListRow[], prefix: string) => + rows.flatMap((row): ShownRow[] => { + const key = `${prefix}${row.key}` + const workersOpen = row.workers.length > 0 ? isDisclosureOpen(workersKey(row)) : undefined + const workers = workersOpen + ? row.workers.map((worker) => ({ row: worker, key: `${key}>${worker.key}` })) + : [] + return [{ row, key, workersOpen }, ...workers] + }) + const renderRows = (items: readonly ShownRow[], separateFirst: boolean) => + items.map((item, index) => ( + + {index > 0 || separateFirst ? ( + + ) : null} + + + )) + return ( + + {renderRows(withWorkers(props.rows, ''), false)} + {idleRows.length > 0 ? ( + <> + {props.rows.length > 0 ? : null} + [styles.foldRow, pressed && homeListStyles.rowPressed]} + onPress={() => toggle(idleKey)} + > + {idleOpen ? ( + + ) : ( + + )} + + {t('agents.list.idleCount', '{{count}} idle', { count: idleRows.length })} + + + {idleOpen ? renderRows(withWorkers(idleRows, 'idle>'), true) : null} + + ) : null} + + ) +} + +// Each refresh rebuilds every row; compare by value so only changed rows redraw. +const MobileAgentListRow = memo(function MobileAgentListRow( + props: AgentListRowHandlers & { + row: AgentListRow + host: HostProfile | null + footer: AgentListSection['footer'] + nameDesktop: boolean + now: number + /** Undefined when the row has no workers to show. */ + workersOpen?: boolean + onToggleWorkers: (key: string) => void + } +) { + const t = useMobileTranslation() + useMobileColorScheme() + const { row } = props + const { agent } = row.entry + const desktop = useHostDisplay(props.host).title + const title = agentListTitle(agent) + const group = row.stale ? null : agentStatusGroup(row.dotState) + const preview = agentListPreview(agent, group) + const needsYou = group === 'needs-you' + const stateWord = needsYou ? agentStateLabel(row.dotState) : '' + const place = [ + props.footer === 'agent' ? formatAgentTypeLabel(agent.agentType) : row.entry.workspaceName, + props.nameDesktop ? desktop : null + ] + .filter(Boolean) + .join(' · ') + const time = row.timeAt > 0 ? formatTimeAgo(row.timeAt, props.now) : '' + const workerCount = row.workers.length + const longPress = () => { + triggerMediumImpact() + props.onLongPress(row) + } + const open = () => { + if (row.offline) { + Alert.alert( + t('agents.list.offlineTitle', '{{desktop}} is offline', { desktop }), + t('agents.list.offlineMessage', 'Reconnect it to open this agent.') + ) + return + } + props.onOpen(row) + } + const actionsLabel = t('agents.list.actions', 'Actions for {{title}}', { title }) + return ( + { + if (event.nativeEvent.actionName === 'longpress') { + longPress() + } + }} + style={({ pressed }) => [ + homeListStyles.row, + row.depth > 0 && { paddingLeft: spacing.lg + row.depth * WORKER_INDENT }, + pressed && homeListStyles.rowPressed + ]} + onPress={open} + onLongPress={longPress} + delayLongPress={400} + > + + + + + + + {title} + + {time ? {time} : null} + + {stateWord || preview ? ( + + {stateWord ? ( + + {stateWord} + + ) : null} + {stateWord && preview ? ' · ' : ''} + {preview} + + ) : null} + + {agent.agentType ? : null} + + {place} + + {props.workersOpen !== undefined ? ( + { + event.stopPropagation() + props.onToggleWorkers(workersKey(row)) + }} + > + {props.workersOpen ? ( + + ) : ( + + )} + + {workerCount === 1 + ? t('agents.list.workers_one', '{{count}} worker', { count: workerCount }) + : t('agents.list.workers_other', '{{count}} workers', { count: workerCount })} + + + ) : null} + + + + ) +}, areStructurallyEqual) + +const styles = themedStyleSheet(() => ({ + text: { flex: 1, minWidth: 0, paddingTop: 9, paddingBottom: 10, paddingRight: 14, gap: 3 }, + titleLine: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm }, + title: { flex: 1, minWidth: 0, fontSize: 15, lineHeight: 20, color: colors.textPrimary }, + time: { fontSize: 12, color: colors.textMuted, fontVariant: ['tabular-nums'] }, + preview: { fontSize: 14, lineHeight: 19, color: colors.textSecondary }, + stateWord: { fontWeight: '600' }, + footer: { flexDirection: 'row', alignItems: 'center', gap: 6, minWidth: 0 }, + place: { flexShrink: 1, fontSize: 12, color: colors.textMuted }, + workers: { flexDirection: 'row', alignItems: 'center', gap: 4, marginLeft: 'auto' }, + workersLabel: { fontSize: 12, fontWeight: '500', color: colors.textSecondary }, + foldRow: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + minHeight: 44, + paddingLeft: HOME_ROW_TEXT_INSET - 4, + paddingRight: spacing.lg + }, + foldLabel: { fontSize: 14, color: colors.textSecondary } +})) diff --git a/mobile/src/agents/agent-list-model.test.ts b/mobile/src/agents/agent-list-model.test.ts new file mode 100644 index 00000000000..4bbb12b74e6 --- /dev/null +++ b/mobile/src/agents/agent-list-model.test.ts @@ -0,0 +1,169 @@ +import { describe, expect, it } from 'vitest' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { ConnectionState } from '../transport/connection/connection-state' +import type { HostWorktreeInfo } from '../worktree/home-worktree-info' +import { + buildAgentList, + selectAgentsNeedingYou, + type AgentListInput, + type AgentListRow, + type AgentListSection +} from './agent-list-model' + +const NOW = 1_800_000_000_000 +const MINUTE = 60_000 + +function agent( + paneKey: string, + state: RuntimeWorktreeAgentRow['state'], + overrides: Partial = {} +): RuntimeWorktreeAgentRow { + return { + paneKey, + parentPaneKey: null, + state, + agentType: 'claude', + prompt: '', + taskTitle: null, + displayName: null, + lastAssistantMessage: null, + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: NOW - MINUTE, + updatedAt: NOW - MINUTE, + ...overrides + } +} + +function entries(agents: RuntimeWorktreeAgentRow[]) { + return agents.map((row) => ({ + worktreeId: 'wt-1', + workspaceName: 'mobile-tabs', + repo: 'orca', + branch: 'main', + agent: row + })) +} + +function input( + hosts: Record }> +): AgentListInput { + return { + hosts: Object.keys(hosts).map((id) => ({ id })), + hostStates: Object.fromEntries(Object.entries(hosts).map(([id, host]) => [id, host.state])), + worktreeInfo: Object.fromEntries( + Object.entries(hosts).map(([id, host]) => [ + id, + { hostId: id, totalWorktrees: 1, activeCount: 0, lastActiveWorktree: null, ...host.info } + ]) + ), + now: NOW + } +} + +const panes = (rows: readonly AgentListRow[] | undefined) => + rows?.map((row) => row.entry.agent.paneKey) +const shape = (sections: AgentListSection[]) => + sections.map((section) => ({ + kind: section.kind, + rows: panes(section.rows), + workers: section.rows.map((row) => panes(row.workers)), + idle: panes(section.idleRows) + })) +const statusView = (showWorkers: boolean) => ({ + view: { groupBy: 'status' as const, showWorkers }, + hostFilter: null, + query: '' +}) + +describe('buildAgentList by status', () => { + it('buckets agents by what they ask of the user, newest first, and folds idle ones', () => { + const list = buildAgentList( + input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('asking', 'waiting'), + agent('older-run', 'working', { stateStartedAt: NOW - 5 * MINUTE }), + agent('newer-run', 'working', { stateStartedAt: NOW - 2 * MINUTE }), + agent('finished', 'done'), + // Silent past the 30-minute freshness window. + agent('quiet', 'working', { updatedAt: NOW - 31 * MINUTE }) + ]) + } + } + }), + statusView(true) + ) + expect(shape(list.sections)).toEqual([ + { kind: 'needs-you', rows: ['asking'], workers: [[]], idle: undefined }, + { + kind: 'working', + rows: ['newer-run', 'older-run'], + workers: [[], []], + idle: undefined + }, + { kind: 'done', rows: ['finished'], workers: [[]], idle: ['quiet'] } + ]) + }) + + it('nests workers under their coordinator and still lists the one that needs the user', () => { + const host = input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('coordinator', 'working'), + agent('worker-busy', 'working', { parentPaneKey: 'coordinator' }), + agent('worker-asking', 'blocked', { parentPaneKey: 'coordinator' }) + ]) + } + } + }) + expect(shape(buildAgentList(host, statusView(true)).sections)).toEqual([ + { kind: 'needs-you', rows: ['worker-asking'], workers: [[]], idle: undefined }, + { + kind: 'working', + rows: ['coordinator'], + workers: [['worker-busy', 'worker-asking']], + idle: undefined + } + ]) + expect(shape(buildAgentList(host, statusView(false)).sections)).toEqual([ + { kind: 'needs-you', rows: ['worker-asking'], workers: [[]], idle: undefined }, + { kind: 'working', rows: ['coordinator'], workers: [[]], idle: undefined } + ]) + expect(panes(selectAgentsNeedingYou(host))).toEqual(['worker-asking']) + }) + + it('keeps a lost desktop’s agents as last seen, outside the status groups and the counts', () => { + const lastSeen = entries([agent('was-asking', 'waiting')]) + const disconnected = input({ + mac: { state: 'connected', info: { agents: entries([agent('asking', 'waiting')]) } }, + studio: { state: 'disconnected', info: { lastSeenAgents: lastSeen, countsProvenAt: NOW } } + }) + const list = buildAgentList(disconnected, statusView(true)) + expect(shape(list.sections)).toEqual([ + { kind: 'needs-you', rows: ['asking'], workers: [[]], idle: undefined }, + { kind: 'desktop', rows: ['was-asking'], workers: [[]], idle: undefined } + ]) + expect(list.sections[1]).toMatchObject({ + hostId: 'studio', + lastSeen: { offline: true, at: NOW } + }) + expect(list.sections[1].rows[0]).toMatchObject({ stale: true, offline: true, dotState: 'idle' }) + expect(panes(selectAgentsNeedingYou(disconnected))).toEqual(['asking']) + + // Reconnected, but until its own read lands the old rows still claim nothing. + const reconnected = input({ + studio: { state: 'connected', info: { lastSeenAgents: lastSeen, countsProvenAt: NOW } } + }) + expect(selectAgentsNeedingYou(reconnected)).toEqual([]) + expect(buildAgentList(reconnected, statusView(true)).sections[0].rows[0]).toMatchObject({ + stale: true, + offline: false + }) + }) +}) diff --git a/mobile/src/agents/agent-list-model.ts b/mobile/src/agents/agent-list-model.ts new file mode 100644 index 00000000000..7b99eead86c --- /dev/null +++ b/mobile/src/agents/agent-list-model.ts @@ -0,0 +1,343 @@ +import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { ConnectionState } from '../transport/connection/connection-state' +import { agentDotState, agentRowTimeAt, type AgentDotState } from '../worktree/agent-row-display' +import { flattenAgentRowLineage, type AgentRowNode } from '../worktree/agent-row-lineage' +import type { HomeAgentEntry, HostWorktreeInfo } from '../worktree/home-worktree-info' +import { agentListEntryMatches } from './agent-list-row-text' + +export const AGENT_LIST_GROUP_BY_CHOICES = [ + 'status', + 'workspace', + 'project', + 'agent', + 'desktop' +] as const + +export type AgentListGroupBy = (typeof AGENT_LIST_GROUP_BY_CHOICES)[number] + +export type AgentListView = Readonly<{ groupBy: AgentListGroupBy; showWorkers: boolean }> + +export const DEFAULT_AGENT_LIST_VIEW: AgentListView = { groupBy: 'status', showWorkers: true } + +export type AgentStatusGroup = 'needs-you' | 'working' | 'done' | 'idle' + +export function agentStatusGroup(state: AgentDotState): AgentStatusGroup { + switch (state) { + case 'blocked': + case 'waiting': + case 'failed': + return 'needs-you' + case 'working': + case 'monitoring': + return 'working' + case 'done': + case 'interrupted': + case 'unconfirmed': + return 'done' + case 'idle': + case 'unverifiable': + return 'idle' + } +} + +export type AgentListRow = Readonly<{ + key: string + hostId: string + entry: HomeAgentEntry + dotState: AgentDotState + timeAt: number + /** A copy from a read the desktop no longer backs: it claims no state. */ + stale: boolean + /** Its desktop isn't connected, so the row can't open. */ + offline: boolean + depth: number + /** Nested workers in tree order; empty when workers are hidden. */ + workers: readonly AgentListRow[] +}> + +export type AgentListSectionKind = AgentStatusGroup | 'workspace' | 'project' | 'agent' | 'desktop' + +export type AgentListSection = Readonly<{ + key: string + kind: AgentListSectionKind + /** The workspace, project or agent a data-named section is for. */ + title?: string + hostId?: string + rows: readonly AgentListRow[] + /** Status grouping folds idle agents into one row at the end of the list. */ + idleRows?: readonly AgentListRow[] + /** A desktop whose rows are last seen, and when they were read. */ + lastSeen?: Readonly<{ offline: boolean; at?: number }> + /** What each row's footer names; the section header names the rest. */ + footer: 'workspace' | 'agent' + nameDesktop: boolean +}> + +export type AgentListInput = Readonly<{ + /** Paired desktops in Home's order. */ + hosts: readonly { id: string }[] + hostStates: Readonly> + worktreeInfo: Readonly> + now: number +}> + +type HostAgents = { + hostId: string + roots: AgentListRow[] + live: boolean + offline: boolean + seenAt?: number +} + +function hostAgents(input: AgentListInput, hostId: string): HostAgents { + const info = input.worktreeInfo[hostId] + const connected = input.hostStates[hostId] === 'connected' + // Only this connection's own read may show states; anything else is what the agents last were. + const liveAgents = connected && !info?.catalogUnavailable ? info?.agents : undefined + const live = liveAgents !== undefined + const entries = liveAgents ?? info?.lastSeenAgents ?? info?.agents ?? [] + const entryByAgent = new Map( + entries.map((entry) => [entry.agent, entry]) + ) + const toRow = (node: AgentRowNode, depth: number): AgentListRow | null => { + const entry = entryByAgent.get(node.row) + if (!entry) { + return null + } + return { + key: `${hostId}:${node.row.paneKey}`, + hostId, + entry, + dotState: live ? agentDotState(node.row, input.now) : 'idle', + timeAt: agentRowTimeAt(node.row), + stale: !live, + offline: !connected, + depth, + workers: node.children.flatMap((child) => descendants(child, depth + 1)) + } + } + const descendants = (node: AgentRowNode, depth: number): AgentListRow[] => { + const row = toRow(node, depth) + return row ? [{ ...row, workers: [] }, ...row.workers] : [] + } + // Lineage spans the desktop: a coordinator's workers often run in other workspaces. + const roots = flattenAgentRowLineage(entries.map((entry) => entry.agent)) + .filter((node) => node.depth === 0) + .map((node) => toRow(node, 0)) + .filter((row): row is AgentListRow => row !== null) + return { hostId, roots, live, offline: !connected, seenAt: info?.countsProvenAt } +} + +function everyRow(roots: readonly AgentListRow[]): AgentListRow[] { + return roots.flatMap((row) => [row, ...row.workers]) +} + +const asTopLevel = (row: AgentListRow): AgentListRow => ({ ...row, depth: 0, workers: [] }) + +const newestFirst = (a: AgentListRow, b: AgentListRow): number => b.timeAt - a.timeAt + +function needsYou(row: AgentListRow): boolean { + return !row.stale && agentStatusGroup(row.dotState) === 'needs-you' +} + +/** Live agents that need the user, workers included: Feed's rows and both badge counts. */ +export function selectAgentsNeedingYou(input: AgentListInput): AgentListRow[] { + return input.hosts + .flatMap((host) => everyRow(hostAgents(input, host.id).roots)) + .filter(needsYou) + .map(asTopLevel) + .sort(newestFirst) +} + +export function countAgentsNeedingYouByHost( + rows: readonly AgentListRow[] +): Readonly> { + const counts: Record = {} + for (const row of rows) { + counts[row.hostId] = (counts[row.hostId] ?? 0) + 1 + } + return counts +} + +export type AgentListHostSummary = Readonly<{ + hostId: string + agents: number + needsYou: number + offline: boolean +}> + +export function summarizeAgentListHosts(input: AgentListInput): AgentListHostSummary[] { + return input.hosts.map((host) => { + const agents = hostAgents(input, host.id) + const rows = everyRow(agents.roots) + return { + hostId: host.id, + agents: rows.length, + needsYou: rows.filter(needsYou).length, + offline: agents.offline + } + }) +} + +type GroupDraft = { key: string; title?: string; hostId?: string; rows: AgentListRow[] } + +function groupRows( + rows: readonly AgentListRow[], + keyOf: (row: AgentListRow) => Omit +): GroupDraft[] { + const groups = new Map() + for (const row of rows) { + const draft = keyOf(row) + const group = groups.get(draft.key) + if (group) { + group.rows.push(row) + } else { + groups.set(draft.key, { ...draft, rows: [row] }) + } + } + return [...groups.values()] +} + +// Groups with something that needs the user lead, then the most recently active. +function byUrgencyThenRecent(a: GroupDraft, b: GroupDraft): number { + const urgent = (group: GroupDraft) => (group.rows.some(needsYou) ? 0 : 1) + const latest = (group: GroupDraft) => Math.max(...group.rows.map((row) => row.timeAt)) + return urgent(a) - urgent(b) || latest(b) - latest(a) +} + +const STATUS_SECTIONS: readonly Exclude[] = [ + 'needs-you', + 'working', + 'done' +] + +export function buildAgentList( + input: AgentListInput, + options: Readonly<{ view: AgentListView; hostFilter: string | null; query: string }> +): { sections: AgentListSection[]; total: number } { + const { view } = options + const hosts = input.hosts + .filter((host) => options.hostFilter === null || host.id === options.hostFilter) + .map((host) => hostAgents(input, host.id)) + const total = hosts.reduce((sum, host) => sum + everyRow(host.roots).length, 0) + const nameDesktop = input.hosts.length > 1 && options.hostFilter === null + const query = options.query.trim().toLowerCase() + + const topLevel = (host: HostAgents): AgentListRow[] => { + if (query) { + // A match is shown on its own; its coordinator may not match. + return everyRow(host.roots) + .filter((row) => agentListEntryMatches(row.entry, query)) + .map(asTopLevel) + } + const roots = view.showWorkers ? host.roots : host.roots.map(asTopLevel) + // A worker that needs the user can't hide inside a folded coordinator. + const surfaced = host.roots.flatMap((root) => root.workers.filter(needsYou).map(asTopLevel)) + return [...roots, ...surfaced] + } + + const section = ( + draft: GroupDraft, + kind: AgentListSectionKind, + footer: AgentListSection['footer'], + names: boolean + ): AgentListSection => ({ + ...draft, + kind, + rows: [...draft.rows].sort(newestFirst), + footer, + nameDesktop: names + }) + + if (view.groupBy === 'desktop') { + const sections = hosts.flatMap((host): AgentListSection[] => { + const rows = topLevel(host) + // An offline desktop keeps its header, so its absence reads as offline rather than idle. + if (rows.length === 0 && (host.live || query)) { + return [] + } + return [ + { + ...section( + { key: host.hostId, hostId: host.hostId, rows }, + 'desktop', + 'workspace', + false + ), + ...(host.live ? {} : { lastSeen: { offline: host.offline, at: host.seenAt } }) + } + ] + }) + return { sections, total } + } + + if (view.groupBy === 'status') { + const live = hosts.filter((host) => host.live).flatMap(topLevel) + const sections: AgentListSection[] = STATUS_SECTIONS.map((kind) => + section( + { key: kind, rows: live.filter((row) => agentStatusGroup(row.dotState) === kind) }, + kind, + 'workspace', + nameDesktop + ) + ).filter((entry) => entry.rows.length > 0) + const idleRows = live.filter((row) => agentStatusGroup(row.dotState) === 'idle') + if (idleRows.length > 0) { + const folded = [...idleRows].sort(newestFirst) + const last = sections.at(-1) + if (last) { + sections[sections.length - 1] = { ...last, idleRows: folded } + } else { + sections.push({ + ...section({ key: 'idle', rows: [] }, 'idle', 'workspace', nameDesktop), + idleRows: folded + }) + } + } + // Last-seen rows claim no status, so they stay under their desktop. + for (const host of hosts) { + const rows = host.live ? [] : topLevel(host) + if (rows.length > 0) { + sections.push({ + ...section( + { key: host.hostId, hostId: host.hostId, rows }, + 'desktop', + 'workspace', + false + ), + lastSeen: { offline: host.offline, at: host.seenAt } + }) + } + } + return { sections, total } + } + + const rows = hosts.flatMap(topLevel) + const drafts = + view.groupBy === 'workspace' + ? groupRows(rows, (row) => ({ + key: `${row.hostId}:${row.entry.worktreeId}`, + title: row.entry.workspaceName, + hostId: row.hostId + })) + : view.groupBy === 'project' + ? groupRows(rows, (row) => ({ + key: `${row.hostId}:${row.entry.repo}`, + title: row.entry.repo, + hostId: row.hostId + })) + : groupRows(rows, (row) => { + const label = formatAgentTypeLabel(row.entry.agent.agentType) + return { key: label, title: label } + }) + const kind = view.groupBy + const sections = drafts + .sort(byUrgencyThenRecent) + .map((draft) => + kind === 'agent' + ? section(draft, kind, 'workspace', nameDesktop) + : section(draft, kind, kind === 'workspace' ? 'agent' : 'workspace', false) + ) + return { sections, total } +} diff --git a/mobile/src/agents/agent-list-preferences.ts b/mobile/src/agents/agent-list-preferences.ts new file mode 100644 index 00000000000..30da78f1ba7 --- /dev/null +++ b/mobile/src/agents/agent-list-preferences.ts @@ -0,0 +1,33 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' +import { + AGENT_LIST_GROUP_BY_CHOICES, + DEFAULT_AGENT_LIST_VIEW, + type AgentListView +} from './agent-list-model' + +const AGENT_LIST_VIEW_KEY = 'orca:agentListView' + +export async function loadAgentListView(): Promise { + try { + const raw = await AsyncStorage.getItem(AGENT_LIST_VIEW_KEY) + const parsed: unknown = raw ? JSON.parse(raw) : null + if (!parsed || typeof parsed !== 'object') { + return DEFAULT_AGENT_LIST_VIEW + } + const groupBy = 'groupBy' in parsed ? parsed.groupBy : undefined + const showWorkers = 'showWorkers' in parsed ? parsed.showWorkers : undefined + return { + groupBy: + AGENT_LIST_GROUP_BY_CHOICES.find((choice) => choice === groupBy) ?? + DEFAULT_AGENT_LIST_VIEW.groupBy, + showWorkers: + typeof showWorkers === 'boolean' ? showWorkers : DEFAULT_AGENT_LIST_VIEW.showWorkers + } + } catch { + return DEFAULT_AGENT_LIST_VIEW + } +} + +export async function saveAgentListView(view: AgentListView): Promise { + await AsyncStorage.setItem(AGENT_LIST_VIEW_KEY, JSON.stringify(view)) +} diff --git a/mobile/src/agents/agent-list-row-text.ts b/mobile/src/agents/agent-list-row-text.ts new file mode 100644 index 00000000000..81ff91a29dc --- /dev/null +++ b/mobile/src/agents/agent-list-row-text.ts @@ -0,0 +1,61 @@ +import { getAgentRowPrimaryText } from '../../../src/shared/agent-status/presentation/agent-row-primary-text' +import { formatAgentToolPreviewLine } from '../../../src/shared/agent-status/presentation/agent-tool-preview' +import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' +import { withoutNativeChatVisualDirectiveLines } from '../../../src/shared/native-chat/native-chat-visual-directive' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { HomeAgentEntry } from '../worktree/home-worktree-info' +import type { AgentStatusGroup } from './agent-list-model' + +/** The row's name: what the conversation is called, else its task, else what it was asked. */ +export function agentListTitle(agent: RuntimeWorktreeAgentRow): string { + return ( + agent.conversationName?.trim() || + agent.displayName?.trim() || + agent.taskTitle?.trim() || + getAgentRowPrimaryText({ prompt: agent.prompt }) || + formatAgentTypeLabel(agent.agentType) + ) +} + +function oneLine(text: string | null | undefined): string { + return text?.replace(/\s+/g, ' ').trim() ?? '' +} + +function lastMessage(agent: RuntimeWorktreeAgentRow): string { + const message = agent.lastAssistantMessage + return message ? oneLine(withoutNativeChatVisualDirectiveLines(message)) : '' +} + +/** + * The row's second line: what it waits on or is doing, else what it last said. A last-seen row + * (`group` null) shows no tool, since the tool call is long over. + */ +export function agentListPreview( + agent: RuntimeWorktreeAgentRow, + group: AgentStatusGroup | null +): string { + const tool = group === null ? '' : oneLine(formatAgentToolPreviewLine(agent, false)) + const preview = + group === 'needs-you' || group === 'working' + ? tool || lastMessage(agent) + : lastMessage(agent) || tool + if (preview) { + return preview + } + const prompt = oneLine(getAgentRowPrimaryText({ prompt: agent.prompt })) + return prompt === agentListTitle(agent) ? '' : prompt +} + +/** Search covers what the row shows plus the prompt; `query` is already lower-cased. */ +export function agentListEntryMatches(entry: HomeAgentEntry, query: string): boolean { + const { agent } = entry + return [ + agentListTitle(agent), + entry.workspaceName, + entry.branch, + entry.repo, + formatAgentTypeLabel(agent.agentType), + agent.prompt, + agent.lastAssistantMessage + ].some((field) => field?.toLowerCase().includes(query)) +} diff --git a/mobile/src/agents/use-agent-list-row-actions.tsx b/mobile/src/agents/use-agent-list-row-actions.tsx new file mode 100644 index 00000000000..a86ee0c2b56 --- /dev/null +++ b/mobile/src/agents/use-agent-list-row-actions.tsx @@ -0,0 +1,88 @@ +import { ArrowUpRight, Copy, Folder } from 'lucide-react-native' +import { useCallback, useMemo, useState } from 'react' +import { Alert } from 'react-native' +import { ActionSheetModal } from '../components/ActionSheetModal' +import { TransientToast, useTransientToast } from '../components/TransientToast' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { useClipboardWriter } from '../platform/clipboard' +import { useOpenMobileSession } from '../session/use-open-mobile-session' +import type { AgentListRow } from './agent-list-model' +import { agentListTitle } from './agent-list-row-text' +import type { AgentListRowHandlers } from './MobileAgentListRows' + +/** Tap opens the agent's tab; long-press offers it, its workspace and its title. Shared by Feed and Agents. */ +export function useAgentListRowActions(toastBottomInset: number) { + const t = useMobileTranslation() + const openMobileSession = useOpenMobileSession() + const clipboard = useClipboardWriter() + const { message, showToast } = useTransientToast() + const [target, setTarget] = useState(null) + + const open = useCallback( + (row: AgentListRow, withPane: boolean) => + openMobileSession({ + hostId: row.hostId, + worktreeId: row.entry.worktreeId, + name: row.entry.workspaceName, + ...(withPane ? { paneKey: row.entry.agent.paneKey } : {}) + }), + [openMobileSession] + ) + const handlers = useMemo( + () => ({ onOpen: (row) => open(row, true), onLongPress: setTarget }), + [open] + ) + + const title = target ? agentListTitle(target.entry.agent) : undefined + const offlineHint = target?.offline + ? t('agents.actions.offlineHint', 'Its desktop is offline.') + : undefined + const sheet = ( + <> + open(target, true) + }, + { + id: 'workspace', + label: t('agents.actions.goToWorkspace', 'Go to workspace'), + icon: Folder, + disabled: target.offline, + hint: offlineHint, + closeBeforePress: true, + onPress: () => open(target, false) + }, + { + id: 'copy-title', + label: t('agents.actions.copyTitle', 'Copy title'), + icon: Copy, + closeBeforePress: true, + onPress: () => { + void clipboard.writeText(title ?? '').then( + () => showToast(t('agents.actions.copied', 'Copied')), + () => Alert.alert(t('agents.actions.copyFailed', 'Couldn’t copy the title')) + ) + } + } + ] + : [] + } + onClose={() => setTarget(null)} + /> + + + ) + return { handlers, sheet } +} diff --git a/mobile/src/home/MobileHomeDesktopRow.tsx b/mobile/src/home/MobileHomeDesktopRow.tsx index 617a9c29ee8..2d8786ddb8a 100644 --- a/mobile/src/home/MobileHomeDesktopRow.tsx +++ b/mobile/src/home/MobileHomeDesktopRow.tsx @@ -12,7 +12,6 @@ import type { ConnectionState } from '../transport/connection/connection-state' import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' import { colors } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import { homeAgentNeedsYou } from '../worktree/home-jump-back-in' import { homeHostWorktreeSummary, type HostWorktreeInfo } from '../worktree/home-worktree-info' import { homeListStyles as styles } from './home-list-styles' @@ -52,6 +51,8 @@ export function MobileHomeDesktopRow(props: { path: MobileConnectionPath // The row owns fresh/stale/unavailable wording so callers cannot hide retained counts again (STA-3123). worktreeInfo?: HostWorktreeInfo + /** Agents on this desktop waiting on the user. */ + needsYou: number onPress: () => void onLongPress: () => void }) { @@ -95,12 +96,7 @@ export function MobileHomeDesktopRow(props: { Boolean(line) ) const statusLine = connected && worktreeSummary.visual ? worktreeSummary.visual : statusLabel - const attention = props.worktreeInfo?.catalogUnavailable - ? undefined - : props.worktreeInfo?.attention - const needsYou = connected - ? (attention?.filter((worktree) => homeAgentNeedsYou(worktree.dotStatus)).length ?? 0) - : 0 + const needsYou = connected ? props.needsYou : 0 const needsYouLabel = needsYou > 0 ? needsYou === 1 diff --git a/mobile/src/home/MobileHomeHostList.tsx b/mobile/src/home/MobileHomeHostList.tsx index cef4133c87f..ad442bc3472 100644 --- a/mobile/src/home/MobileHomeHostList.tsx +++ b/mobile/src/home/MobileHomeHostList.tsx @@ -22,6 +22,8 @@ type MobileHomeHostListProps = { hostConnections: HomeHostConnections hosts: HostCatalogEntry[] hostStates: Record + /** Agents waiting on the user, per desktop. */ + needsYouByHost: Readonly> worktreeInfo: Record onOpen: (host: HostCatalogEntry) => void onOpenActions: (host: HostCatalogEntry) => void @@ -48,6 +50,7 @@ export function MobileHomeHostList(props: MobileHomeHostListProps) { hostLastConnected={props.hostLastConnected} hostConnections={props.hostConnections} hostStates={props.hostStates} + needsYou={props.needsYouByHost[host.id] ?? 0} worktreeInfo={props.worktreeInfo} onOpen={props.onOpen} onOpenActions={props.onOpenActions} @@ -86,7 +89,7 @@ type MobileHomeHostRowProps = Pick< | 'worktreeInfo' | 'onOpen' | 'onOpenActions' -> & { item: HostCatalogEntry } +> & { item: HostCatalogEntry; needsYou: number } const MobileHomeHostRow = memo(function MobileHomeHostRow(props: MobileHomeHostRowProps) { const { item, onOpen, onOpenActions } = props @@ -117,6 +120,7 @@ const MobileHomeHostRow = memo(function MobileHomeHostRow(props: MobileHomeHostR verdict={verdict} path={connection?.path ?? 'lan'} worktreeInfo={props.worktreeInfo[item.id]} + needsYou={props.needsYou} onPress={open} onLongPress={openActions} /> diff --git a/mobile/src/home/MobileHomeJumpBackIn.tsx b/mobile/src/home/MobileHomeJumpBackIn.tsx deleted file mode 100644 index 3af562be54c..00000000000 --- a/mobile/src/home/MobileHomeJumpBackIn.tsx +++ /dev/null @@ -1,171 +0,0 @@ -import { ChevronRight } from 'lucide-react-native' -import { memo, useMemo, useState } from 'react' -import { Pressable, Text, View } from 'react-native' -import Animated, { FadeIn, FadeOut, LinearTransition } from 'react-native-reanimated' -import type { WorktreeStatus } from '../../../src/shared/worktree-status-rollup' -import { AgentSpinner, agentStatusColors } from '../components/AgentSpinner' -import { useMobileTranslation } from '../i18n/use-mobile-translation' -import { useReducedMotionEnabled } from '../platform/use-reduced-motion' -import { colors } from '../theme/mobile-theme' -import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import { useHostDisplay } from '../transport/hosts/use-host-display' -import { areStructurallyEqual } from '../worktree/structural-equality' -import type { HostCatalogEntry } from '../transport/hosts/host-profile' -import type { HomeJumpBackInRow } from '../worktree/home-jump-back-in' -import { agentStateLabel, type AgentDotState } from '../worktree/agent-row-display' -import { homeListStyles as styles } from './home-list-styles' -import { MobileHomeSectionHeading } from './MobileHomeSectionHeading' -import { HOME_EASE_OUT } from './tabs/home-tabs' - -const LABEL_STATE: Partial> = { - permission: 'waiting', - failed: 'failed', - done: 'done', - working: 'working', - monitoring: 'monitoring' -} - -// Only states that ask something of the user take the dot's colour; running work stays quiet. -const TINTED_STATUSES: ReadonlySet = new Set(['permission', 'failed', 'done']) - -// Enough to see what needs you without the list pushing Desktops off the first screen. -const AGENT_ROWS_COLLAPSED = 5 - -// Usage, stats and connection ticks re-render Home; the section redraws only when its rows change. -export const MobileHomeJumpBackIn = memo(function MobileHomeJumpBackIn(props: { - rows: readonly HomeJumpBackInRow[] - hosts: readonly HostCatalogEntry[] - first: boolean - onOpen: (row: HomeJumpBackInRow) => void -}) { - const t = useMobileTranslation() - useMobileColorScheme() - const reducedMotion = useReducedMotionEnabled() === true - const [expanded, setExpanded] = useState(false) - // Rows glide to their new place when an agent's state reorders the list. - const layout = useMemo( - () => (reducedMotion ? undefined : LinearTransition.duration(220).easing(HOME_EASE_OUT)), - [reducedMotion] - ) - if (props.rows.length === 0) { - return null - } - // One desktop needs no naming. - const nameDesktops = props.hosts.length > 1 - const collapsible = props.rows.length > AGENT_ROWS_COLLAPSED - const shown = expanded || !collapsible ? props.rows : props.rows.slice(0, AGENT_ROWS_COLLAPSED) - const activeCount = props.rows.filter((row) => !row.lastOpened).length - const entering = reducedMotion ? undefined : FadeIn.duration(180) - return ( - <> - 0 - ? t('home.agents.activeCount', '{{count}} active', { count: activeCount }) - : undefined - } - first={props.first} - /> - - {shown.map((row, index) => ( - - {index > 0 ? : null} - host.id === row.hostId) ?? null} - nameDesktop={nameDesktops} - onOpen={props.onOpen} - /> - - ))} - {collapsible ? ( - - - [styles.actionRow, pressed && styles.rowPressed]} - onPress={() => setExpanded((value) => !value)} - > - - {expanded - ? t('home.agents.showFewer', 'Show fewer') - : t('home.agents.showAll', 'Show all {{count}}', { count: props.rows.length })} - - - - ) : null} - - - ) -}) - -// Each refresh rebuilds every row object; compare by value so only changed rows redraw. -const JumpBackInRow = memo(function JumpBackInRow(props: { - row: HomeJumpBackInRow - host: HostCatalogEntry | null - nameDesktop: boolean - onOpen: (row: HomeJumpBackInRow) => void -}) { - const t = useMobileTranslation() - useMobileColorScheme() - const { row } = props - const desktopName = useHostDisplay(props.host).title - const workspace = row.worktree.displayName || row.worktree.repo - const conversation = row.worktree.conversationName - const title = conversation ?? workspace - const labelState = LABEL_STATE[row.worktree.dotStatus] - const status = row.lastOpened - ? row.actionable - ? t('home.jumpBackIn.lastOpened', 'Last opened') - : t('home.jumpBackIn.connectToOpen', 'Connect {{desktop}} to open', { desktop: desktopName }) - : labelState - ? agentStateLabel(labelState) - : '' - // Branch names repeat across projects, so the repo is always named (#37642); "Connect X" already names the desktop. - // A named conversation takes the title and moves the workspace to the subtitle (#38007). - const where = [ - conversation ? workspace : null, - row.worktree.repo && row.worktree.repo !== workspace ? row.worktree.repo : null, - props.nameDesktop && (row.actionable || !row.lastOpened) ? desktopName : null - ] - .filter(Boolean) - .join(' · ') - const statusColor = - !row.lastOpened && TINTED_STATUSES.has(row.worktree.dotStatus) - ? agentStatusColors()[row.worktree.dotStatus] - : colors.textSecondary - - return ( - [styles.row, pressed && styles.rowPressed]} - onPress={() => props.onOpen(row)} - > - - - - - - {title} - - - {status} - {where ? `${status ? ' · ' : ''}${where}` : ''} - - - - - - - ) -}, areStructurallyEqual) diff --git a/mobile/src/home/MobileHomeNeedsYou.tsx b/mobile/src/home/MobileHomeNeedsYou.tsx new file mode 100644 index 00000000000..5345ea8ac5d --- /dev/null +++ b/mobile/src/home/MobileHomeNeedsYou.tsx @@ -0,0 +1,45 @@ +import { memo } from 'react' +import type { AgentListRow } from '../agents/agent-list-model' +import { MobileAgentListRows, type AgentListRowHandlers } from '../agents/MobileAgentListRows' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import type { HostProfile } from '../transport/hosts/host-profile' +import { areStructurallyEqual } from '../worktree/structural-equality' +import { MobileHomeSectionHeading } from './MobileHomeSectionHeading' + +// Enough to act on without pushing Desktops off the first screen; the Agents tab has the rest. +const NEEDS_YOU_ROWS_SHOWN = 3 + +/** Feed's short list of agents waiting on the user; hidden when none are. */ +export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou( + props: AgentListRowHandlers & { + rows: readonly AgentListRow[] + hosts: readonly HostProfile[] + now: number + onSeeAll: () => void + } +) { + const t = useMobileTranslation() + if (props.rows.length === 0) { + return null + } + return ( + <> + + 1} + hosts={props.hosts} + now={props.now} + onOpen={props.onOpen} + onLongPress={props.onLongPress} + /> + + ) +}, areStructurallyEqual) diff --git a/mobile/src/home/MobileHomeScreen.tsx b/mobile/src/home/MobileHomeScreen.tsx index c3e56a26534..205802355a2 100644 --- a/mobile/src/home/MobileHomeScreen.tsx +++ b/mobile/src/home/MobileHomeScreen.tsx @@ -4,13 +4,11 @@ import { Alert, BackHandler, View } from 'react-native' import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { useOpenMobileAccounts } from '../accounts/use-open-mobile-accounts' -import { getProvenCachedWorktrees } from '../cache/worktree-cache' import { ActionSheetModal } from '../components/ActionSheetModal' import { ConfirmModal } from '../components/ConfirmModal' import { getHostListActionSheetActions } from '../host-list-action-sheet-actions' -import { hostRouteWithNotice } from '../host-route-notice' import { triggerMediumImpact } from '../platform/haptics' -import { useOpenMobileSession } from '../session/use-open-mobile-session' +import { useAgentListRowActions } from '../agents/use-agent-list-row-actions' import { useOpenMobileTasks } from '../tasks/use-open-mobile-tasks' import { useOpenMobileAutomations } from '../automations/use-open-mobile-automations' import { colors, spacing } from '../theme/mobile-theme' @@ -28,11 +26,10 @@ import { loadHostCatalog } from '../transport/hosts/host-store' import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' import { useOpenMobileHostEdit } from '../host-screen/use-open-mobile-host-edit' import { mobileConnectionPathLabel } from '../transport/connection/mobile-connection-path-label' -import { homeAgentNeedsYou, type HomeJumpBackInRow } from '../worktree/home-jump-back-in' -import { isResumeTargetConfirmedMissing } from '../worktree/home-resume-card' import { newWorkspaceOverlayHref } from '../new-workspace/new-workspace-overlay-route' import { useMobileHomeData } from './use-mobile-home-data' import { HOME_TABS, type HomeTabId } from './tabs/home-tabs' +import { MobileHomeAgentsTab } from './tabs/MobileHomeAgentsTab' import { MobileHomeAutomationsTab } from './tabs/MobileHomeAutomationsTab' import { MobileHomeFab } from './tabs/MobileHomeFab' import { MobileHomeFeedTab } from './tabs/MobileHomeFeedTab' @@ -51,7 +48,6 @@ export function MobileHomeScreen() { const openMobileHostEdit = useOpenMobileHostEdit() const openMobileTasks = useOpenMobileTasks() const openMobileAutomations = useOpenMobileAutomations() - const openMobileSession = useOpenMobileSession() const openMobileAccounts = useOpenMobileAccounts() const disconnectHostClient = useDisconnectHostClient() const forgetHostClient = useForgetHostClient() @@ -63,6 +59,7 @@ export function MobileHomeScreen() { const [visitedTabs, setVisitedTabs] = useState>(() => new Set(['feed'])) const [automationsHostId, setAutomationsHostId] = useState(null) const [tabBarHeight, setTabBarHeight] = useState(0) + const agentActions = useAgentListRowActions(tabBarHeight) const selectTab = useCallback((next: HomeTabId) => { setTab(next) @@ -85,21 +82,7 @@ export function MobileHomeScreen() { // Stable handlers keep the memoized Feed sections and desktop rows from redrawing on every Home update. const { router, setHostCatalog } = data - const openWorktree = useCallback( - (row: HomeJumpBackInRow) => { - if (isResumeTargetConfirmedMissing(row, getProvenCachedWorktrees(row.hostId))) { - router.push(hostRouteWithNotice(row.hostId, 'worktree-missing')) - return - } - openMobileSession({ - hostId: row.hostId, - worktreeId: row.worktree.worktreeId, - name: row.worktree.displayName || row.worktree.repo, - paneKey: row.worktree.paneKey - }) - }, - [router, openMobileSession] - ) + const seeAllAgents = useCallback(() => selectTab('agents'), [selectTab]) const openHost = useCallback( (host: HostCatalogEntry) => { @@ -156,9 +139,6 @@ export function MobileHomeScreen() { actionTarget != null && data.hostStates[actionTarget.id] === 'connected' const paired = data.hostCatalogLoaded && data.hostCatalog.length > 0 - const feedBadge = data.jumpBackInRows.filter( - (row) => !row.lastOpened && homeAgentNeedsYou(row.worktree.dotStatus) - ).length const automationsHostConnected = automationsHostId != null && data.hostStates[automationsHostId] === 'connected' const fab = @@ -194,12 +174,19 @@ export function MobileHomeScreen() { + ) : id === 'agents' ? ( + ) : id === 'usage' ? ( + {agentActions.sheet} void +}) { useMobileColorScheme() + const AsideIcon = props.asideIcon return ( - + {props.title} + {props.count !== undefined ? ( + {` ${props.count}`} + ) : null} - {props.aside ? {props.aside} : null} + {props.aside && props.onAsidePress ? ( + + {({ pressed }) => ( + + {props.aside} + + )} + + ) : props.aside ? ( + + {AsideIcon ? : null} + + {props.aside} + + + ) : null} ) } diff --git a/mobile/src/home/home-list-styles.ts b/mobile/src/home/home-list-styles.ts index 0b1ae21bc9b..780ccc85973 100644 --- a/mobile/src/home/home-list-styles.ts +++ b/mobile/src/home/home-list-styles.ts @@ -5,6 +5,8 @@ import { themedStyleSheet } from '../theme/themed-styles' // Text starts after the status column, so separators inset to it. const STATUS_COLUMN_WIDTH = 24 const ROW_LEADING_PADDING = spacing.lg +/** Where a row's text starts: separators and nested rows line up with it. */ +export const HOME_ROW_TEXT_INSET = ROW_LEADING_PADDING + STATUS_COLUMN_WIDTH const TILE_SIZE = 30 const TILE_GAP = 11 const TILE_DOT_SIZE = 10 @@ -21,8 +23,12 @@ export const homeListStyles = themedStyleSheet(() => ({ marginTop: 20, marginBottom: 7 }, - sectionHeading: { fontSize: 15, fontWeight: '600', color: colors.textPrimary }, + sectionHeading: { flexShrink: 1, fontSize: 15, fontWeight: '600', color: colors.textPrimary }, + sectionCount: { fontWeight: '500', color: colors.textMuted, fontVariant: ['tabular-nums'] }, sectionAside: { fontSize: 14, color: colors.textMuted, fontVariant: ['tabular-nums'] }, + sectionAsideRow: { flexShrink: 1, flexDirection: 'row', alignItems: 'center', gap: 6 }, + sectionLink: { color: colors.accentBlue, fontWeight: '500' }, + linkPressed: { opacity: 0.5 }, firstSectionHeading: { marginTop: spacing.xs }, // Matches a heading's top gap for a group that has none. headinglessGroup: { marginTop: 20 }, @@ -33,7 +39,7 @@ export const homeListStyles = themedStyleSheet(() => ({ separator: { height: StyleSheet.hairlineWidth, backgroundColor: colors.borderSubtle, - marginLeft: ROW_LEADING_PADDING + STATUS_COLUMN_WIDTH + marginLeft: HOME_ROW_TEXT_INSET }, fullSeparator: { marginLeft: ROW_LEADING_PADDING }, tileSeparator: { marginLeft: ROW_LEADING_PADDING + TILE_SIZE + TILE_GAP }, diff --git a/mobile/src/home/tabs/MobileHomeAgentsTab.tsx b/mobile/src/home/tabs/MobileHomeAgentsTab.tsx new file mode 100644 index 00000000000..eef7c90715d --- /dev/null +++ b/mobile/src/home/tabs/MobileHomeAgentsTab.tsx @@ -0,0 +1,374 @@ +import { Bot, ChevronRight, Monitor, Search, SlidersHorizontal, WifiOff } from 'lucide-react-native' +import { useEffect, useMemo, useRef, useState } from 'react' +import { ScrollView, Text, View } from 'react-native' +import { + AGENT_LIST_GROUP_BY_CHOICES, + buildAgentList, + DEFAULT_AGENT_LIST_VIEW, + summarizeAgentListHosts, + type AgentListGroupBy, + type AgentListSection +} from '../../agents/agent-list-model' +import { loadAgentListView, saveAgentListView } from '../../agents/agent-list-preferences' +import { MobileAgentListRows, type AgentListRowHandlers } from '../../agents/MobileAgentListRows' +import type { ActionSheetAction } from '../../components/ActionSheetModal' +import { MobileSearchField } from '../../components/MobileSearchField' +import { PullDownMenu } from '../../components/nav-bar/PullDownMenu' +import { PickerModal, type PickerOption } from '../../components/PickerModal' +import { hostPickerOptions } from '../../components/use-connected-host-picker' +import type { Translate } from '../../i18n/mobile-i18n' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { useResponsiveLayout } from '../../layout/responsive-layout' +import { useSerializedStoredState } from '../../storage/use-serialized-stored-state' +import { colors, spacing } from '../../theme/mobile-theme' +import { themedStyleSheet } from '../../theme/themed-styles' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import type { HostProfile } from '../../transport/hosts/host-profile' +import { useHostDisplay } from '../../transport/hosts/use-host-display' +import { formatTimeAgo } from '../../worktree/agent-row-display' +import { homeListStyles } from '../home-list-styles' +import { MobileHomeSectionHeading } from '../MobileHomeSectionHeading' +import type { MobileHomeData } from '../use-mobile-home-data' +import { MobileHomePill } from './MobileHomeHostPill' +import { MobileHomeTabHeader, MobileHomeTabHeaderButton } from './MobileHomeTabHeader' + +const ALL_DESKTOPS = '__all__' + +/** Every agent on every paired desktop, grouped the way the user picked. */ +export function MobileHomeAgentsTab(props: { + data: MobileHomeData + bottomInset: number + handlers: AgentListRowHandlers +}) { + const t = useMobileTranslation() + useMobileColorScheme() + const { isWideLayout, contentMaxWidth } = useResponsiveLayout() + const { data } = props + const hosts = data.sortedHosts + const stored = useSerializedStoredState( + DEFAULT_AGENT_LIST_VIEW, + loadAgentListView, + saveAgentListView + ) + const { refresh } = stored + useEffect(() => refresh(), [refresh]) + const view = stored.value + const [searchOpen, setSearchOpen] = useState(false) + const [query, setQuery] = useState('') + const [pickedHost, setPickedHost] = useState(null) + const [pickerOpen, setPickerOpen] = useState(false) + const [menu, setMenu] = useState<'closed' | 'options' | 'group-by'>('closed') + const optionsRef = useRef(null) + // An unpaired desktop's filter falls back to every desktop. + const hostFilter = hosts.some((host) => host.id === pickedHost) ? pickedHost : null + const { now } = data.agentList + const list = useMemo( + () => buildAgentList(data.agentList, { view, hostFilter, query }), + [data.agentList, view, hostFilter, query] + ) + const nameDesktops = hosts.length > 1 && hostFilter === null + const setView = (next: typeof view) => { + stored.setValue(next) + stored.persist(next) + } + + const groupByLabels: Record = { + status: t('agents.groupBy.status', 'Status'), + workspace: t('agents.groupBy.workspace', 'Workspace'), + project: t('agents.groupBy.project', 'Project'), + agent: t('agents.groupBy.agent', 'Agent'), + desktop: t('agents.groupBy.desktop', 'Desktop') + } + const menuGroups: ActionSheetAction[][] = + menu === 'group-by' + ? [ + AGENT_LIST_GROUP_BY_CHOICES.map((groupBy) => ({ + id: groupBy, + label: groupByLabels[groupBy], + checked: view.groupBy === groupBy, + onPress: () => setView({ ...view, groupBy }) + })) + ] + : [ + [ + { + id: 'group-by', + label: t('agents.options.groupBy', 'Group by'), + skipAutoClose: true, + renderIcon: () => ( + + {groupByLabels[view.groupBy]} + + + ), + onPress: () => setMenu('group-by') + }, + { + id: 'show-workers', + label: t('agents.options.showWorkers', 'Show worker agents'), + checked: view.showWorkers, + onPress: () => setView({ ...view, showWorkers: !view.showWorkers }) + } + ] + ] + + const body = !data.hostCatalogLoaded ? null : list.sections.length === 0 ? ( + + ) : ( + list.sections.map((section, index) => ( + + host.id === section.hostId) ?? null} + nameDesktop={nameDesktops} + first={index === 0} + now={now} + /> + + + )) + ) + + return ( + <> + + { + setSearchOpen((open) => !open) + setQuery('') + }} + /> + setMenu('options')} + /> + + } + /> + {searchOpen ? ( + setQuery('')} + autoFocus + style={styles.search} + /> + ) : null} + {hosts.length > 1 ? ( + + setPickerOpen(true)} /> + + ) : null} + + {body} + + setMenu('closed')} + /> + {hosts.length > 1 ? ( + setPickedHost(value === ALL_DESKTOPS ? null : value)} + onClose={() => setPickerOpen(false)} + /> + ) : null} + + ) +} + +function desktopFilterOptions( + hosts: readonly HostProfile[], + summaries: ReturnType, + t: Translate +): PickerOption[] { + const agentCount = (count: number) => + count === 1 + ? t('agents.desktops.agents_one', '{{count}} agent', { count }) + : t('agents.desktops.agents_other', '{{count}} agents', { count }) + const total = summaries.reduce((sum, summary) => sum + summary.agents, 0) + const icon = (offline: boolean) => () => + offline ? ( + + ) : ( + + ) + return [ + { + value: ALL_DESKTOPS, + label: t('agents.desktops.all', 'All desktops'), + subtitle: agentCount(total), + renderIcon: icon(false) + }, + ...hostPickerOptions([...hosts]).map((option) => { + const summary = summaries.find((entry) => entry.hostId === option.value) + const needsYou = summary?.needsYou ?? 0 + return { + value: option.value, + label: option.label, + subtitle: summary?.offline + ? t('agents.desktops.offline', 'Offline') + : [ + agentCount(summary?.agents ?? 0), + needsYou > 0 + ? needsYou === 1 + ? t('agents.desktops.needsYou_one', '{{count}} needs you', { count: needsYou }) + : t('agents.desktops.needsYou_other', '{{count}} need you', { count: needsYou }) + : null + ] + .filter(Boolean) + .join(' · '), + renderIcon: icon(summary?.offline ?? false) + } + }) + ] +} + +function DesktopFilter(props: { + hosts: readonly HostProfile[] + selected: string | null + onOpen: () => void +}) { + const t = useMobileTranslation() + useMobileColorScheme() + const selected = props.hosts.find((host) => host.id === props.selected) ?? null + const title = useHostDisplay(selected).title + const label = selected ? title : t('agents.desktops.all', 'All desktops') + return ( + } + accessibilityLabel={t('home.tabs.chooseDesktop', '{{desktop}}, choose another desktop', { + desktop: label + })} + onPress={props.onOpen} + /> + ) +} + +function AgentListSectionHeading(props: { + section: AgentListSection + host: HostProfile | null + nameDesktop: boolean + first: boolean + now: number +}) { + const t = useMobileTranslation() + const { section } = props + const desktop = useHostDisplay(props.host).title + if (section.kind === 'idle') { + return + } + const titles: Partial> = { + 'needs-you': t('agents.sections.needsYou', 'Needs you'), + working: t('agents.sections.working', 'Working'), + done: t('agents.sections.done', 'Done'), + desktop + } + const counted = section.kind !== 'workspace' && section.kind !== 'project' + const seen = section.lastSeen + const seenAgo = + seen?.at === undefined + ? null + : props.now - seen.at < 60_000 + ? null + : formatTimeAgo(seen.at, props.now) + const aside = seen + ? seen.offline + ? seen.at === undefined + ? t('agents.sections.offline', 'Offline') + : seenAgo + ? t('agents.sections.offlineSeenAgo', 'Offline · seen {{ago}} ago', { ago: seenAgo }) + : t('agents.sections.offlineSeenJustNow', 'Offline · seen just now') + : seenAgo + ? t('agents.sections.seenAgo', 'Seen {{ago}} ago', { ago: seenAgo }) + : t('agents.sections.seenJustNow', 'Seen just now') + : props.nameDesktop && (section.kind === 'workspace' || section.kind === 'project') + ? desktop + : undefined + return ( + + ) +} + +function AgentsEmpty(props: { title: string; message?: string }) { + useMobileColorScheme() + return ( + + + + {props.title} + + {props.message ? {props.message} : null} + + ) +} + +const styles = themedStyleSheet(() => ({ + content: { paddingHorizontal: spacing.lg }, + search: { marginHorizontal: spacing.lg, marginBottom: spacing.sm }, + filters: { paddingHorizontal: spacing.lg }, + menuValue: { flexDirection: 'row', alignItems: 'center', gap: 2 }, + menuValueText: { fontSize: 15, color: colors.textMuted }, + empty: { + alignItems: 'center', + paddingHorizontal: spacing.xl, + paddingVertical: 28, + marginTop: 32, + gap: spacing.sm + }, + emptyTitle: { fontSize: 16, fontWeight: '600', color: colors.textPrimary }, + emptyBody: { fontSize: 14, lineHeight: 20, color: colors.textSecondary, textAlign: 'center' } +})) diff --git a/mobile/src/home/tabs/MobileHomeFeedTab.tsx b/mobile/src/home/tabs/MobileHomeFeedTab.tsx index 61809896ba5..abae60f97ab 100644 --- a/mobile/src/home/tabs/MobileHomeFeedTab.tsx +++ b/mobile/src/home/tabs/MobileHomeFeedTab.tsx @@ -3,21 +3,22 @@ import { useMobileTranslation } from '../../i18n/use-mobile-translation' import { useResponsiveLayout } from '../../layout/responsive-layout' import { spacing } from '../../theme/mobile-theme' import { themedStyleSheet } from '../../theme/themed-styles' +import type { AgentListRowHandlers } from '../../agents/MobileAgentListRows' import type { HostCatalogEntry } from '../../transport/hosts/host-profile' -import type { HomeJumpBackInRow } from '../../worktree/home-jump-back-in' import { MobileHomeAppUpdateCard } from '../MobileHomeAppUpdateCard' import { MobileHomeEmptyState } from '../MobileHomeEmptyState' import { MobileHomeHostList } from '../MobileHomeHostList' -import { MobileHomeJumpBackIn } from '../MobileHomeJumpBackIn' +import { MobileHomeNeedsYou } from '../MobileHomeNeedsYou' import { MobileHomeTasksSection } from '../MobileHomeTasksSection' import type { MobileHomeData } from '../use-mobile-home-data' import { MobileHomeTabHeader } from './MobileHomeTabHeader' -/** Home's first tab: agents to get back to, the desktops, and Tasks. */ +/** Home's first tab: agents that need you, the desktops, and Tasks. */ export function MobileHomeFeedTab(props: { data: MobileHomeData bottomInset: number - onOpenWorktree: (row: HomeJumpBackInRow) => void + agentHandlers: AgentListRowHandlers + onSeeAllAgents: () => void onOpenHost: (host: HostCatalogEntry) => void onOpenHostActions: (host: HostCatalogEntry) => void onPairDesktop: () => void @@ -41,7 +42,7 @@ export function MobileHomeFeedTab(props: { /> ) } - const hasAgents = data.jumpBackInRows.length > 0 + const needsYou = data.agentsNeedingYou.length > 0 return ( <> {title} @@ -52,20 +53,23 @@ export function MobileHomeFeedTab(props: { isWideLayout && { maxWidth: contentMaxWidth, width: '100%', alignSelf: 'center' } ]} > - 1 const dot = statusDotColor(props.state ?? 'disconnected') return ( <> - } accessibilityLabel={ choosable ? t('home.tabs.chooseDesktop', '{{desktop}}, choose another desktop', { @@ -50,30 +50,8 @@ export function MobileHomeHostPill(props: { }) : title } - disabled={!choosable} - onPressIn={() => setPressed(true)} - onPressOut={() => setPressed(false)} - onPress={() => setOpen(true)} - style={styles.pillHit} - > - - - - {title} - - {choosable ? : null} - - + onPress={choosable ? () => setOpen(true) : undefined} + /> {choosable ? ( void +}) { + useMobileColorScheme() + const [pressed, setPressed] = useState(false) + const choosable = props.onPress !== undefined + return ( + setPressed(true)} + onPressOut={() => setPressed(false)} + onPress={props.onPress} + style={styles.pillHit} + > + + {props.leading} + + {props.label} + + {choosable ? : null} + + + ) +} + const styles = themedStyleSheet(() => ({ pillHit: { alignSelf: 'flex-start', maxWidth: '100%' }, pill: { diff --git a/mobile/src/home/tabs/MobileHomeTabBar.tsx b/mobile/src/home/tabs/MobileHomeTabBar.tsx index 3d9dad7e528..f5d84087a79 100644 --- a/mobile/src/home/tabs/MobileHomeTabBar.tsx +++ b/mobile/src/home/tabs/MobileHomeTabBar.tsx @@ -1,4 +1,11 @@ -import { CalendarClock, Gauge, LayoutList, Settings, type LucideIcon } from 'lucide-react-native' +import { + Bot, + CalendarClock, + Gauge, + LayoutList, + Settings, + type LucideIcon +} from 'lucide-react-native' import { useEffect, useState } from 'react' import { Platform, Pressable, StyleSheet, Text, View } from 'react-native' import Animated, { @@ -16,6 +23,7 @@ import { HOME_EASE_OUT, type HomeTabId } from './home-tabs' const TAB_ICONS: Record = { feed: LayoutList, + agents: Bot, usage: Gauge, automations: CalendarClock, settings: Settings @@ -27,14 +35,15 @@ export function MobileHomeTabBar(props: { tabs: readonly HomeTabId[] active: HomeTabId bottomInset: number - /** Agents that need you; shown on Feed. */ - feedBadge: number + /** Agents that need you; shown on Agents. */ + agentsBadge: number onSelect: (tab: HomeTabId) => void }) { const t = useMobileTranslation() useMobileColorScheme() const labels: Record = { feed: t('home.tabs.feed', 'Feed'), + agents: t('home.tabs.agents', 'Agents'), usage: t('home.tabs.usage', 'Usage'), automations: t('home.tabs.automations', 'Automations'), settings: t('common.settings', 'Settings') @@ -51,7 +60,7 @@ export function MobileHomeTabBar(props: { icon={TAB_ICONS[tab]} label={labels[tab]} selected={tab === props.active} - badge={tab === 'feed' ? props.feedBadge : 0} + badge={tab === 'agents' ? props.agentsBadge : 0} onPress={() => props.onSelect(tab)} /> ))} diff --git a/mobile/src/home/tabs/MobileHomeTabHeader.tsx b/mobile/src/home/tabs/MobileHomeTabHeader.tsx index 29b415be876..4e05b072cff 100644 --- a/mobile/src/home/tabs/MobileHomeTabHeader.tsx +++ b/mobile/src/home/tabs/MobileHomeTabHeader.tsx @@ -1,5 +1,5 @@ import type { LucideIcon } from 'lucide-react-native' -import { useState, type ReactNode } from 'react' +import { useState, type ReactNode, type Ref } from 'react' import { Pressable, Text, View } from 'react-native' import Animated from 'react-native-reanimated' import { colors, radii, spacing } from '../../theme/mobile-theme' @@ -20,11 +20,15 @@ export function MobileHomeTabHeader(props: { title: string; trailing?: ReactNode } export function MobileHomeTabHeaderButton(props: { + /** The anchor a pull-down menu drops from. */ + ref?: Ref icon: LucideIcon accessibilityLabel: string disabled?: boolean /** Spins the glyph while a refresh it started is in flight. */ spinning?: boolean + /** What the button opens is showing. */ + active?: boolean onPress: () => void }) { useMobileColorScheme() @@ -32,14 +36,23 @@ export function MobileHomeTabHeaderButton(props: { const Icon = props.icon return ( setPressed(true)} onPressOut={() => setPressed(false)} onPress={props.onPress} - style={[styles.button, pressed && styles.buttonPressed, props.disabled && styles.disabled]} + style={[ + styles.button, + (pressed || props.active) && styles.buttonPressed, + props.disabled && styles.disabled + ]} > ({ setWorktreeInfo, setStats: setStatsByHost, setAccounts: setAccountsByHost }), [] ) - const [lastVisited, setLastVisited] = useState<{ hostId: string; worktreeId: string } | null>( - null - ) const onboardingCheckedRef = useRef(false) const hydratedRef = useRef(false) const focusedRef = useRef(false) @@ -90,7 +82,10 @@ export function useMobileHomeData() { useEffect(() => { if (Object.keys(worktreeInfo).length > 0) { - saveHomeSnapshot({ worktreeInfo, savedAt: Date.now() }) + const saved = Object.fromEntries( + Object.entries(worktreeInfo).map(([hostId, info]) => [hostId, withoutHomeAgentStates(info)]) + ) + saveHomeSnapshot({ worktreeInfo: saved, savedAt: Date.now() }) } }, [worktreeInfo]) @@ -130,11 +125,6 @@ export function useMobileHomeData() { router.replace(mobileOnboardingDestination(steps)) } }) - void AsyncStorage.getItem(LAST_VISITED_WORKTREE_STORAGE_KEY).then((raw) => { - if (!stale) { - setLastVisited(readLastVisitedWorktreeRecord(raw)) - } - }) for (const entry of allClientsRef.current) { if (entry.client.getState() === 'connected') { void fetchHomeHostWorktreeInfo(entry.client, entry.hostId, setWorktreeInfo, () => stale) @@ -150,26 +140,16 @@ export function useMobileHomeData() { const sortedHosts = useMemo(() => sortHostsByLastConnected(hosts), [hosts]) const sortedHostCatalog = useMemo(() => sortHostsByLastConnected(hostCatalog), [hostCatalog]) - const resumeCard = useMemo( - () => - selectHomeResumeCard({ - hosts: sortedHosts, - hostStates: connections.hostStates, - worktreeInfo, - lastVisited, - cachedWorktrees: (hostId) => getCachedWorktrees(hostId) as HomeWorktreeSummary[] | null - }), - [sortedHosts, connections.hostStates, worktreeInfo, lastVisited] + // One clock for every agent count, so Feed, the Agents badge and each desktop agree. + const now = useNow(30_000) + const agentList = useMemo( + () => ({ hosts: sortedHosts, hostStates: connections.hostStates, worktreeInfo, now }), + [sortedHosts, connections.hostStates, worktreeInfo, now] ) - const jumpBackInRows = useMemo( - () => - selectHomeJumpBackInRows({ - hosts: sortedHosts, - hostStates: connections.hostStates, - worktreeInfo, - resumeCard - }), - [sortedHosts, connections.hostStates, worktreeInfo, resumeCard] + const agentsNeedingYou = useMemo(() => selectAgentsNeedingYou(agentList), [agentList]) + const needsYouByHost = useMemo( + () => countAgentsNeedingYouByHost(agentsNeedingYou), + [agentsNeedingYou] ) const connectedHosts = useMemo( () => sortedHosts.filter((host) => connections.hostStates[host.id] === 'connected'), @@ -190,12 +170,14 @@ export function useMobileHomeData() { return { ...connections, accountsByHost, + agentList, + agentsNeedingYou, connectedHosts, hostCatalog, hostCatalogLoaded, hostConnections, hostsConnecting, - jumpBackInRows, + needsYouByHost, router, setHostCatalog, sortedHostCatalog, diff --git a/mobile/src/home/use-mobile-home-host-connections.ts b/mobile/src/home/use-mobile-home-host-connections.ts index 17052ba6c3f..605bd45720f 100644 --- a/mobile/src/home/use-mobile-home-host-connections.ts +++ b/mobile/src/home/use-mobile-home-host-connections.ts @@ -14,7 +14,7 @@ import { fetchHomeHostWorktreeInfo, type HostWorktreeInfoSetter } from '../worktree/home-host-worktree-fetch' -import { withoutHomeAgentStates } from '../worktree/home-worktree-info' +import { withLastSeenHomeAgents } from '../worktree/home-worktree-info' import { fetchHomeHostStats, type HomeStatsSetter } from '../stats/home-stats-summary-read' import { readMobileHomeLastConnected, @@ -107,7 +107,7 @@ function wireMobileHomeHostSubscriptions( // Agents keep moving while we're away; only the reconnect read may show their states again. setWorktreeInfo((previous) => { const current = previous[entry.hostId] - const next = current && withoutHomeAgentStates(current) + const next = current && withLastSeenHomeAgents(current) return next === current ? previous : { ...previous, [entry.hostId]: next } }) } diff --git a/mobile/src/i18n/en-runtime-required.json b/mobile/src/i18n/en-runtime-required.json index d96869ea533..0e3e52d24b7 100644 --- a/mobile/src/i18n/en-runtime-required.json +++ b/mobile/src/i18n/en-runtime-required.json @@ -9,6 +9,18 @@ "messages_other": "{{count}} messages" } }, + "agents": { + "desktops": { + "agents_one": "{{count}} agent", + "agents_other": "{{count}} agents", + "needsYou_one": "{{count}} needs you", + "needsYou_other": "{{count}} need you" + }, + "list": { + "workers_one": "{{count}} worker", + "workers_other": "{{count}} workers" + } + }, "app": { "terminalSettings": { "restoreAfterMinutes_one": "After {{count}} minute", diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index 895b87f3cef..a2da39a8e47 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -1411,12 +1411,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} aktiv", - "heading": "Agenten", - "showAll": "Alle {{count}} anzeigen", - "showFewer": "Weniger anzeigen" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Update-Hinweis für Orca {{version}} ausblenden", "title": "Orca {{version}} ist verfügbar", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 82349083240..a81b470d601 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -557,10 +557,6 @@ "desktops": { "pairDesktop": "Pair a desktop" }, - "jumpBackIn": { - "lastOpened": "Last opened", - "connectToOpen": "Connect {{desktop}} to open" - }, "sections": { "tasks": "Tasks", "tasksSubtitle": "Browse your issues and reviews" @@ -574,12 +570,6 @@ "hours": "{{hours}}h", "minutes": "{{minutes}}m" }, - "agents": { - "heading": "Agents", - "activeCount": "{{count}} active", - "showFewer": "Show fewer", - "showAll": "Show all {{count}}" - }, "automationsTab": { "newAutomation": "New automation", "lastStatus": "Last: {{status}}", @@ -598,7 +588,8 @@ "automations": "Automations", "feed": "Feed", "chooseDesktop": "{{desktop}}, choose another desktop", - "usage": "Usage" + "usage": "Usage", + "agents": "Agents" }, "usage": { "refresh": "Refresh usage", @@ -611,6 +602,10 @@ "active": "Active", "openAccountsHint": "Opens this desktop’s accounts", "emptyTitle": "No usage yet" + }, + "needsYou": { + "heading": "Needs you", + "seeAll": "See all agents" } }, "hooks": { @@ -4755,5 +4750,62 @@ "renameUnconfirmed": "Not confirmed yet. Orca checks the name when {{host}} is back.", "saving": "Saving", "serverUnreachable": "Its server can't be reached." + }, + "agents": { + "list": { + "idleCount": "{{count}} idle", + "offlineTitle": "{{desktop}} is offline", + "offlineMessage": "Reconnect it to open this agent.", + "actions": "Actions for {{title}}", + "workers_one": "{{count}} worker", + "workers_other": "{{count}} workers", + "noMatches": "No agents match “{{query}}”", + "emptyTitle": "No agents running", + "pairDesktop": "Pair a desktop to see its agents here.", + "emptyBody": "Start an agent in any workspace and it shows up here." + }, + "actions": { + "offlineHint": "Its desktop is offline.", + "open": "Open", + "goToWorkspace": "Go to workspace", + "copyTitle": "Copy title", + "copied": "Copied", + "copyFailed": "Couldn’t copy the title" + }, + "groupBy": { + "status": "Status", + "workspace": "Workspace", + "project": "Project", + "agent": "Agent", + "desktop": "Desktop" + }, + "options": { + "groupBy": "Group by", + "showWorkers": "Show worker agents", + "open": "Agent list options" + }, + "search": { + "toggle": "Search agents", + "placeholder": "Search agents" + }, + "desktops": { + "pickerTitle": "Show agents on", + "agents_one": "{{count}} agent", + "agents_other": "{{count}} agents", + "all": "All desktops", + "offline": "Offline", + "needsYou_one": "{{count}} needs you", + "needsYou_other": "{{count}} need you" + }, + "sections": { + "needsYou": "Needs you", + "working": "Working", + "done": "Done", + "offline": "Offline", + "offlineSeenAgo": "Offline · seen {{ago}} ago", + "offlineSeenJustNow": "Offline · seen just now", + "seenAgo": "Seen {{ago}} ago", + "seenJustNow": "Seen just now" + } } } diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index f243326969a..615bc3008fa 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -1450,12 +1450,6 @@ } }, "home": { - "agents": { - "activeCount": "Activos: {{count}}", - "heading": "Agentes", - "showAll": "Mostrar todos ({{count}})", - "showFewer": "Mostrar menos" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Descartar la actualización de Orca {{version}}", "title": "Orca {{version}} está disponible", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index 1ca9a89435f..b4968d0c4b4 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -1450,12 +1450,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} en activité", - "heading": "Agents", - "showAll": "Tout afficher ({{count}})", - "showFewer": "Afficher moins" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Ignorer la mise à jour Orca {{version}}", "title": "Orca {{version}} est disponible", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index a355885573f..41b59f00545 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -1407,12 +1407,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} 件がアクティブ", - "heading": "Agent", - "showAll": "{{count}} 件をすべて表示", - "showFewer": "折りたたむ" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Orca {{version}} の更新通知を閉じる", "title": "Orca {{version}} が利用可能です", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index 3839cc56e5a..7c34395812a 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -1407,12 +1407,6 @@ } }, "home": { - "agents": { - "activeCount": "활성 {{count}}개", - "heading": "에이전트", - "showAll": "{{count}}개 모두 보기", - "showFewer": "접기" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Orca {{version}} 업데이트 알림 닫기", "title": "Orca {{version}} 업데이트 가능", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index f61c5108c01..fb83a84674d 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -1450,12 +1450,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} em atividade", - "heading": "Agentes", - "showAll": "Mostrar todos ({{count}})", - "showFewer": "Mostrar menos" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Descartar atualização do Orca {{version}}", "title": "Orca {{version}} está disponível", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 2361a23e865..9ced7c69b59 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -1489,12 +1489,6 @@ } }, "home": { - "agents": { - "activeCount": "Активных: {{count}}", - "heading": "Агенты", - "showAll": "Показать все ({{count}})", - "showFewer": "Свернуть" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Скрыть уведомление об обновлении Orca {{version}}", "title": "Доступна Orca {{version}}", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index 51d30ec5537..f103d17aec0 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -1411,12 +1411,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} etkin", - "heading": "Ajanlar", - "showAll": "Tümünü göster ({{count}})", - "showFewer": "Daha az göster" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Orca {{version}} güncellemesini gizle", "title": "Orca {{version}} sürümü mevcut", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 552b77a5435..b41f7765fec 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -1407,12 +1407,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} 個使用中", - "heading": "代理程式", - "showAll": "顯示全部 {{count}} 個", - "showFewer": "收合" - }, "appUpdateCard": { "dismissAccessibilityLabel": "關閉 Orca {{version}} 更新提示", "title": "Orca {{version}} 已推出", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index 84c03919729..b99d10462d5 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -1407,12 +1407,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} 个活跃", - "heading": "智能体", - "showAll": "显示全部 {{count}} 个", - "showFewer": "收起" - }, "appUpdateCard": { "dismissAccessibilityLabel": "关闭 Orca {{version}} 更新提示", "title": "Orca {{version}} 已可用", diff --git a/mobile/src/worktree/home-host-worktree-fetch.ts b/mobile/src/worktree/home-host-worktree-fetch.ts index ac17d70c8a4..783f3376b67 100644 --- a/mobile/src/worktree/home-host-worktree-fetch.ts +++ b/mobile/src/worktree/home-host-worktree-fetch.ts @@ -3,11 +3,11 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract' import '../transport/connection/stable-logical-rpc-client' import { isLogicalClientCutoverError } from '../transport/connection/logical-client-cutover-error' import { + homeAgentEntries, markHomeWorktreeCatalogUnavailable, type HomeWorktreeSummary, type HostWorktreeInfo } from './home-worktree-info' -import { selectHomeAttentionWorktrees } from './home-jump-back-in' import { pickResumeWorktree } from './resume-worktree' import { isWorktreeActive } from './workspace-list-sections' import { WorktreeCatalogSnapshotClient } from './worktree-catalog-snapshot-client' @@ -59,7 +59,7 @@ export function fetchHomeHostWorktreeInfo( markUnavailable() return } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the rows stay opaque because three screens project a row differently. Home reads `status`, `sidebarStatus` and the resume pick through their own guards, plus the host-typed `agents` that name Jump back in rows, and the `worktree-home-catalog` golden records the row it is given as `{worktreeId, displayName, repo, status}`. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the rows stay opaque because three screens project a row differently. Home reads `status`, `sidebarStatus` and the resume pick through their own guards, plus the host-typed `agents` the Agents list shows, and the `worktree-home-catalog` golden records the row it is given as `{worktreeId, displayName, repo, status}`. const worktrees = rows as HomeWorktreeSummary[] setCachedWorktrees(hostId, worktrees, { proven: true }) // Count what the list shows: archived rows are hidden, and active is the sleeping filter's rule. @@ -73,7 +73,7 @@ export function fetchHomeHostWorktreeInfo( totalWorktrees: listed.length, activeCount: listed.filter(isWorktreeActive).length, lastActiveWorktree: lastActive, - attention: selectHomeAttentionWorktrees(listed), + agents: homeAgentEntries(listed), countsProvenAt: Date.now() } })) diff --git a/mobile/src/worktree/home-jump-back-in.test.ts b/mobile/src/worktree/home-jump-back-in.test.ts deleted file mode 100644 index 1b83a5269a4..00000000000 --- a/mobile/src/worktree/home-jump-back-in.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { selectHomeAttentionWorktrees, selectHomeJumpBackInRows } from './home-jump-back-in' -import type { HomeWorktreeSummary, HostWorktreeInfo } from './home-worktree-info' - -const NOW = 1_000_000_000 - -function row(id: string, fields: Partial): HomeWorktreeSummary { - return { - worktreeId: id, - repo: 'orca', - branch: id, - displayName: id, - liveTerminalCount: 1, - ...fields - } -} - -function agent(paneKey: string, fields: Partial): RuntimeWorktreeAgentRow { - return { - paneKey, - parentPaneKey: null, - state: 'working', - agentType: 'claude', - prompt: '', - taskTitle: null, - displayName: null, - lastAssistantMessage: null, - toolName: null, - toolInput: null, - interrupted: false, - stateStartedAt: NOW, - updatedAt: NOW, - ...fields - } -} - -function info(hostId: string, rows: HomeWorktreeSummary[]): HostWorktreeInfo { - return { - hostId, - totalWorktrees: rows.length, - activeCount: 0, - lastActiveWorktree: null, - attention: selectHomeAttentionWorktrees(rows), - countsProvenAt: NOW - } -} - -describe('home jump back in', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('puts agents waiting on the user first, then unseen finished work, then running work', () => { - const rows = selectHomeAttentionWorktrees([ - row('running', { sidebarStatus: 'working', lastOutputAt: NOW }), - row('finished-seen', { sidebarStatus: 'done', unread: false }), - row('finished-unseen', { sidebarStatus: 'done', unread: true, lastOutputAt: NOW - 5 }), - row('blocked', { sidebarStatus: 'permission', lastOutputAt: NOW - 10 }), - row('archived', { sidebarStatus: 'permission', isArchived: true }), - row('idle', { status: 'inactive', hasHostSidebarActivity: false }) - ]) - expect(rows.map((worktree) => worktree.worktreeId)).toEqual([ - 'blocked', - 'finished-unseen', - 'running' - ]) - }) - - it('claims no agent state for a desktop that is offline or whose last read failed', () => { - const blocked = [row('blocked', { sidebarStatus: 'permission' })] - const rows = selectHomeJumpBackInRows({ - hosts: [{ id: 'live' }, { id: 'offline' }, { id: 'failed' }], - hostStates: { live: 'connected', offline: 'disconnected', failed: 'connected' }, - worktreeInfo: { - live: info('live', blocked), - offline: info('offline', blocked), - failed: { ...info('failed', blocked), catalogUnavailable: true } - }, - resumeCard: null - }) - expect(rows.map((entry) => entry.hostId)).toEqual(['live']) - }) - - it('adds the last-opened workspace after the agents, unless it is already listed', () => { - const resumeWorktree = row('resume', {}) - const base = { - hosts: [{ id: 'host' }], - hostStates: { host: 'connected' as const } - } - const appended = selectHomeJumpBackInRows({ - ...base, - worktreeInfo: { host: info('host', [row('blocked', { sidebarStatus: 'permission' })]) }, - resumeCard: { hostId: 'host', worktree: resumeWorktree, actionable: true } - }) - expect(appended.map((entry) => [entry.worktree.worktreeId, entry.lastOpened])).toEqual([ - ['blocked', false], - ['resume', true] - ]) - - const deduped = selectHomeJumpBackInRows({ - ...base, - worktreeInfo: { host: info('host', [row('resume', { sidebarStatus: 'working' })]) }, - resumeCard: { hostId: 'host', worktree: resumeWorktree, actionable: true } - }) - expect(deduped.map((entry) => [entry.worktree.worktreeId, entry.lastOpened])).toEqual([ - ['resume', false] - ]) - }) - - it('names a row after the newest live top-level conversation in the dot state, else none', () => { - vi.useFakeTimers({ now: NOW }) - const rows = selectHomeAttentionWorktrees([ - row('blocked', { - sidebarStatus: 'permission', - agents: [ - agent('older', { - state: 'waiting', - conversationName: 'Older question', - updatedAt: NOW - 9 - }), - agent('newer', { state: 'blocked', conversationName: 'Fix login', updatedAt: NOW - 5 }), - agent('running', { state: 'working', conversationName: 'Refactor', updatedAt: NOW }), - agent('worker', { - parentPaneKey: 'running', - state: 'waiting', - conversationName: 'Worker', - updatedAt: NOW - }) - ] - }), - row('unnamed', { - sidebarStatus: 'working', - agents: [agent('a', { state: 'working' })] - }), - row('stale', { - sidebarStatus: 'working', - agents: [ - agent('s', { - state: 'working', - conversationName: 'Old task', - updatedAt: NOW - 31 * 60_000 - }) - ] - }), - row('old-host', { sidebarStatus: 'done', unread: true }) - ]) - expect( - rows.map((worktree) => [worktree.worktreeId, worktree.conversationName, worktree.paneKey]) - ).toEqual([ - ['blocked', 'Fix login', 'newer'], - ['old-host', undefined, undefined], - ['unnamed', undefined, undefined], - ['stale', undefined, undefined] - ]) - }) -}) diff --git a/mobile/src/worktree/home-jump-back-in.ts b/mobile/src/worktree/home-jump-back-in.ts deleted file mode 100644 index 446d6baaa17..00000000000 --- a/mobile/src/worktree/home-jump-back-in.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { isAgentStatusFresh } from '../../../src/shared/agent-status/contracts/agent-status-freshness' -import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { - applyAgentPaneActivityFlags, - createAgentPaneActivityFlags, - rankWorktreeStatus, - type WorktreeStatus -} from '../../../src/shared/worktree-status-rollup' -import type { ConnectionState } from '../transport/connection/connection-state' -import type { HomeResumeCard } from './home-resume-card' -import type { - HomeAttentionWorktree, - HomeWorktreeSummary, - HostWorktreeInfo -} from './home-worktree-info' -import { buildAgentRowLineageTree } from './agent-row-lineage' -import { getWorktreeDotStatus } from './workspace-list-ordering' - -// Feed shows the first few and "Show all" the rest; the bound keeps a busy desktop's list small. -const ATTENTION_ROWS_PER_HOST = 25 -const ATTENTION_ROWS_SHOWN = 25 - -/** Agents blocked on the user: they rank first, badge the Feed tab and are counted per desktop. */ -export function homeAgentNeedsYou(dotStatus: WorktreeStatus): boolean { - return dotStatus === 'permission' || dotStatus === 'failed' -} - -// Lower comes first: agents blocked on the user, then finished work they haven't seen, then running work. -function attentionRank(dotStatus: WorktreeStatus, unread: boolean): number | null { - if (homeAgentNeedsYou(dotStatus)) { - return 0 - } - if (dotStatus === 'done' && unread) { - return 1 - } - if (dotStatus === 'working' || dotStatus === 'monitoring') { - return 2 - } - return null -} - -function byRankThenRecent( - a: { rank: number; lastOutputAt?: number }, - b: { rank: number; lastOutputAt?: number } -): number { - return a.rank - b.rank || (b.lastOutputAt ?? 0) - (a.lastOutputAt ?? 0) -} - -function agentDotStatus(agent: RuntimeWorktreeAgentRow): WorktreeStatus { - const flags = createAgentPaneActivityFlags() - applyAgentPaneActivityFlags(flags, agent) - return rankWorktreeStatus('inactive', flags) -} - -// The newest top-level agent the host counted in the dot's state names the row; a nameless one keeps the workspace title. -function conversationBehindDot( - agents: readonly RuntimeWorktreeAgentRow[] | undefined, - dotStatus: WorktreeStatus, - now: number -): Pick { - let newest: RuntimeWorktreeAgentRow | undefined - for (const agent of buildAgentRowLineageTree(agents ?? []).rootRows) { - if ( - isAgentStatusFresh(agent, now) && - agentDotStatus(agent) === dotStatus && - (!newest || agent.updatedAt > newest.updatedAt) - ) { - newest = agent - } - } - const conversationName = newest?.conversationName?.trim() - return newest && conversationName ? { conversationName, paneKey: newest.paneKey } : {} -} - -/** The rows of one desktop's list that "Jump back in" may show, using the workspace list's dot status. */ -export function selectHomeAttentionWorktrees( - rows: readonly HomeWorktreeSummary[] -): HomeAttentionWorktree[] { - const now = Date.now() - const ranked: (HomeAttentionWorktree & Pick & { rank: number })[] = - [] - for (const row of rows) { - if (row.isArchived === true) { - continue - } - const dotStatus = getWorktreeDotStatus(row) - const rank = attentionRank(dotStatus, row.unread === true) - if (rank === null) { - continue - } - ranked.push({ - rank, - dotStatus, - worktreeId: row.worktreeId, - repo: row.repo, - branch: row.branch, - displayName: row.displayName, - lastOutputAt: typeof row.lastOutputAt === 'number' ? row.lastOutputAt : undefined, - workingMode: row.workingMode, - agents: row.agents - }) - } - return ranked - .sort(byRankThenRecent) - .slice(0, ATTENTION_ROWS_PER_HOST) - .map(({ rank: _rank, agents, ...worktree }) => ({ - ...worktree, - ...conversationBehindDot(agents, worktree.dotStatus, now) - })) -} - -export type HomeJumpBackInRow = Readonly<{ - hostId: string - worktree: HomeAttentionWorktree - /** The resume target rather than an agent that needs the user. */ - lastOpened: boolean - actionable: boolean -}> - -export function selectHomeJumpBackInRows(input: { - hosts: readonly { id: string }[] - hostStates: Readonly> - worktreeInfo: Readonly> - resumeCard: HomeResumeCard | null -}): HomeJumpBackInRow[] { - const candidates: (HomeJumpBackInRow & { rank: number; lastOutputAt?: number })[] = [] - for (const host of input.hosts) { - const info = input.worktreeInfo[host.id] - // Agent states are shown only from a connected desktop's list read this session. - if (input.hostStates[host.id] !== 'connected' || !info?.attention || info.catalogUnavailable) { - continue - } - for (const worktree of info.attention) { - candidates.push({ - hostId: host.id, - worktree, - lastOpened: false, - actionable: true, - rank: attentionRank(worktree.dotStatus, true) ?? 2, - lastOutputAt: worktree.lastOutputAt - }) - } - } - const rows: HomeJumpBackInRow[] = candidates - .sort(byRankThenRecent) - .slice(0, ATTENTION_ROWS_SHOWN) - .map(({ rank: _rank, lastOutputAt: _lastOutputAt, ...row }) => row) - const resume = input.resumeCard - if ( - resume && - !rows.some( - (row) => - row.hostId === resume.hostId && row.worktree.worktreeId === resume.worktree.worktreeId - ) - ) { - rows.push({ - hostId: resume.hostId, - worktree: { - worktreeId: resume.worktree.worktreeId, - repo: resume.worktree.repo, - branch: resume.worktree.branch, - displayName: resume.worktree.displayName, - lastOutputAt: resume.worktree.lastOutputAt, - dotStatus: 'inactive' - }, - lastOpened: true, - actionable: resume.actionable - }) - } - return rows -} diff --git a/mobile/src/worktree/home-resume-card.test.ts b/mobile/src/worktree/home-resume-card.test.ts deleted file mode 100644 index 65f9bd4c7bf..00000000000 --- a/mobile/src/worktree/home-resume-card.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - isResumeTargetConfirmedMissing, - selectHomeResumeCard, - type HomeResumeCardInput -} from './home-resume-card' -import type { HomeWorktreeSummary, HostWorktreeInfo } from './home-worktree-info' - -function worktree(worktreeId: string): HomeWorktreeSummary { - return { - worktreeId, - repo: 'orca', - branch: 'main', - displayName: worktreeId, - liveTerminalCount: 0 - } -} - -function info(hostId: string, lastActive: HomeWorktreeSummary | null): HostWorktreeInfo { - return { hostId, totalWorktrees: 1, activeCount: 0, lastActiveWorktree: lastActive } -} - -function input(overrides: Partial = {}): HomeResumeCardInput { - return { - hosts: [{ id: 'host-1' }], - hostStates: {}, - worktreeInfo: { 'host-1': info('host-1', worktree('repo::/tmp/wt')) }, - lastVisited: null, - cachedWorktrees: () => null, - ...overrides - } -} - -describe('home resume card', () => { - it('reserves the slot from snapshot data while the host is still connecting', () => { - const connecting = selectHomeResumeCard(input({ hostStates: { 'host-1': 'connecting' } })) - - expect(connecting).toEqual({ - hostId: 'host-1', - worktree: worktree('repo::/tmp/wt'), - actionable: false - }) - }) - - it('keeps the same card in place once the host connects, only enabling it', () => { - const before = selectHomeResumeCard(input({ hostStates: { 'host-1': 'connecting' } })) - const after = selectHomeResumeCard(input({ hostStates: { 'host-1': 'connected' } })) - - expect(after?.hostId).toBe(before?.hostId) - expect(after?.worktree.worktreeId).toBe(before?.worktree.worktreeId) - expect(after?.actionable).toBe(true) - }) - - it('leaves Tasks first when no host has resume history at all', () => { - expect( - selectHomeResumeCard(input({ worktreeInfo: { 'host-1': info('host-1', null) } })) - ).toBeNull() - }) - - it('prefers the worktree last opened on this device, enabled with its host', () => { - const visited = worktree('repo::/tmp/visited') - const fromLastVisited = (state: 'connecting' | 'connected') => - selectHomeResumeCard( - input({ - hostStates: { 'host-1': state }, - lastVisited: { hostId: 'host-1', worktreeId: visited.worktreeId }, - cachedWorktrees: (hostId) => (hostId === 'host-1' ? [visited] : null) - }) - ) - - expect(fromLastVisited('connecting')).toEqual({ - hostId: 'host-1', - worktree: visited, - actionable: false - }) - expect(fromLastVisited('connected')?.actionable).toBe(true) - }) - - it('prefers a connected host over an unconnected one holding older snapshot data', () => { - const card = selectHomeResumeCard( - input({ - hosts: [{ id: 'host-1' }, { id: 'host-2' }], - hostStates: { 'host-1': 'connecting', 'host-2': 'connected' }, - worktreeInfo: { - 'host-1': info('host-1', worktree('repo::/tmp/one')), - 'host-2': info('host-2', worktree('repo::/tmp/two')) - } - }) - ) - - expect(card).toEqual({ - hostId: 'host-2', - worktree: worktree('repo::/tmp/two'), - actionable: true - }) - }) - - it('gives a connected host precedence over an offline last-visited worktree', () => { - const visited = worktree('repo::/tmp/visited') - const card = selectHomeResumeCard( - input({ - hosts: [{ id: 'host-1' }, { id: 'host-2' }], - hostStates: { 'host-1': 'disconnected', 'host-2': 'connected' }, - worktreeInfo: { 'host-2': info('host-2', worktree('repo::/tmp/two')) }, - lastVisited: { hostId: 'host-1', worktreeId: visited.worktreeId }, - cachedWorktrees: (hostId) => (hostId === 'host-1' ? [visited] : null) - }) - ) - - expect(card).toEqual({ - hostId: 'host-2', - worktree: worktree('repo::/tmp/two'), - actionable: true - }) - }) -}) - -// A persisted Resume target may have been deleted while offline; require host evidence before confirming it missing (F7). -describe('isResumeTargetConfirmedMissing', () => { - const card = { - hostId: 'host-1', - worktree: worktree('repo::/tmp/wt'), - actionable: true - } as const - - it('confirms a target the host listed without', () => { - expect(isResumeTargetConfirmedMissing(card, [{ worktreeId: 'repo::/tmp/other' }])).toBe(true) - }) - - it('clears a target present in the listing', () => { - expect( - isResumeTargetConfirmedMissing(card, [ - { worktreeId: 'repo::/tmp/other' }, - { worktreeId: 'repo::/tmp/wt' } - ]) - ).toBe(false) - }) - - // An unproven catalog cannot establish deletion. - it('never confirms without a proven catalog', () => { - expect(isResumeTargetConfirmedMissing(card, null)).toBe(false) - }) - - it('confirms the target when the host proves it has no workspaces at all', () => { - expect(isResumeTargetConfirmedMissing(card, [])).toBe(true) - }) - - it('exempts synthetic routes the catalog can never list', () => { - const folder = { ...card, worktree: worktree('folder:/Users/x/dir') } - const floating = { ...card, worktree: worktree('global-floating-terminal') } - - expect(isResumeTargetConfirmedMissing(folder, [])).toBe(false) - expect(isResumeTargetConfirmedMissing(floating, [])).toBe(false) - }) -}) diff --git a/mobile/src/worktree/home-resume-card.ts b/mobile/src/worktree/home-resume-card.ts deleted file mode 100644 index e89c5254353..00000000000 --- a/mobile/src/worktree/home-resume-card.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { isSyntheticWorkspaceRoute } from '../session/synthetic-workspace-route' -import type { ConnectionState } from '../transport/connection/connection-state' -import type { HomeWorktreeSummary, HostWorktreeInfo } from './home-worktree-info' - -// Reserve Resume’s slot from persisted history before connection so Tasks cannot move under the user’s thumb. - -export type HomeResumeCard = Readonly<{ - hostId: string - worktree: HomeWorktreeSummary - actionable: boolean -}> - -export type HomeResumeCardInput = Readonly<{ - /** Home's sorted hosts — order decides which snapshot wins when several have history. */ - hosts: readonly { id: string }[] - hostStates: Readonly> - worktreeInfo: Readonly> - lastVisited: Readonly<{ hostId: string; worktreeId: string }> | null - cachedWorktrees: (hostId: string) => HomeWorktreeSummary[] | null -}> - -function lastVisitedCard({ - lastVisited, - cachedWorktrees, - hostStates -}: HomeResumeCardInput): HomeResumeCard | null { - if (!lastVisited) { - return null - } - const match = cachedWorktrees(lastVisited.hostId)?.find( - (worktree) => worktree.worktreeId === lastVisited.worktreeId - ) - if (!match) { - return null - } - return { - hostId: lastVisited.hostId, - worktree: match, - actionable: hostStates[lastVisited.hostId] === 'connected' - } -} - -function hostHistoryCard( - { hosts, hostStates, worktreeInfo }: HomeResumeCardInput, - connectedOnly: boolean -): HomeResumeCard | null { - for (const host of hosts) { - const worktree = worktreeInfo[host.id]?.lastActiveWorktree - if (!worktree) { - continue - } - const actionable = hostStates[host.id] === 'connected' - if (actionable || !connectedOnly) { - return { hostId: host.id, worktree, actionable } - } - } - return null -} - -// Only a proven catalog can establish deletion; cold/loading snapshots leave navigation to the session’s later check. -export function isResumeTargetConfirmedMissing( - card: Readonly<{ worktree: Readonly<{ worktreeId: string }> }>, - provenWorktrees: readonly unknown[] | null -): boolean { - if (!provenWorktrees || isSyntheticWorkspaceRoute(card.worktree.worktreeId)) { - return false - } - return !provenWorktrees.some( - (worktree) => - typeof worktree === 'object' && - worktree !== null && - 'worktreeId' in worktree && - worktree.worktreeId === card.worktree.worktreeId - ) -} - -export function selectHomeResumeCard(input: HomeResumeCardInput): HomeResumeCard | null { - const visited = lastVisitedCard(input) - if (visited?.actionable) { - return visited - } - const connected = hostHistoryCard(input, true) - if (connected) { - return connected - } - return visited ?? hostHistoryCard(input, false) -} diff --git a/mobile/src/worktree/home-worktree-info.ts b/mobile/src/worktree/home-worktree-info.ts index e0630913958..d030f7b8471 100644 --- a/mobile/src/worktree/home-worktree-info.ts +++ b/mobile/src/worktree/home-worktree-info.ts @@ -1,6 +1,5 @@ import type { AgentWorkingMode } from '../../../src/shared/agent-status/contracts/agent-status-types' import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import type { WorktreeStatus } from '../../../src/shared/worktree-status-rollup' export type HomeWorktreeSummary = { worktreeId: string @@ -19,23 +18,24 @@ export type HomeWorktreeSummary = { agents?: RuntimeWorktreeAgentRow[] } -/** A workspace whose agents Home surfaces under "Jump back in", with the list's dot status. */ -export type HomeAttentionWorktree = Pick< - HomeWorktreeSummary, - 'worktreeId' | 'repo' | 'branch' | 'displayName' | 'lastOutputAt' | 'workingMode' -> & { - dotStatus: WorktreeStatus - /** The conversation behind the dot and its pane; older hosts send no names. */ - conversationName?: string - paneKey?: string -} +/** One agent on a desktop, with the workspace it runs in. */ +export type HomeAgentEntry = Readonly<{ + worktreeId: string + workspaceName: string + repo: string + branch: string + agent: RuntimeWorktreeAgentRow +}> export type HostWorktreeInfo = { hostId: string totalWorktrees: number activeCount: number lastActiveWorktree: HomeWorktreeSummary | null - attention?: HomeAttentionWorktree[] + /** Every agent from this connection's latest list read. */ + agents?: HomeAgentEntry[] + /** The agents of a read the connection has since lost: what they were, not what they are. */ + lastSeenAgents?: HomeAgentEntry[] catalogUnavailable?: boolean // The counts are the last proven ones, kept across a failed refresh. staleCounts?: boolean @@ -43,15 +43,38 @@ export type HostWorktreeInfo = { countsProvenAt?: number } -/** Agent states are live facts; a saved copy or a dropped connection can't vouch for them. */ +export function homeAgentEntries(worktrees: readonly HomeWorktreeSummary[]): HomeAgentEntry[] { + return worktrees.flatMap((worktree) => + Array.isArray(worktree.agents) + ? worktree.agents.map((agent) => ({ + worktreeId: worktree.worktreeId, + workspaceName: worktree.displayName || worktree.repo, + repo: worktree.repo, + branch: worktree.branch, + agent + })) + : [] + ) +} + +/** Agent states are live facts; a saved copy can't vouch for them, even as last seen. */ export function withoutHomeAgentStates(info: HostWorktreeInfo): HostWorktreeInfo { - if (!info.attention) { + if (!info.agents && !info.lastSeenAgents) { return info } - const { attention: _attention, ...rest } = info + const { agents: _agents, lastSeenAgents: _lastSeenAgents, ...rest } = info return rest } +/** A dropped connection keeps its agents only as last seen; the reconnect read makes them live again. */ +export function withLastSeenHomeAgents(info: HostWorktreeInfo): HostWorktreeInfo { + if (!info.agents) { + return info + } + const { agents, ...rest } = info + return { ...rest, lastSeenAgents: agents } +} + export function markHomeWorktreeCatalogUnavailable( current: HostWorktreeInfo | undefined, hostId: string From ba6b11cd8be1461b98d4f83d9fd6d173cd6b140e Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:32:09 +0000 Subject: [PATCH 08/23] fix(ai-vault): cut session search index disk writes with wider FTS merges and fewer vacuums (#39314) * fix(ai-vault): cut search-index disk writes from merge rewrites and idle vacuums The session-search index sustained tens of GB of daily writes on busy multi-agent days (#36666): ~650 KB/s of file-backed pages dirtied by the Orca Helper process that owns the index, against a ~214 MB database. Two write paths compound there: 1. FTS5 merges whole segment levels on every steady append. With the default automerge=4, an index of this size rewrites several bytes of deep segments for each byte appended, and every merge page is then copied from WAL into the database by autocheckpoint. 2. Every full purge ran `incremental_vacuum(2000)` even when it deleted nothing, moving free pages around the file. Full purges back every freshness wait (`reconcile({ full: true })`) and the periodic sweep, so idle sweeps themselves became a write source. A measured loop (one busy transcript appending 100 KB per 20 s cycle, sweeps every 15 cycles) shows sweeps dropping from 428-736 KB to 132-144 KB per pass and merge spikes from ~1 MB to 432-800 KB (-28% total WAL bytes at 10 MB index scale; the merge saving grows with index size). Fix: - Set FTS5 `automerge` to 8 on every open (new and existing databases, no schema rebuild): merging wider rewrites roughly half the deep-level pages on this insert-heavy, rarely-deleted index, at a small read fan-in cost. - Gate the trailing `incremental_vacuum` in retention drains on actual deletion work. Drains scheduled after real deletions (retention, replacement, retirement) keep reclaiming pages; recurring unlimited purges with nothing to delete leave the freelist for page reuse instead of shuffling it. Read paths, cache semantics, and the on-disk schema are unchanged. Fixes #36666 * fix(ai-vault): vacuum the search index only when free pages pile up FTS merges free pages on every write and later writes reuse them, so a vacuum after every drain batch and sweep only moved pages around. Gate it on the free share of the file instead of on whether a purge deleted anything, which also covers drains after whole-session replaces. --------- Co-authored-by: ggbdpq --- .../session-search-retention-delete.test.ts | 27 +++++++++++++++++++ .../session-search-retention-delete.ts | 13 +++++++-- .../ai-vault-search/session-search-schema.ts | 2 ++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/main/ai-vault-search/session-search-retention-delete.test.ts b/src/main/ai-vault-search/session-search-retention-delete.test.ts index 2cf168ad3a5..8ff715f7bdf 100644 --- a/src/main/ai-vault-search/session-search-retention-delete.test.ts +++ b/src/main/ai-vault-search/session-search-retention-delete.test.ts @@ -156,3 +156,30 @@ it('keeps a file a read refreshed after the expiry list was taken', async () => await index.close() } }) + +function freelistShare(db: SyncDatabase): number { + const free = Number(db.pragma('freelist_count', { simple: true })) + return free / Number(db.pragma('page_count', { simple: true })) +} + +it("leaves a replaced session's free pages for reuse but reclaims a large purge", async () => { + const index = await openSessionSearchIndexFile('ss-retention-reclaim') + const store = new SessionSearchStore(index.path) + try { + seed(index.db, 1, 2000, 1) + seed(index.db, 2, 2000, 200) + seed(index.db, 3, 400, 200) + // A replaced session leaves its old rows orphaned; moving the few pages they free only churns the file. + index.db.prepare('DELETE FROM sessions WHERE id = 3').run() + await store.purgeOlderThan(null) + expect(count(index.db, 'messages')).toBe(4000) + expect(freelistShare(index.db)).toBeGreaterThan(0) + + await store.purgeOlderThan(100) + expect(count(index.db, 'messages')).toBe(2000) + expect(freelistShare(index.db)).toBeLessThanOrEqual(0.25) + } finally { + store.close() + await index.close() + } +}) diff --git a/src/main/ai-vault-search/session-search-retention-delete.ts b/src/main/ai-vault-search/session-search-retention-delete.ts index 4956b5d1bfd..09222aa16a5 100644 --- a/src/main/ai-vault-search/session-search-retention-delete.ts +++ b/src/main/ai-vault-search/session-search-retention-delete.ts @@ -5,6 +5,8 @@ import { deleteSearchMessages } from './session-search-message-rows' export const RETENTION_DELETE_ROWS_PER_STEP = 256 // Reclaim freed pages incrementally to avoid a long vacuum after the purge. const RECLAIM_PAGES_PER_STEP = 2000 +// FTS merges free pages constantly and later writes reuse them; moving them each drain only churns the file. +const RECLAIM_FREE_PAGE_SHARE = 0.25 /** Hide expired sessions atomically, then reclaim their unreachable messages in bounded transactions. */ export async function deleteExpiredSearchFiles( @@ -64,12 +66,19 @@ export async function drainOrphanedMessages( db.exec('ROLLBACK') throw error } - db.pragma(`incremental_vacuum(${RECLAIM_PAGES_PER_STEP})`) + reclaimFreePages(db) if (deleted < RETENTION_DELETE_ROWS_PER_STEP) { orphan = (nextOrphan.get() as { session_row_id: number } | undefined)?.session_row_id } await yieldStep() } // removeFile may free pages even when this drain has no orphaned messages. - db.pragma(`incremental_vacuum(${RECLAIM_PAGES_PER_STEP})`) + reclaimFreePages(db) +} + +function reclaimFreePages(db: SyncDatabase): void { + const free = Number(db.pragma('freelist_count', { simple: true })) + if (free > Number(db.pragma('page_count', { simple: true })) * RECLAIM_FREE_PAGE_SHARE) { + db.pragma(`incremental_vacuum(${RECLAIM_PAGES_PER_STEP})`) + } } diff --git a/src/main/ai-vault-search/session-search-schema.ts b/src/main/ai-vault-search/session-search-schema.ts index 4c5aa58acaf..5c8ec720068 100644 --- a/src/main/ai-vault-search/session-search-schema.ts +++ b/src/main/ai-vault-search/session-search-schema.ts @@ -79,6 +79,8 @@ export function openSessionSearchDatabase(path: string): SyncDatabase { 'index_incarnation', randomUUID() ) + // Each small commit adds an FTS segment; wider merges mean fewer levels rewriting it (#36666). + db.prepare("INSERT INTO messages_fts(messages_fts, rank) VALUES ('automerge', 8)").run() // Older Cursor rows omitted the file-time fallback; repair metadata without rereading transcripts. db.exec(` UPDATE sessions SET updated_at = ( From c18515a5d9b5a0148845fb43b6eaa6674ff370ac Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:32:30 +0000 Subject: [PATCH 09/23] fix(ai-vault): keep search results on screen while typing in Session History (#39325) * fix(ai-vault): keep search results on screen while typing in Session History * perf(ai-vault): fold session search text once and keep resolver maps stable on empty replies --- .../ai-vault/panel/AiVaultPanel.tsx | 23 +++++----- ...-vault-panel-session-list-request.test.tsx | 36 +++++++++++++++- .../search/ai-vault-search-session.ts | 36 ++++++++++++++++ .../search/use-ai-vault-search.test.tsx | 29 +++++++++++++ .../ai-vault/search/use-ai-vault-search.ts | 43 +++++++++++-------- .../AiVaultSessionVirtualList.tsx | 28 ++++++++++-- .../session-list/ai-vault-session-filters.ts | 13 +++--- ...se-ai-vault-session-keyboard-navigation.ts | 20 +++++---- .../ai-vault-session-filters.ts | 39 +++++++++++------ 9 files changed, 207 insertions(+), 60 deletions(-) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx b/src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx index f10a3ced542..25c3a35a1e9 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx @@ -38,7 +38,7 @@ import { AgentSessionContinuationDialog } from '@/components/agent-session-conti import { AiVaultScanIssueBanners } from '../scanning/AiVaultScanIssueBanners' import { useAiVaultSessionDeleteAction } from '../session-actions/ai-vault-session-delete-action' import { useAiVaultPanelSearch } from '../search/use-ai-vault-search' -import { withAiVaultHistoryPreviews } from '../search/ai-vault-search-session' +import { useAiVaultPanelSearchSessions } from '../search/ai-vault-search-session' import { aiVaultSearchScopeIdentity } from '../search/ai-vault-search-scope-identity' import { AiVaultPanelSearch } from '../search/AiVaultPanelSearch' import { useAiVaultPanelSessionResume } from '../session-actions/use-ai-vault-panel-session-resume' @@ -174,11 +174,10 @@ export default function AiVaultPanel({ ) const search = useAiVaultPanelSearch(query, agents, searchWithin, executionHostScope, searchSort) const { searching, searchHits } = search - const searchSessions = useMemo( - () => withAiVaultHistoryPreviews(search.sessions, history), - [history, search.sessions] + const { listMode, stale, sessions, resolverSessions } = useAiVaultPanelSearchSessions( + search, + history ) - const sessions = searching ? searchSessions : history const requestedScanKey = aiVaultLocalScanKey({ scopePaths, includeAntigravityIdeSessions: true, @@ -194,9 +193,9 @@ export default function AiVaultPanel({ repos, worktrees: allWorktrees, projectHostSetupProjection, - sessions + sessions: resolverSessions }), - [allWorktrees, projectHostSetupProjection, repos, sessions] + [allWorktrees, projectHostSetupProjection, repos, resolverSessions] ) const effectiveActiveWorktreeId = activeWorktreeId ?? activeWorktree?.id ?? null const { @@ -205,7 +204,7 @@ export default function AiVaultPanel({ getSessionResumeActions, getSessionResumeInChat } = useAiVaultPanelSessionResume({ - sessions, + sessions: resolverSessions, repos, allWorktrees, workspaceId: effectiveActiveWorktreeId, @@ -225,7 +224,7 @@ export default function AiVaultPanel({ sessionLimit }) - const { filteredSessions, groups } = useAiVaultPanelSessions(sessions, searching, group, { + const { filteredSessions, groups } = useAiVaultPanelSessions(sessions, listMode, group, { query, agents, scope, @@ -328,7 +327,9 @@ export default function AiVaultPanel({ )} {(!searching || sessions.length > 0 || search.loading) && ( { + useAppStore.setState({ + settings: { + ...getDefaultSettings('/tmp'), + aiVaultSearch: { ...resolveAiVaultSearchSettings({}), enabled: true } + } + }) + const loaded = (sessionId: string, title: string) => + aiVaultSearchHitToSession( + { ...searchHit(), agent: 'claude', cwd: '/repo/wt', sessionId, title }, + 'local' + ) + returned.sessions = [loaded('login', 'Fix login redirect'), loaded('parser', 'Refactor parser')] + const search = vi.mocked(window.api.aiVault.searchSessions).mockReturnValue(new Promise(() => {})) + const { default: AiVaultPanel } = await import('../panel/AiVaultPanel') + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + try { + render() + fireEvent.change(screen.getByRole('textbox', { name: 'Search sessions' }), { + target: { value: 'login' } + }) + expect(panelRows.map((row) => row.session.sessionId)).toEqual(['login']) + await act(async () => { + await vi.advanceTimersByTimeAsync(250) + }) + expect(search).toHaveBeenCalled() + expect(panelRows.map((row) => row.session.sessionId)).toEqual(['login']) + } finally { + vi.useRealTimers() + } +}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.ts b/src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.ts index 804d63e27a3..be15baa6edf 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.ts @@ -1,7 +1,9 @@ +import { useMemo } from 'react' import type { AiVaultSearchHit } from '../../../../../../shared/ai-vault/search/ai-vault-search-types' import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { withAiVaultSessionCwdAliases } from '../../../../../../shared/ai-vault/scanning/ai-vault-session-cwd-aliases' +import type { AiVaultPanelListMode } from '../session-list/ai-vault-session-filters' export function aiVaultSearchHitToSession( hit: AiVaultSearchHit, @@ -91,3 +93,37 @@ export function canResumeAiVaultSearchHit(hit: AiVaultSearchHit): boolean { export function hasAiVaultSearchHitPath(hit: AiVaultSearchHit): boolean { return hit.source.presence === 'present' && hit.source.filePath !== undefined } + +/** What the panel lists for the current search state, and which sessions feed its project and worktree lookups. */ +export function useAiVaultPanelSearchSessions( + search: { + searching: boolean + loading: boolean + answered: boolean + hits: readonly AiVaultSearchHit[] + sessions: AiVaultSession[] + }, + history: readonly AiVaultSession[] +) { + const searchSessions = useMemo( + () => withAiVaultHistoryPreviews(search.sessions, history), + [history, search.sessions] + ) + // Until this query's first reply, older hits stay dimmed or, with none, title matches fill the wait. + const waitingForHits = search.searching && search.loading && !search.answered + const searchTitles = waitingForHits && search.hits.length === 0 + const showHits = search.searching && !searchTitles + const listMode: AiVaultPanelListMode = search.searching + ? searchTitles + ? 'search-titles' + : 'search-hits' + : 'browse' + return { + listMode, + stale: waitingForHits && search.hits.length > 0, + sessions: showHits ? searchSessions : history, + // Project and worktree lookups scan sessions against every worktree. Keep them on history + // unless hits are on screen, so an empty reply doesn't rebuild them on every pause in typing. + resolverSessions: showHits && searchSessions.length > 0 ? searchSessions : history + } +} diff --git a/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx b/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx index 7cfbe788edd..21fff8bd8c8 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx +++ b/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx @@ -230,3 +230,32 @@ it('revalidates active search without losing hits, accepting old pages, or touch await act(async () => feeds.emit.get('a')?.({ type: 'snapshot', sessions: [] })) expect(searchSessions).toHaveBeenCalledTimes(baseline + 2) }) + +it('keeps the last hits on screen until a newer query answers, ignoring the older reply', async () => { + const hit = (sessionId: string) => ({ ...searchHit(), sessionId }) + let answerOld = (_response: AiVaultSearchResponse): void => {} + searchSessions + .mockResolvedValueOnce({ ...searchResults(), hits: [hit('first')] }) + .mockImplementationOnce( + () => + new Promise((resolve) => { + answerOld = resolve + }) + ) + .mockResolvedValueOnce({ ...searchResults(), hits: [hit('newest')] }) + const { result, rerender, unmount } = renderHook( + ({ request }) => useAiVaultSearch(request, 'local', ''), + { initialProps: { request: { query: 'n' } } } + ) + await debounce() + rerender({ request: { query: 'ne' } }) + await debounce() + rerender({ request: { query: 'nee' } }) + expect(result.current.hits.map((entry) => entry.sessionId)).toEqual(['first']) + expect(result.current.answered).toBe(false) + await debounce() + await act(async () => answerOld({ ...searchResults(), hits: [hit('older')] })) + expect(result.current.hits.map((entry) => entry.sessionId)).toEqual(['newest']) + expect(result.current.answered).toBe(true) + unmount() +}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.ts b/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.ts index 75822d6b6ec..d399f92abdd 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.ts @@ -61,7 +61,7 @@ export function useAiVaultSearch( let pending = false let followUp = false let started = false - async function run(cursor?: string, revalidate = false) { + async function run(cursor?: string) { if (pending || cancelled || !request || !scope) { return } @@ -69,13 +69,12 @@ export function useAiVaultSearch( started = true const revision = associations.getSnapshot() const isCurrent = () => !cancelled && revision === associations.getSnapshot() - setPage((previous) => ({ - identity, - hits: (cursor || revalidate) && previous?.identity === identity ? previous.hits : [], - response: null, - error: false, - loading: true - })) + // Only a rerun of the same request touches its page; a new request's page waits for its reply. + setPage((previous) => + previous?.identity === identity + ? { ...previous, response: null, error: false, loading: true } + : previous + ) try { let response = await window.api.aiVault.searchSessions({ ...request, cursor }, scope) let append = Boolean(cursor) @@ -110,7 +109,7 @@ export function useAiVaultSearch( pending = false if (followUp && !cancelled) { followUp = false - void run(undefined, true) + void run() } } } @@ -122,10 +121,10 @@ export function useAiVaultSearch( if (pending) { followUp = true } else { - void run(undefined, true) + void run() } }) - const timer = setTimeout(() => void run(undefined, true), 250) + const timer = setTimeout(() => void run(), 250) return () => { cancelled = true followUp = false @@ -135,17 +134,26 @@ export function useAiVaultSearch( } }, [identity, associations]) + // Leaving search drops its hits so returning cannot revive another request's results or cursor. + if (page && !(request && scope)) { + setPage(null) + } const current = page?.identity === identity ? page : null + // Same-host hits stay visible while a newer request is debounced or in flight. + const shown = current ?? (page?.identity.scope === scope ? page : null) return { - hits: current?.hits ?? [], + hits: shown?.hits ?? [], + /** The hits answer this request; until then they are an older request's, or none. */ + answered: current !== null, + /** Changes when hits for a different request land, never while one is pending. */ + resultsKey: JSON.stringify(shown ? [shown.identity.scope, shown.identity.request] : null), response: current?.response ?? null, error: current?.error ?? false, loading: Boolean(request && scope && (!current || current.loading)), removeHit: (hit: AiVaultSearchHit) => - setPage((previous) => - previous?.identity === identity - ? { ...previous, hits: previous.hits.filter((entry) => entry !== hit) } - : previous + setPage( + (previous) => + previous && { ...previous, hits: previous.hits.filter((entry) => entry !== hit) } ), retry: () => setRevision((value) => value + 1), loadMore: () => { @@ -235,7 +243,6 @@ export function useAiVaultPanelSearch( hasQuery, needsLocalConsent, titleOnly: hasQuery && titleOnly, - host, - resetKey: JSON.stringify([scope, request]) + host } } diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionVirtualList.tsx b/src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionVirtualList.tsx index 97a491a17fa..9fb1525250f 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionVirtualList.tsx +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionVirtualList.tsx @@ -1,6 +1,6 @@ import { SubagentExpansionProvider } from './ai-vault-subagent-expansion' import { useVirtualizer } from '@tanstack/react-virtual' -import { useCallback, useMemo, useRef, useState, type Ref } from 'react' +import { useCallback, useLayoutEffect, useMemo, useRef, useState, type Ref } from 'react' import type { AgentDotState } from '@/components/AgentStateDot' import type { AiVaultScope, @@ -8,6 +8,7 @@ import type { } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import type { AiVaultResumeStartup } from '../../../../../../shared/ai-vault/resume/ai-vault-resume-startup' import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' import { measureVirtualRowRetainingHiddenSize } from '@/hooks/virtualized-hidden-row-measurement' import { getActiveStickyHeaderIndexForScroll } from '../../../sidebar/worktree-list/viewport/virtual-rows' import { EmptyState, SessionLoadingState } from './AiVaultSessionListStates' @@ -45,6 +46,8 @@ export function AiVaultSessionVirtualList({ groups, collapsedGroups, loading, + stale = false, + resultsKey, scopePending = false, scanProgressShown = false, sessionsCount, @@ -84,6 +87,10 @@ export function AiVaultSessionVirtualList({ groups: readonly AiVaultSessionListGroup[] collapsedGroups: ReadonlySet loading: boolean + /** Rows answer an older search while a newer one runs. */ + stale?: boolean + /** Changes when a different result set lands, which returns the list to its top match. */ + resultsKey?: string scopePending?: boolean /** The progress strip above names the scan, so the list does not repeat it. */ scanProgressShown?: boolean @@ -130,6 +137,9 @@ export function AiVaultSessionVirtualList({ const stickyRangeStartIndexRef = useRef(0) const activeStickyHeaderIndexRef = useRef(null) const [expandedSessionIds, setExpandedSessionIds] = useState>(() => new Set()) + useLayoutEffect(() => { + listScrollRef.current?.scrollTo({ top: 0 }) + }, [resultsKey]) const vaultRows = useMemo(() => { const rows: AiVaultListRow[] = [] @@ -148,7 +158,11 @@ export function AiVaultSessionVirtualList({ }, [collapsedGroups, groups]) const stickyHeaderIndexes = useMemo(() => getVaultStickyHeaderIndexes(vaultRows), [vaultRows]) - const selection = useAiVaultSessionSelection(vaultRows, keyboardRef !== undefined, query) + const selection = useAiVaultSessionSelection( + vaultRows, + keyboardRef !== undefined, + JSON.stringify([query, resultsKey ?? null]) + ) const { selectedIndex } = selection const virtualizer = useVirtualizer({ @@ -231,6 +245,10 @@ export function AiVaultSessionVirtualList({ } // Enter resumes the row in the chat; a row that can't shows its details instead. const activateSession = (session: AiVaultSession, index: number): void => { + // A stale row answers an older query, so Enter waits for the current one. + if (stale) { + return + } if (!pickHere(session)) { setExpandedSessionIds((current) => new Set(current).add(session.id)) virtualizer.scrollToIndex(index) @@ -288,7 +306,11 @@ export function AiVaultSessionVirtualList({ ) : null} {vaultRows.length > 0 ? ( -
+
{virtualItems.map((virtualRow) => ( - searching + mode === 'search-hits' ? sessions : filterAiVaultSessions(sessions, { query, @@ -49,7 +52,7 @@ export function useAiVaultPanelSessions( hideEmptySessions }), [ - searching, + mode, sessions, query, agents, @@ -64,13 +67,13 @@ export function useAiVaultPanelSessions( ) const groups = useMemo( () => - searching + mode !== 'browse' ? filteredSessions.length === 0 ? [] : // The results bar above the list carries the count, so this group only holds rows. [{ key: 'search-results', label: null, sessions: [...filteredSessions] }] : groupAiVaultSessions(filteredSessions, group, { sessionProjectById, projectLabelByKey }), - [searching, filteredSessions, group, projectLabelByKey, sessionProjectById] + [mode, filteredSessions, group, projectLabelByKey, sessionProjectById] ) return { filteredSessions, groups } } diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-list/use-ai-vault-session-keyboard-navigation.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-list/use-ai-vault-session-keyboard-navigation.ts index 0cacaf0083e..fba50964c95 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-list/use-ai-vault-session-keyboard-navigation.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-list/use-ai-vault-session-keyboard-navigation.ts @@ -22,20 +22,22 @@ export type AiVaultSessionSelection = { move: (delta: 1 | -1) => number | null } -/** Reconcile selected session/row after list changes; new queries reset to the top match. */ +/** Reconcile selected session/row after list changes; a new `resetKey` (query or result set) resets to the top match. */ export function useAiVaultSessionSelection( rows: readonly AiVaultListRow[], enabled: boolean, - query: string + resetKey: string ): AiVaultSessionSelection { - const [stored, setStored] = useState<{ index: number; sessionId: string; query: string } | null>( - null - ) - // Clear query-owned picks so reverting search text cannot revive them. - if (stored !== null && stored.query !== query) { + const [stored, setStored] = useState<{ + index: number + sessionId: string + resetKey: string + } | null>(null) + // Clear picks owned by an older key so reverting search text cannot revive them. + if (stored !== null && stored.resetKey !== resetKey) { setStored(null) } - const chosen = stored?.query === query ? stored : null + const chosen = stored?.resetKey === resetKey ? stored : null const sessionIndexes = useMemo( () => rows.flatMap((row, index) => (row.type === 'session' ? [index] : [])), [rows] @@ -51,7 +53,7 @@ export function useAiVaultSessionSelection( const select = (index: number): void => { const sessionId = sessionIdAt(rows, index) if (sessionId !== null) { - setStored({ index, sessionId, query }) + setStored({ index, sessionId, resetKey }) } } return { diff --git a/src/shared/ai-vault/session-display/ai-vault-session-filters.ts b/src/shared/ai-vault/session-display/ai-vault-session-filters.ts index 6f33d5e9628..5bfa080a254 100644 --- a/src/shared/ai-vault/session-display/ai-vault-session-filters.ts +++ b/src/shared/ai-vault/session-display/ai-vault-session-filters.ts @@ -208,19 +208,7 @@ function matchesQuery( filters: Pick ): boolean { if (parsed.terms.length > 0) { - const searchable = [ - session.title, - session.sessionId, - session.agent, - session.branch, - session.model, - session.cwd, - session.filePath, - sessionPreviewSearchText(session) - ] - .filter(Boolean) - .join(' ') - .toLowerCase() + const searchable = sessionSearchableText(session) if (parsed.terms.some((term) => !searchable.includes(term))) { return false } @@ -239,6 +227,31 @@ function matchesQuery( ) } +// Session objects are replaced, never mutated, so the folded text can live as long as the object. +// Building it costs a few KB per session; rebuilding it per keystroke over thousands of sessions janks typing. +const searchableTextBySession = new WeakMap() + +function sessionSearchableText(session: AiVaultSession): string { + let searchable = searchableTextBySession.get(session) + if (searchable === undefined) { + searchable = [ + session.title, + session.sessionId, + session.agent, + session.branch, + session.model, + session.cwd, + session.filePath, + sessionPreviewSearchText(session) + ] + .filter(Boolean) + .join(' ') + .toLowerCase() + searchableTextBySession.set(session, searchable) + } + return searchable +} + function sessionSortTime(session: AiVaultSession, sort: AiVaultSort): number { const value = sort === 'created' ? session.createdAt : session.updatedAt return Date.parse(value ?? session.modifiedAt) From c5c12af6f7ea901a89449f7fe0d105895aca765e Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:32:44 +0000 Subject: [PATCH 10/23] fix(session-history): match more Claude and Pi folder names in scope recovery (#39936) Workspace and Project add older in-scope sessions by matching agent folder names to the scope. Several real names were missed: Claude's truncated long-path buckets, Windows paths in another case, drive and filesystem roots, the other WSL share spelling, and Pi buckets under PI_CODING_AGENT_DIR's sessions/ folder. An unreadable folder now shows up as a scan issue instead of looking empty. --- .../claude/claude-project-dir-encoding.ts | 30 +++++++ ...session-scanner-pi-omp-shared-root.test.ts | 9 +- .../ai-vault/session-cwd-bucket-layouts.ts | 14 ++- .../ai-vault/session-scanner-discovery.ts | 7 +- .../session-scanner-scope-discovery.ts | 24 ++++-- .../session-scanner-scope-inventory.ts | 2 +- .../ai-vault/session-scanner-scope.test.ts | 85 ++++++++++++++++++- src/shared/wsl-paths.ts | 6 ++ 8 files changed, 159 insertions(+), 18 deletions(-) diff --git a/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts b/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts index 2ad999b40fa..facf7c026e0 100644 --- a/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts +++ b/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts @@ -28,6 +28,36 @@ export function isClaudeProjectDirInScope( return false } +// Claude Code names a longer encoded path's bucket `-`; older versions kept the full name. +const CLAUDE_BUCKET_NAME_MAX_LENGTH = 200 + +/** Bucket-name prefixes for a scope, including the 200-character cut Claude Code makes for long paths. */ +export function claudeProjectBucketScopePrefixes(pathValue: string): string[] { + return encodeClaudeProjectPaths(pathValue).flatMap((encoded) => + encoded.length > CLAUDE_BUCKET_NAME_MAX_LENGTH + ? [encoded, encoded.slice(0, CLAUDE_BUCKET_NAME_MAX_LENGTH)] + : [encoded] + ) +} + +/** Like isClaudeProjectDirInScope, but a root (`-`, `C--`) keeps its separator, so it prefixes every bucket. */ +export function isClaudeProjectBucketInScope( + projectDirName: string, + scopePrefixes: ReadonlySet +): boolean { + for (const prefix of scopePrefixes) { + const isRoot = prefix === '-' || /^[A-Za-z]--$/.test(prefix) + if ( + isRoot + ? projectDirName.startsWith(prefix) + : isClaudeProjectDirInScope(projectDirName, [prefix]) + ) { + return true + } + } + return false +} + /** Transcripts sit in project buckets (depth 0); `/` folders below hold only subagent and tool output. */ export function isClaudeProjectBucketDirectory(_name: string, depth: number): boolean { return depth === 0 diff --git a/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts b/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts index 0d514b81bd3..7a743a0b37b 100644 --- a/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts +++ b/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts @@ -122,15 +122,22 @@ async function writeSharedRootTranscripts(sessionsDir: string): Promise { describe('scanAiVaultSessions with overlapping Pi and OMP roots', () => { const sameFolder = (sessionsDir: string): string => sessionsDir + const parentFolder = (sessionsDir: string): string => join(sessionsDir, '..') it.each([ { layout: 'the same folder', piRoot: sameFolder, scope: {} }, // PI_CODING_AGENT_DIR=: Pi walks , OMP walks /sessions. - { layout: 'a parent folder', piRoot: (dir: string) => join(dir, '..'), scope: {} }, + { layout: 'a parent folder', piRoot: parentFolder, scope: {} }, // A one-row cap sends the rest through scope recovery: Pi's buckets and OMP's walk. { layout: 'the same folder for a workspace', piRoot: sameFolder, scope: { scopePaths: ['/repo/app'], limit: 1 } + }, + // Scope recovery reads Pi's cwd buckets, which sit under the agent folder's sessions/. + { + layout: 'a parent folder for a workspace', + piRoot: parentFolder, + scope: { scopePaths: ['/repo/app'], limit: 1 } } ])('lists each transcript once under its writer when Pi scans $layout', async (testCase) => { const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-pi-omp-shared-')) diff --git a/src/main/ai-vault/session-cwd-bucket-layouts.ts b/src/main/ai-vault/session-cwd-bucket-layouts.ts index cb4e2de2fb6..2579edf2175 100644 --- a/src/main/ai-vault/session-cwd-bucket-layouts.ts +++ b/src/main/ai-vault/session-cwd-bucket-layouts.ts @@ -1,19 +1,22 @@ +import { basename, join } from 'node:path' import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types' import { - encodeClaudeProjectPaths, - isClaudeProjectDirInScope + claudeProjectBucketScopePrefixes, + isClaudeProjectBucketInScope } from './scanners/claude/claude-project-dir-encoding' export type CwdBucketLayout = { agent: Extract encodeScopePrefixes: (scopePath: string) => string[] isDirInScope: (dirName: string, prefixes: ReadonlySet) => boolean + /** Folders whose children are cwd buckets; defaults to the root itself. */ + bucketDirs?: (rootDir: string) => string[] } export const CLAUDE_CWD_BUCKET_LAYOUT: CwdBucketLayout = { agent: 'claude', - encodeScopePrefixes: encodeClaudeProjectPaths, - isDirInScope: isClaudeProjectDirInScope + encodeScopePrefixes: claudeProjectBucketScopePrefixes, + isDirInScope: isClaudeProjectBucketInScope } // Omit Pi's closing -- so the prefix also matches nested working directories. @@ -24,6 +27,9 @@ function encodePiSessionDirPrefix(pathValue: string): string { export const PI_CWD_BUCKET_LAYOUT: CwdBucketLayout = { agent: 'pi', + // PI_CODING_AGENT_DIR= makes Pi's root the agent folder, whose buckets sit under sessions/. + bucketDirs: (rootDir) => + basename(rootDir) === 'sessions' ? [rootDir] : [rootDir, join(rootDir, 'sessions')], encodeScopePrefixes: (pathValue) => { const raw = encodePiSessionDirPrefix(pathValue) const composed = encodePiSessionDirPrefix(pathValue.normalize('NFC')) diff --git a/src/main/ai-vault/session-scanner-discovery.ts b/src/main/ai-vault/session-scanner-discovery.ts index e9e76c42f2e..e789b0903b9 100644 --- a/src/main/ai-vault/session-scanner-discovery.ts +++ b/src/main/ai-vault/session-scanner-discovery.ts @@ -246,11 +246,12 @@ async function observeSessionSidecar( sizeBytes: fileStat.size } } catch (error) { - return isMissingSidecarError(error) ? 'none' : 'unknown' + return isMissingTranscriptPathError(error) ? 'none' : 'unknown' } } -function isMissingSidecarError(error: unknown): boolean { +/** A missing file or folder is absence, not a refusal; WSL gate errors are always refusals. */ +export function isMissingTranscriptPathError(error: unknown): boolean { if (error instanceof WslTranscriptFsError) { return false } @@ -295,7 +296,7 @@ export async function forEachSessionFile( // Propagate gate refusal so stalled distros are not reported as empty trees. if ( error instanceof WslTranscriptFsError || - (options.strictErrors && !isMissingSidecarError(error)) + (options.strictErrors && !isMissingTranscriptPathError(error)) ) { throw error } diff --git a/src/main/ai-vault/session-scanner-scope-discovery.ts b/src/main/ai-vault/session-scanner-scope-discovery.ts index 7cbfefc2850..bcbd59b8b4b 100644 --- a/src/main/ai-vault/session-scanner-scope-discovery.ts +++ b/src/main/ai-vault/session-scanner-scope-discovery.ts @@ -5,16 +5,16 @@ import { wslGatedReaddir, wslGatedStat } from '../native-chat/wsl-transcript-fs-access' -import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import type { createAiVaultScopeCwdMatcher } from '../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' import type { CwdBucketLayout } from './session-cwd-bucket-layouts' import type { AiVaultAgent, AiVaultScanIssue } from '../../shared/ai-vault/contracts/ai-vault-types' -import { parseWslUncPath } from '../../shared/wsl-paths' +import { parseWslUncPath, toWindowsWslUncPathSpellings } from '../../shared/wsl-paths' import { throwIfAiVaultScanCancelled } from './ai-vault-scan-cancellation' import { yieldToEventLoop } from '../../shared/event-loop-yield' import type { FileWithMtime } from './session-scanner-types' import { extractString, parseJsonObject } from './session-scanner-values' import { scanIssueTextFromError } from './session-scan-issues' +import { isMissingTranscriptPathError } from './session-scanner-discovery' // Limit representative probing when a bucket contains transcripts without cwd records. const REPRESENTATIVE_CWD_LINE_LIMIT = 200 @@ -30,14 +30,14 @@ export function resetProjectDirCwdCacheForTests(): void { projectDirCwdCache.clear() } -// Report WSL refusal so an unreachable root is not mistaken for an empty one. +// Report refusals (WSL, permissions) so an unreadable folder or transcript is not mistaken for an empty one. export function recordRefusal( issues: IssueSink, path: string, error: unknown, agent: AiVaultAgent ): void { - if (error instanceof WslTranscriptFsError) { + if (!isMissingTranscriptPathError(error)) { issues({ agent, path, ...scanIssueTextFromError(error) }) } } @@ -76,16 +76,20 @@ export function cwdBucketScopePrefixes( for (const scopePath of scopePaths) { for (const candidate of scopePathCandidates(scopePath)) { for (const prefix of layout.encodeScopePrefixes(candidate)) { - prefixes.add(prefix) + prefixes.add(prefix.toLowerCase()) } } } return prefixes } +// A WSL share has two UNC spellings, and a transcript may record either one. function scopePathCandidates(scopePath: string): string[] { - const wslScopePath = parseWslUncPath(scopePath) - return wslScopePath ? [scopePath, wslScopePath.linuxPath] : [scopePath] + const wsl = parseWslUncPath(scopePath) + if (!wsl) { + return [scopePath] + } + return [scopePath, wsl.linuxPath, ...toWindowsWslUncPathSpellings(wsl.linuxPath, wsl.distro)] } export async function listProjectDirs( @@ -106,8 +110,12 @@ export async function listProjectDirs( recordRefusal(issues, rootDir, err, layout.agent) return [] } + // Case-folded: Windows cwds differ in case, and each bucket's cwd is still checked afterwards. return entries - .filter((entry) => entry.isDirectory() && layout.isDirInScope(entry.name, scopeProjectPrefixes)) + .filter( + (entry) => + entry.isDirectory() && layout.isDirInScope(entry.name.toLowerCase(), scopeProjectPrefixes) + ) .map((entry) => join(rootDir, entry.name)) } diff --git a/src/main/ai-vault/session-scanner-scope-inventory.ts b/src/main/ai-vault/session-scanner-scope-inventory.ts index 170cf35f924..c0408671123 100644 --- a/src/main/ai-vault/session-scanner-scope-inventory.ts +++ b/src/main/ai-vault/session-scanner-scope-inventory.ts @@ -66,7 +66,7 @@ export async function inventoryCwdBucketFiles( const prefixes = cwdBucketScopePrefixes(layout, args.scopePaths) const inScope = createAiVaultScopeCwdMatcher(args.scopePaths) let index = 0 - for (const rootDir of args.rootDirs) { + for (const rootDir of args.rootDirs.flatMap(layout.bucketDirs ?? ((dir) => [dir]))) { throwIfAiVaultScanCancelled(args.signal) let close: () => void = () => undefined try { diff --git a/src/main/ai-vault/session-scanner-scope.test.ts b/src/main/ai-vault/session-scanner-scope.test.ts index 39f4b2faa17..0af9cfc9b68 100644 --- a/src/main/ai-vault/session-scanner-scope.test.ts +++ b/src/main/ai-vault/session-scanner-scope.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, mkdir, rm, utimes, writeFile } from 'node:fs/promises' +import { chmod, mkdtemp, mkdir, rm, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -37,6 +37,30 @@ function scopedScanOptions(claudeProjectsDir: string, extra: Partial { + await writeClaudeSession({ + claudeRoot, + ...old, + sessionId: 'old-in-scope', + iso: '2026-01-01T00:00:00.000Z' + }) + for (let index = 0; index < 4; index++) { + await writeClaudeSession({ + claudeRoot, + dirName: `-other-${index}`, + sessionId: `recent-${index}`, + cwd: `/other/${index}`, + iso: `2026-06-2${index}T00:00:00.000Z` + }) + } +} + +const LONG_PATH = `/repo/${'nested-folder/'.repeat(16)}app` + async function writeClaudeSession(args: { claudeRoot: string dirName: string @@ -140,4 +164,63 @@ describe('scanAiVaultSessions scope inclusion', () => { expect(result.sessions.map((session) => session.sessionId)).not.toContain('old-wsl-in-scope') }) + + it.each([ + { layout: 'a drive root', scopePath: 'C:\\', dirName: 'C--repo', cwd: 'C:\\repo' }, + { + layout: 'a Windows path in another case', + scopePath: 'c:\\users\\ada\\repo', + dirName: 'C--Users-Ada-repo', + cwd: 'C:\\Users\\Ada\\repo' + }, + { + layout: 'the other WSL share spelling', + scopePath: '\\\\wsl.localhost\\Ubuntu\\home\\ada\\repo', + dirName: '--wsl--Ubuntu-home-ada-repo', + cwd: '\\\\wsl$\\Ubuntu\\home\\ada\\repo' + }, + { + // Claude Code names a bucket over 200 characters `-`. + layout: 'a long path', + scopePath: LONG_PATH, + dirName: `${LONG_PATH.replace(/[^a-zA-Z0-9]/g, '-').slice(0, 200)}-1a2b3c`, + cwd: LONG_PATH + } + ])('finds older in-scope Claude sessions for $layout', async ({ scopePath, dirName, cwd }) => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-scope-')) + tempRoots.push(root) + const claudeRoot = join(root, 'claude-projects') + await writeOldClaudeSessionBehindRecentOnes(claudeRoot, { dirName, cwd }) + + const result = await scanAiVaultSessions( + scopedScanOptions(claudeRoot, { limit: 2, scopePaths: [scopePath] }) + ) + + expect(result.sessions.map((session) => session.sessionId)).toContain('old-in-scope') + }) + + // chmod cannot lock out root, and Windows ignores the mode bits. + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'reports an unreadable in-scope folder instead of listing it as empty', + async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-scope-')) + tempRoots.push(root) + const claudeRoot = join(root, 'claude-projects') + await writeOldClaudeSessionBehindRecentOnes(claudeRoot, { + dirName: '-repo-app', + cwd: '/repo/app' + }) + const bucket = join(claudeRoot, '-repo-app') + await chmod(bucket, 0o000) + try { + const result = await scanAiVaultSessions( + scopedScanOptions(claudeRoot, { limit: 2, scopePaths: ['/repo/app'] }) + ) + + expect(result.issues.map((issue) => issue.path)).toContain(bucket) + } finally { + await chmod(bucket, 0o755) + } + } + ) }) diff --git a/src/shared/wsl-paths.ts b/src/shared/wsl-paths.ts index 68819233440..b71949a4d23 100644 --- a/src/shared/wsl-paths.ts +++ b/src/shared/wsl-paths.ts @@ -69,6 +69,12 @@ export function toWindowsWslUncPath(linuxPath: string, distro: string): string { return `\\\\wsl.localhost\\${distro}${linuxPath === '/' ? '\\' : linuxPath.replace(/\//g, '\\')}` } +/** Both UNC spellings of a WSL path: `\\\\wsl.localhost\\` and the older `\\\\wsl$\\`. */ +export function toWindowsWslUncPathSpellings(linuxPath: string, distro: string): string[] { + const localhost = toWindowsWslUncPath(linuxPath, distro) + return [localhost, `\\\\wsl$${localhost.slice('\\\\wsl.localhost'.length)}`] +} + /** Resolve an absolute POSIX base within the repo’s WSL distro; Windows otherwise treats it as drive-relative and discards it (STA-4772). Other forms pass through. * Keep drvfs on the distro UNC view so mirroring retains WSL terminal routing. Preserve ambiguous multi-slash/backslash roots unchanged; collapse dot segments so creation and ownership classification agree. */ export function resolveWslRepoWorktreeBasePath(repoPath: string, basePath: string): string { From 8f58492e3f255652cdea2fe6da6b36290e32d346 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 11:37:14 -0800 Subject: [PATCH 11/23] fix(toasts): match toast action buttons to Orca's Button (#39935) * fix(toasts): match toast action buttons to Orca's Button * fix(toasts): keep toast cancel buttons on the secondary color in dark mode --- src/renderer/src/assets/main.css | 36 +++++++++++++++++++ .../claude-theme-sync-offer.ts | 4 +-- src/renderer/src/i18n/locales/en.json | 4 +-- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 996f314de67..f5412aa291f 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -588,6 +588,42 @@ body[data-modal-overlay-open] [data-toasts-raised] [data-sonner-toaster] { margin-left: 0; } +/* Why: Sonner's 24px buttons with untokened fills don't match Orca; mirror Button size="sm" default/secondary. */ +[data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-button] { + height: 2rem; + padding: 0 0.75rem; + border-radius: calc(var(--radius) - 2px); + font-size: 0.875rem; + font-weight: 500; + background: var(--primary); + color: var(--primary-foreground); + transition: + opacity 0.4s, + box-shadow 0.2s, + background-color 150ms; +} + +[data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-button]:hover { + background: color-mix(in oklab, var(--primary) 90%, transparent); +} + +[data-sonner-toaster][data-sonner-theme] + [data-sonner-toast][data-styled='true'] + [data-button][data-cancel] { + background: var(--secondary); + color: var(--secondary-foreground); +} + +[data-sonner-toaster][data-sonner-theme] + [data-sonner-toast][data-styled='true'] + [data-button][data-cancel]:hover { + background: color-mix(in oklab, var(--secondary) 80%, transparent); +} + +[data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-button]:focus-visible { + box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent); +} + [data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-title] { line-height: 1.35; } diff --git a/src/renderer/src/components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer.ts b/src/renderer/src/components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer.ts index f3e546a353e..8e49967f640 100644 --- a/src/renderer/src/components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer.ts +++ b/src/renderer/src/components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer.ts @@ -27,7 +27,7 @@ function showClaudeThemeSyncOffer(): void { duration: Infinity, classNames: TRAILING_ACTIONS_CLASS_NAMES, action: { - label: translate('terminal.claudeThemeSyncOffer.accept', 'Match Theme'), + label: translate('terminal.claudeThemeSyncOffer.accept', 'Match theme'), onClick: () => { // Why confirm only after the write: a failed save must not claim the sync is on. updateSettingsOrThrow({ claudeCodeThemeSync: true }).then( @@ -58,7 +58,7 @@ function showClaudeThemeSyncOffer(): void { } }, cancel: { - label: translate('terminal.claudeThemeSyncOffer.decline', 'No Thanks'), + label: translate('terminal.claudeThemeSyncOffer.decline', 'No thanks'), onClick: () => {} } }) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index daac77282ca..da6289db69e 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -22342,10 +22342,10 @@ "claudeThemeSyncOffer": { "title": "Match Claude Code to your Orca theme?", "description": "Claude Code on this computer would use your terminal colors and follow theme changes, including outside Orca. You can change this in Settings.", - "accept": "Match Theme", + "accept": "Match theme", "accepted": "Claude Code theme sync is on", "acceptedDescription": "New Claude Code sessions on this computer use your Orca theme.", - "decline": "No Thanks", + "decline": "No thanks", "failed": "Could not turn on Claude Code theme sync", "failedDescription": "Turn it on in Settings." } From 51c77320bc3302923ad4e194de7edacb2a91b6b6 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:40:47 +0000 Subject: [PATCH 12/23] feat(mobile): mark agents read and clear them from the Agents tab (#39245) Unread rows show the desktop's bell, swipe right toggles read, swipe left clears a finished agent, and the long-press and options menus get Mark read/unread, Unread only, Mark all read and Clear finished. Writes go through agentActivity.setRead/clear and show optimistically until the desktop's list confirms them. --- mobile/src/agents/MobileAgentListRows.tsx | 274 +++++++++++------- mobile/src/agents/agent-list-model.test.ts | 128 +++++++- mobile/src/agents/agent-list-model.ts | 229 +++++---------- mobile/src/agents/agent-list-preferences.ts | 4 +- mobile/src/agents/agent-list-row-text.ts | 8 +- mobile/src/agents/agent-list-rows.ts | 190 ++++++++++++ .../src/agents/use-agent-activity-writes.ts | 133 +++++++++ .../src/agents/use-agent-list-row-actions.tsx | 162 ++++++++--- mobile/src/cache/worktree-cache.test.ts | 35 +-- mobile/src/cache/worktree-cache.ts | 11 +- mobile/src/components/AgentStateDot.tsx | 1 + mobile/src/components/SwipeRowActions.tsx | 151 ++++++++++ mobile/src/home/MobileHomeNeedsYou.tsx | 20 +- mobile/src/home/MobileHomeScreen.tsx | 238 +++++++-------- .../tabs/MobileHomeAgentsDesktopFilter.tsx | 107 +++++++ mobile/src/home/tabs/MobileHomeAgentsTab.tsx | 259 ++++++++--------- mobile/src/home/tabs/MobileHomeFeedTab.tsx | 3 +- mobile/src/home/use-mobile-home-data.ts | 28 +- .../home/use-mobile-home-host-connections.ts | 4 +- mobile/src/i18n/locales/en.json | 32 +- .../MobileSourceControlFileRows.tsx | 131 ++------- .../mobile-source-control-list-styles.ts | 17 -- mobile/src/worktree/agent-row-display.ts | 17 +- 23 files changed, 1417 insertions(+), 765 deletions(-) create mode 100644 mobile/src/agents/agent-list-rows.ts create mode 100644 mobile/src/agents/use-agent-activity-writes.ts create mode 100644 mobile/src/components/SwipeRowActions.tsx create mode 100644 mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx diff --git a/mobile/src/agents/MobileAgentListRows.tsx b/mobile/src/agents/MobileAgentListRows.tsx index 5a5e84fbe17..0f5f5b7908b 100644 --- a/mobile/src/agents/MobileAgentListRows.tsx +++ b/mobile/src/agents/MobileAgentListRows.tsx @@ -1,10 +1,11 @@ -import { ChevronDown, ChevronRight } from 'lucide-react-native' +import { Bell, ChevronDown, ChevronRight, Eye, EyeOff, X } from 'lucide-react-native' import { Fragment, memo, useCallback, useState } from 'react' import { Alert, Pressable, Text, View } from 'react-native' import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' import type { WorktreeStatus } from '../../../src/shared/worktree-status-rollup' import { AgentSpinner, agentStatusColors } from '../components/AgentSpinner' import { MobileAgentIcon } from '../components/MobileAgentIcon' +import { SwipeRowActions } from '../components/SwipeRowActions' import { HOME_ROW_TEXT_INSET, homeListStyles } from '../home/home-list-styles' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { triggerMediumImpact } from '../platform/haptics' @@ -16,8 +17,9 @@ import { useHostDisplay } from '../transport/hosts/use-host-display' import { agentStateLabel, formatTimeAgo, type AgentDotState } from '../worktree/agent-row-display' import { isDisclosureOpen, toggleDisclosure } from '../worktree/agent-child-disclosure' import { areStructurallyEqual } from '../worktree/structural-equality' -import { agentStatusGroup, type AgentListRow, type AgentListSection } from './agent-list-model' -import { agentListPreview, agentListTitle } from './agent-list-row-text' +import type { AgentListSection } from './agent-list-model' +import { agentStatusGroup, type AgentListRow } from './agent-list-rows' +import { agentListPreview } from './agent-list-row-text' // The Home rollup glyph is the list's size; this maps a per-agent state onto its palette. const GLYPH_STATUS: Record = { @@ -25,6 +27,7 @@ const GLYPH_STATUS: Record = { monitoring: 'monitoring', blocked: 'permission', waiting: 'permission', + permission: 'permission', failed: 'failed', done: 'done', interrupted: 'interrupted', @@ -43,21 +46,22 @@ type ShownRow = { row: AgentListRow; key: string; workersOpen?: boolean } export type AgentListRowHandlers = Readonly<{ onOpen: (row: AgentListRow) => void onLongPress: (row: AgentListRow) => void + onSetRead: (rows: readonly AgentListRow[], read: boolean) => void + onClear: (rows: readonly AgentListRow[]) => void }> /** One inset group of agent rows, with each coordinator's workers and an optional idle fold. */ -export function MobileAgentListRows( - props: AgentListRowHandlers & { - rows: readonly AgentListRow[] - idleRows?: readonly AgentListRow[] - footer: AgentListSection['footer'] - nameDesktop: boolean - hosts: readonly HostProfile[] - now: number - /** Remembers the idle fold per list. */ - idleKey?: string - } -) { +export function MobileAgentListRows(props: { + handlers: AgentListRowHandlers + rows: readonly AgentListRow[] + idleRows?: readonly AgentListRow[] + footer: AgentListSection['footer'] + nameDesktop: boolean + hosts: readonly HostProfile[] + now: number + /** Remembers the idle fold per list. */ + idleKey?: string +}) { const t = useMobileTranslation() useMobileColorScheme() // Disclosures live in a module cache so they survive remounts; this only redraws after a toggle. @@ -98,8 +102,7 @@ export function MobileAgentListRows( now={props.now} workersOpen={item.workersOpen} onToggleWorkers={toggle} - onOpen={props.onOpen} - onLongPress={props.onLongPress} + handlers={props.handlers} /> )) @@ -132,26 +135,25 @@ export function MobileAgentListRows( } // Each refresh rebuilds every row; compare by value so only changed rows redraw. -const MobileAgentListRow = memo(function MobileAgentListRow( - props: AgentListRowHandlers & { - row: AgentListRow - host: HostProfile | null - footer: AgentListSection['footer'] - nameDesktop: boolean - now: number - /** Undefined when the row has no workers to show. */ - workersOpen?: boolean - onToggleWorkers: (key: string) => void - } -) { +const MobileAgentListRow = memo(function MobileAgentListRow(props: { + handlers: AgentListRowHandlers + row: AgentListRow + host: HostProfile | null + footer: AgentListSection['footer'] + nameDesktop: boolean + now: number + /** Undefined when the row has no workers to show. */ + workersOpen?: boolean + onToggleWorkers: (key: string) => void +}) { const t = useMobileTranslation() useMobileColorScheme() const { row } = props const { agent } = row.entry const desktop = useHostDisplay(props.host).title - const title = agentListTitle(agent) + const { title } = row const group = row.stale ? null : agentStatusGroup(row.dotState) - const preview = agentListPreview(agent, group) + const preview = agentListPreview(agent, group, title) const needsYou = group === 'needs-you' const stateWord = needsYou ? agentStateLabel(row.dotState) : '' const place = [ @@ -162,9 +164,23 @@ const MobileAgentListRow = memo(function MobileAgentListRow( .join(' · ') const time = row.timeAt > 0 ? formatTimeAgo(row.timeAt, props.now) : '' const workerCount = row.workers.length + const workersLabel = + workerCount === 1 + ? t('agents.list.workers_one', '{{count}} worker', { count: workerCount }) + : t('agents.list.workers_other', '{{count}} workers', { count: workerCount }) + // The row is one accessibility element, so screen readers reach the workers toggle through it. + const workersAction = + props.workersOpen === undefined + ? null + : { + name: 'toggleWorkers', + label: props.workersOpen + ? t('agents.list.hideWorkers', 'Hide {{workers}}', { workers: workersLabel }) + : t('agents.list.showWorkers', 'Show {{workers}}', { workers: workersLabel }) + } const longPress = () => { triggerMediumImpact() - props.onLongPress(row) + props.handlers.onLongPress(row) } const open = () => { if (row.offline) { @@ -174,95 +190,149 @@ const MobileAgentListRow = memo(function MobileAgentListRow( ) return } - props.onOpen(row) + props.handlers.onOpen(row) } const actionsLabel = t('agents.list.actions', 'Actions for {{title}}', { title }) + const unread = row.unread === true return ( - { - if (event.nativeEvent.actionName === 'longpress') { - longPress() - } - }} - style={({ pressed }) => [ - homeListStyles.row, - row.depth > 0 && { paddingLeft: spacing.lg + row.depth * WORKER_INDENT }, - pressed && homeListStyles.rowPressed - ]} - onPress={open} - onLongPress={longPress} - delayLongPress={400} + props.handlers.onSetRead([row], unread) + } + } + trailing={ + row.clearable && !row.offline + ? { + label: t('agents.swipe.clear', 'Clear'), + accessibilityLabel: t('agents.actions.clear', 'Clear from list'), + icon: X, + background: colors.textMuted, + foreground: colors.onAccent, + onPress: () => props.handlers.onClear([row]) + } + : undefined + } > - - - - - - - {title} - - {time ? {time} : null} - - {stateWord || preview ? ( - - {stateWord ? ( - - {stateWord} + {(guardPress) => ( + { + if (event.nativeEvent.actionName === 'longpress') { + longPress() + } else if (event.nativeEvent.actionName === 'toggleWorkers') { + props.onToggleWorkers(workersKey(row)) + } + }} + style={({ pressed }) => [ + homeListStyles.row, + styles.row, + row.depth > 0 && { paddingLeft: spacing.lg + row.depth * WORKER_INDENT }, + pressed && homeListStyles.rowPressed + ]} + onPress={guardPress(open)} + onLongPress={longPress} + delayLongPress={400} + > + + + + + + + {title} + + {time ? {time} : null} + + {stateWord || preview ? ( + + {stateWord ? ( + + {stateWord} + + ) : null} + {stateWord && preview ? ' · ' : ''} + {preview} ) : null} - {stateWord && preview ? ' · ' : ''} - {preview} - - ) : null} - - {agent.agentType ? : null} - - {place} - - {props.workersOpen !== undefined ? ( - { - event.stopPropagation() - props.onToggleWorkers(workersKey(row)) - }} - > - {props.workersOpen ? ( - - ) : ( - - )} - - {workerCount === 1 - ? t('agents.list.workers_one', '{{count}} worker', { count: workerCount }) - : t('agents.list.workers_other', '{{count}} workers', { count: workerCount })} + + {agent.agentType ? : null} + + {place} - - ) : null} - - - + + {unread ? ( + + ) : null} + {props.workersOpen !== undefined ? ( + { + event.stopPropagation() + guardPress(() => props.onToggleWorkers(workersKey(row)))() + }} + > + {props.workersOpen ? ( + + ) : ( + + )} + {workersLabel} + + ) : null} + + + + + )} + ) }, areStructurallyEqual) const styles = themedStyleSheet(() => ({ text: { flex: 1, minWidth: 0, paddingTop: 9, paddingBottom: 10, paddingRight: 14, gap: 3 }, titleLine: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm }, + // Opaque so a swipe's actions stay hidden until the row slides off them. + row: { backgroundColor: colors.bgPanel }, title: { flex: 1, minWidth: 0, fontSize: 15, lineHeight: 20, color: colors.textPrimary }, + titleUnread: { fontWeight: '600' }, time: { fontSize: 12, color: colors.textMuted, fontVariant: ['tabular-nums'] }, preview: { fontSize: 14, lineHeight: 19, color: colors.textSecondary }, stateWord: { fontWeight: '600' }, footer: { flexDirection: 'row', alignItems: 'center', gap: 6, minWidth: 0 }, place: { flexShrink: 1, fontSize: 12, color: colors.textMuted }, - workers: { flexDirection: 'row', alignItems: 'center', gap: 4, marginLeft: 'auto' }, + trailing: { flexDirection: 'row', alignItems: 'center', gap: 8, marginLeft: 'auto' }, + workers: { flexDirection: 'row', alignItems: 'center', gap: 4 }, workersLabel: { fontSize: 12, fontWeight: '500', color: colors.textSecondary }, foldRow: { flexDirection: 'row', diff --git a/mobile/src/agents/agent-list-model.test.ts b/mobile/src/agents/agent-list-model.test.ts index 4bbb12b74e6..0001a6684d0 100644 --- a/mobile/src/agents/agent-list-model.test.ts +++ b/mobile/src/agents/agent-list-model.test.ts @@ -2,13 +2,13 @@ import { describe, expect, it } from 'vitest' import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' import type { ConnectionState } from '../transport/connection/connection-state' import type { HostWorktreeInfo } from '../worktree/home-worktree-info' +import { buildAgentList, type AgentListSection } from './agent-list-model' import { - buildAgentList, selectAgentsNeedingYou, type AgentListInput, type AgentListRow, - type AgentListSection -} from './agent-list-model' + type ListedAgentVerdict +} from './agent-list-rows' const NOW = 1_800_000_000_000 const MINUTE = 60_000 @@ -71,8 +71,8 @@ const shape = (sections: AgentListSection[]) => workers: section.rows.map((row) => panes(row.workers)), idle: panes(section.idleRows) })) -const statusView = (showWorkers: boolean) => ({ - view: { groupBy: 'status' as const, showWorkers }, +const statusView = (showWorkers: boolean, unreadOnly = false) => ({ + view: { groupBy: 'status' as const, showWorkers, unreadOnly }, hostFilter: null, query: '' }) @@ -166,4 +166,122 @@ describe('buildAgentList by status', () => { offline: false }) }) + + it('lists, orders and marks agents by the desktop Agents list’s verdicts', () => { + // Every raw state says working: only the verdicts decide. + const listed = (paneKey: string, verdict: Partial) => + agent(paneKey, 'working', { + activity: { + listed: true, + status: 'done', + unread: false, + clearable: false, + sortAt: NOW - MINUTE, + title: `Task ${paneKey}`, + ...verdict + } + }) + const host = (pendingActivity?: AgentListInput['pendingActivity']) => ({ + ...input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('session-start', 'working', { activity: { listed: false } }), + listed('failed', { status: 'failed', clearable: true, sortAt: NOW - MINUTE }), + listed('asking', { status: 'permission', unread: true, sortAt: NOW - 5 * MINUTE }), + listed('unconfirmed', { status: 'unconfirmed', clearable: true }), + listed('finished', { status: 'done', unread: true, clearable: true }), + listed('quiet', { status: 'unverifiable' }), + listed('stopped', { status: 'interrupted', clearable: true }) + ]) + } + } + }), + pendingActivity + }) + const rows = (list: ReturnType) => + list.sections.map((section) => [ + section.kind, + section.rows.map((row) => [row.entry.agent.paneKey, row.unread, row.clearable]) + ]) + expect(rows(buildAgentList(host(), statusView(true)))).toEqual([ + [ + 'needs-you', + [ + ['asking', true, false], + ['failed', false, true], + ['unconfirmed', false, true] + ] + ], + [ + 'done', + [ + ['stopped', false, true], + ['quiet', false, false], + ['finished', true, true] + ] + ] + ]) + expect(buildAgentList(host(), statusView(true)).sections[0].rows[0]).toMatchObject({ + title: 'Task asking', + dotState: 'permission' + }) + expect(panes(selectAgentsNeedingYou(host()))).toEqual(['asking', 'failed', 'unconfirmed']) + // Unread only is the desktop's unread alone, needs-you rows included. + expect(rows(buildAgentList(host(), statusView(true, true)))).toEqual([ + ['needs-you', [['asking', true, false]]], + ['done', [['finished', true, true]]] + ]) + // A write in flight shows until the desktop's next list read carries it. + const pending = host({ 'mac:failed': { unread: true }, 'mac:finished': { cleared: true } }) + expect(rows(buildAgentList(pending, statusView(true, true)))).toEqual([ + [ + 'needs-you', + [ + ['asking', true, false], + ['failed', true, true] + ] + ] + ]) + }) + + it('nests workers where the desktop does and hides the ones it folds', () => { + const verdict = (status: ListedAgentVerdict['status'], extra: Partial) => ({ + listed: true as const, + status, + unread: false, + clearable: false, + sortAt: NOW - MINUTE, + title: 'Task', + ...extra + }) + const host = input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('coordinator', 'working', { activity: verdict('working', {}) }), + agent('worker-done', 'done', { + activity: verdict('done', { childOf: 'coordinator', foldedChild: true }) + }), + agent('worker-busy', 'working', { + activity: verdict('working', { childOf: 'coordinator', sortAt: NOW }) + }) + ]) + } + } + }) + expect(shape(buildAgentList(host, statusView(true)).sections)).toEqual([ + { + kind: 'working', + rows: ['coordinator'], + workers: [['worker-done', 'worker-busy']], + idle: undefined + } + ]) + expect(shape(buildAgentList(host, statusView(false)).sections)).toEqual([ + { kind: 'working', rows: ['worker-busy', 'coordinator'], workers: [[], []], idle: undefined } + ]) + }) }) diff --git a/mobile/src/agents/agent-list-model.ts b/mobile/src/agents/agent-list-model.ts index 7b99eead86c..3ee9d124589 100644 --- a/mobile/src/agents/agent-list-model.ts +++ b/mobile/src/agents/agent-list-model.ts @@ -1,10 +1,19 @@ import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' -import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import type { ConnectionState } from '../transport/connection/connection-state' -import { agentDotState, agentRowTimeAt, type AgentDotState } from '../worktree/agent-row-display' -import { flattenAgentRowLineage, type AgentRowNode } from '../worktree/agent-row-lineage' -import type { HomeAgentEntry, HostWorktreeInfo } from '../worktree/home-worktree-info' import { agentListEntryMatches } from './agent-list-row-text' +import { + agentStatusGroup, + asTopLevel, + byStatusThenRecent, + everyRow, + hostAgents, + listedAgentVerdict, + newestFirst, + rowNeedsYou, + type AgentListInput, + type AgentListRow, + type AgentStatusGroup, + type HostAgents +} from './agent-list-rows' export const AGENT_LIST_GROUP_BY_CHOICES = [ 'status', @@ -16,46 +25,18 @@ export const AGENT_LIST_GROUP_BY_CHOICES = [ export type AgentListGroupBy = (typeof AGENT_LIST_GROUP_BY_CHOICES)[number] -export type AgentListView = Readonly<{ groupBy: AgentListGroupBy; showWorkers: boolean }> - -export const DEFAULT_AGENT_LIST_VIEW: AgentListView = { groupBy: 'status', showWorkers: true } - -export type AgentStatusGroup = 'needs-you' | 'working' | 'done' | 'idle' - -export function agentStatusGroup(state: AgentDotState): AgentStatusGroup { - switch (state) { - case 'blocked': - case 'waiting': - case 'failed': - return 'needs-you' - case 'working': - case 'monitoring': - return 'working' - case 'done': - case 'interrupted': - case 'unconfirmed': - return 'done' - case 'idle': - case 'unverifiable': - return 'idle' - } -} - -export type AgentListRow = Readonly<{ - key: string - hostId: string - entry: HomeAgentEntry - dotState: AgentDotState - timeAt: number - /** A copy from a read the desktop no longer backs: it claims no state. */ - stale: boolean - /** Its desktop isn't connected, so the row can't open. */ - offline: boolean - depth: number - /** Nested workers in tree order; empty when workers are hidden. */ - workers: readonly AgentListRow[] +export type AgentListView = Readonly<{ + groupBy: AgentListGroupBy + showWorkers: boolean + unreadOnly: boolean }> +export const DEFAULT_AGENT_LIST_VIEW: AgentListView = { + groupBy: 'status', + showWorkers: true, + unreadOnly: false +} + export type AgentListSectionKind = AgentStatusGroup | 'workspace' | 'project' | 'agent' | 'desktop' export type AgentListSection = Readonly<{ @@ -74,112 +55,6 @@ export type AgentListSection = Readonly<{ nameDesktop: boolean }> -export type AgentListInput = Readonly<{ - /** Paired desktops in Home's order. */ - hosts: readonly { id: string }[] - hostStates: Readonly> - worktreeInfo: Readonly> - now: number -}> - -type HostAgents = { - hostId: string - roots: AgentListRow[] - live: boolean - offline: boolean - seenAt?: number -} - -function hostAgents(input: AgentListInput, hostId: string): HostAgents { - const info = input.worktreeInfo[hostId] - const connected = input.hostStates[hostId] === 'connected' - // Only this connection's own read may show states; anything else is what the agents last were. - const liveAgents = connected && !info?.catalogUnavailable ? info?.agents : undefined - const live = liveAgents !== undefined - const entries = liveAgents ?? info?.lastSeenAgents ?? info?.agents ?? [] - const entryByAgent = new Map( - entries.map((entry) => [entry.agent, entry]) - ) - const toRow = (node: AgentRowNode, depth: number): AgentListRow | null => { - const entry = entryByAgent.get(node.row) - if (!entry) { - return null - } - return { - key: `${hostId}:${node.row.paneKey}`, - hostId, - entry, - dotState: live ? agentDotState(node.row, input.now) : 'idle', - timeAt: agentRowTimeAt(node.row), - stale: !live, - offline: !connected, - depth, - workers: node.children.flatMap((child) => descendants(child, depth + 1)) - } - } - const descendants = (node: AgentRowNode, depth: number): AgentListRow[] => { - const row = toRow(node, depth) - return row ? [{ ...row, workers: [] }, ...row.workers] : [] - } - // Lineage spans the desktop: a coordinator's workers often run in other workspaces. - const roots = flattenAgentRowLineage(entries.map((entry) => entry.agent)) - .filter((node) => node.depth === 0) - .map((node) => toRow(node, 0)) - .filter((row): row is AgentListRow => row !== null) - return { hostId, roots, live, offline: !connected, seenAt: info?.countsProvenAt } -} - -function everyRow(roots: readonly AgentListRow[]): AgentListRow[] { - return roots.flatMap((row) => [row, ...row.workers]) -} - -const asTopLevel = (row: AgentListRow): AgentListRow => ({ ...row, depth: 0, workers: [] }) - -const newestFirst = (a: AgentListRow, b: AgentListRow): number => b.timeAt - a.timeAt - -function needsYou(row: AgentListRow): boolean { - return !row.stale && agentStatusGroup(row.dotState) === 'needs-you' -} - -/** Live agents that need the user, workers included: Feed's rows and both badge counts. */ -export function selectAgentsNeedingYou(input: AgentListInput): AgentListRow[] { - return input.hosts - .flatMap((host) => everyRow(hostAgents(input, host.id).roots)) - .filter(needsYou) - .map(asTopLevel) - .sort(newestFirst) -} - -export function countAgentsNeedingYouByHost( - rows: readonly AgentListRow[] -): Readonly> { - const counts: Record = {} - for (const row of rows) { - counts[row.hostId] = (counts[row.hostId] ?? 0) + 1 - } - return counts -} - -export type AgentListHostSummary = Readonly<{ - hostId: string - agents: number - needsYou: number - offline: boolean -}> - -export function summarizeAgentListHosts(input: AgentListInput): AgentListHostSummary[] { - return input.hosts.map((host) => { - const agents = hostAgents(input, host.id) - const rows = everyRow(agents.roots) - return { - hostId: host.id, - agents: rows.length, - needsYou: rows.filter(needsYou).length, - offline: agents.offline - } - }) -} - type GroupDraft = { key: string; title?: string; hostId?: string; rows: AgentListRow[] } function groupRows( @@ -201,7 +76,7 @@ function groupRows( // Groups with something that needs the user lead, then the most recently active. function byUrgencyThenRecent(a: GroupDraft, b: GroupDraft): number { - const urgent = (group: GroupDraft) => (group.rows.some(needsYou) ? 0 : 1) + const urgent = (group: GroupDraft) => (group.rows.some(rowNeedsYou) ? 0 : 1) const latest = (group: GroupDraft) => Math.max(...group.rows.map((row) => row.timeAt)) return urgent(a) - urgent(b) || latest(b) - latest(a) } @@ -215,37 +90,57 @@ const STATUS_SECTIONS: readonly Exclude[] = [ export function buildAgentList( input: AgentListInput, options: Readonly<{ view: AgentListView; hostFilter: string | null; query: string }> -): { sections: AgentListSection[]; total: number } { +): { sections: AgentListSection[]; anyLive: boolean } { const { view } = options const hosts = input.hosts .filter((host) => options.hostFilter === null || host.id === options.hostFilter) .map((host) => hostAgents(input, host.id)) - const total = hosts.reduce((sum, host) => sum + everyRow(host.roots).length, 0) + // With no desktop read this session, an empty list says nothing about running agents. + const anyLive = hosts.some((host) => host.live) const nameDesktop = input.hosts.length > 1 && options.hostFilter === null const query = options.query.trim().toLowerCase() + // Unread is the desktop's verdict alone. Rows it gave none stay: hiding them would claim they + // were read. A coordinator stays for its unread worker. + const shown = (row: AgentListRow) => + !view.unreadOnly || + row.unread === true || + (row.unread === undefined && !listedAgentVerdict(row.entry.agent)) || + row.workers.some((worker) => worker.unread) const topLevel = (host: HostAgents): AgentListRow[] => { if (query) { // A match is shown on its own; its coordinator may not match. return everyRow(host.roots) .filter((row) => agentListEntryMatches(row.entry, query)) .map(asTopLevel) + .filter(shown) + } + if (!view.showWorkers) { + // Desktop hides a finished worker and lists a live one on its own; without its verdict, only + // a worker that needs the user shows. + return everyRow(host.roots) + .filter((row) => { + const verdict = listedAgentVerdict(row.entry.agent) + return verdict ? !verdict.foldedChild : row.depth === 0 || rowNeedsYou(row) + }) + .map(asTopLevel) + .filter(shown) } - const roots = view.showWorkers ? host.roots : host.roots.map(asTopLevel) // A worker that needs the user can't hide inside a folded coordinator. - const surfaced = host.roots.flatMap((root) => root.workers.filter(needsYou).map(asTopLevel)) - return [...roots, ...surfaced] + const surfaced = host.roots.flatMap((root) => root.workers.filter(rowNeedsYou).map(asTopLevel)) + return [...host.roots, ...surfaced].filter(shown) } const section = ( draft: GroupDraft, kind: AgentListSectionKind, footer: AgentListSection['footer'], - names: boolean + names: boolean, + order = newestFirst ): AgentListSection => ({ ...draft, kind, - rows: [...draft.rows].sort(newestFirst), + rows: [...draft.rows].sort(order), footer, nameDesktop: names }) @@ -269,7 +164,7 @@ export function buildAgentList( } ] }) - return { sections, total } + return { sections, anyLive } } if (view.groupBy === 'status') { @@ -279,7 +174,8 @@ export function buildAgentList( { key: kind, rows: live.filter((row) => agentStatusGroup(row.dotState) === kind) }, kind, 'workspace', - nameDesktop + nameDesktop, + byStatusThenRecent ) ).filter((entry) => entry.rows.length > 0) const idleRows = live.filter((row) => agentStatusGroup(row.dotState) === 'idle') @@ -310,7 +206,7 @@ export function buildAgentList( }) } } - return { sections, total } + return { sections, anyLive } } const rows = hosts.flatMap(topLevel) @@ -339,5 +235,16 @@ export function buildAgentList( ? section(draft, kind, 'workspace', nameDesktop) : section(draft, kind, kind === 'workspace' ? 'agent' : 'workspace', false) ) - return { sections, total } + return { sections, anyLive } +} + +/** Every row the list holds, folded ones included, once each: what "Mark all read" and "Clear finished" act on. */ +export function agentListRowsIn(sections: readonly AgentListSection[]): AgentListRow[] { + const rows = new Map() + for (const section of sections) { + for (const row of everyRow([...section.rows, ...(section.idleRows ?? [])])) { + rows.set(row.key, row) + } + } + return [...rows.values()] } diff --git a/mobile/src/agents/agent-list-preferences.ts b/mobile/src/agents/agent-list-preferences.ts index 30da78f1ba7..c3e0aaf5729 100644 --- a/mobile/src/agents/agent-list-preferences.ts +++ b/mobile/src/agents/agent-list-preferences.ts @@ -16,12 +16,14 @@ export async function loadAgentListView(): Promise { } const groupBy = 'groupBy' in parsed ? parsed.groupBy : undefined const showWorkers = 'showWorkers' in parsed ? parsed.showWorkers : undefined + const unreadOnly = 'unreadOnly' in parsed ? parsed.unreadOnly : undefined return { groupBy: AGENT_LIST_GROUP_BY_CHOICES.find((choice) => choice === groupBy) ?? DEFAULT_AGENT_LIST_VIEW.groupBy, showWorkers: - typeof showWorkers === 'boolean' ? showWorkers : DEFAULT_AGENT_LIST_VIEW.showWorkers + typeof showWorkers === 'boolean' ? showWorkers : DEFAULT_AGENT_LIST_VIEW.showWorkers, + unreadOnly: typeof unreadOnly === 'boolean' ? unreadOnly : DEFAULT_AGENT_LIST_VIEW.unreadOnly } } catch { return DEFAULT_AGENT_LIST_VIEW diff --git a/mobile/src/agents/agent-list-row-text.ts b/mobile/src/agents/agent-list-row-text.ts index 81ff91a29dc..c3e9d8ef8b7 100644 --- a/mobile/src/agents/agent-list-row-text.ts +++ b/mobile/src/agents/agent-list-row-text.ts @@ -4,7 +4,7 @@ import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentat import { withoutNativeChatVisualDirectiveLines } from '../../../src/shared/native-chat/native-chat-visual-directive' import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' import type { HomeAgentEntry } from '../worktree/home-worktree-info' -import type { AgentStatusGroup } from './agent-list-model' +import type { AgentStatusGroup } from './agent-list-rows' /** The row's name: what the conversation is called, else its task, else what it was asked. */ export function agentListTitle(agent: RuntimeWorktreeAgentRow): string { @@ -32,7 +32,8 @@ function lastMessage(agent: RuntimeWorktreeAgentRow): string { */ export function agentListPreview( agent: RuntimeWorktreeAgentRow, - group: AgentStatusGroup | null + group: AgentStatusGroup | null, + title: string ): string { const tool = group === null ? '' : oneLine(formatAgentToolPreviewLine(agent, false)) const preview = @@ -43,7 +44,7 @@ export function agentListPreview( return preview } const prompt = oneLine(getAgentRowPrimaryText({ prompt: agent.prompt })) - return prompt === agentListTitle(agent) ? '' : prompt + return prompt === title ? '' : prompt } /** Search covers what the row shows plus the prompt; `query` is already lower-cased. */ @@ -51,6 +52,7 @@ export function agentListEntryMatches(entry: HomeAgentEntry, query: string): boo const { agent } = entry return [ agentListTitle(agent), + agent.activity?.listed === true ? agent.activity.title : null, entry.workspaceName, entry.branch, entry.repo, diff --git a/mobile/src/agents/agent-list-rows.ts b/mobile/src/agents/agent-list-rows.ts new file mode 100644 index 00000000000..a9490a5929b --- /dev/null +++ b/mobile/src/agents/agent-list-rows.ts @@ -0,0 +1,190 @@ +import { + AGENT_LIST_STATUS_RANK, + type AgentListVerdict +} from '../../../src/shared/agent-status/presentation/agent-list-status' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { ConnectionState } from '../transport/connection/connection-state' +import { agentDotState, agentRowTimeAt, type AgentDotState } from '../worktree/agent-row-display' +import { flattenAgentRowLineage, type AgentRowNode } from '../worktree/agent-row-lineage' +import type { HomeAgentEntry, HostWorktreeInfo } from '../worktree/home-worktree-info' +import { agentListTitle } from './agent-list-row-text' + +export type AgentStatusGroup = 'needs-you' | 'working' | 'done' | 'idle' + +/** Desktop's status ranks cut into sections: everything ranked above live work needs the user. */ +export function agentStatusGroup(state: AgentDotState): AgentStatusGroup { + const rank = AGENT_LIST_STATUS_RANK[state] + if (rank < AGENT_LIST_STATUS_RANK.working) { + return 'needs-you' + } + if (rank <= AGENT_LIST_STATUS_RANK.monitoring) { + return 'working' + } + return state === 'idle' ? 'idle' : 'done' +} + +export type ListedAgentVerdict = Extract + +/** The desktop Agents list's row for this agent; undefined when the host sent no verdict. */ +export function listedAgentVerdict(agent: RuntimeWorktreeAgentRow): ListedAgentVerdict | undefined { + return agent.activity?.listed === true ? agent.activity : undefined +} + +export type AgentListRow = Readonly<{ + key: string + hostId: string + entry: HomeAgentEntry + title: string + dotState: AgentDotState + timeAt: number + /** A copy from a read the desktop no longer backs: it claims no state. */ + stale: boolean + /** Its desktop isn't connected, so the row can't open. */ + offline: boolean + /** The desktop's read verdict; undefined when it gave none, so the phone claims nothing. */ + unread?: boolean + /** A finished turn the desktop can clear from its Agents list. */ + clearable: boolean + depth: number + /** Nested workers in tree order; empty when workers are hidden. */ + workers: readonly AgentListRow[] +}> + +export type AgentListInput = Readonly<{ + /** Paired desktops in Home's order. */ + hosts: readonly { id: string }[] + hostStates: Readonly> + worktreeInfo: Readonly> + now: number + /** Writes sent but not yet read back, by row key. */ + pendingActivity?: Readonly> +}> + +/** A read or clear the phone asked its desktop for. */ +export type AgentActivityChange = Readonly<{ unread: boolean } | { cleared: true }> + +export function agentListRowKey(hostId: string, paneKey: string): string { + return `${hostId}:${paneKey}` +} + +export type HostAgents = { + hostId: string + roots: AgentListRow[] + live: boolean + offline: boolean + seenAt?: number +} + +export function hostAgents(input: AgentListInput, hostId: string): HostAgents { + const info = input.worktreeInfo[hostId] + const connected = input.hostStates[hostId] === 'connected' + // Only this connection's own read may show states; anything else is what the agents last were. + const liveAgents = connected && !info?.catalogUnavailable ? info?.agents : undefined + const live = liveAgents !== undefined + const pending = (paneKey: string) => input.pendingActivity?.[agentListRowKey(hostId, paneKey)] + // Only what the desktop lists, less what the phone just cleared; a cleared agent's workers stay, as roots. + const entries = (liveAgents ?? info?.lastSeenAgents ?? info?.agents ?? []).filter((entry) => { + const change = pending(entry.agent.paneKey) + return entry.agent.activity?.listed !== false && !(change && 'cleared' in change) + }) + const entryByPaneKey = new Map(entries.map((entry) => [entry.agent.paneKey, entry])) + const toRow = (node: AgentRowNode, depth: number): AgentListRow | null => { + const entry = entryByPaneKey.get(node.row.paneKey) + if (!entry) { + return null + } + const { agent } = entry + const verdict = listedAgentVerdict(agent) + const liveVerdict = live ? verdict : undefined + const change = pending(agent.paneKey) + return { + key: agentListRowKey(hostId, agent.paneKey), + hostId, + entry, + title: verdict?.title.trim() || agentListTitle(agent), + dotState: !live ? 'idle' : verdict ? verdict.status : agentDotState(agent, input.now), + timeAt: verdict?.sortAt ?? agentRowTimeAt(agent), + stale: !live, + offline: !connected, + // Read state is the desktop's call; a host that sends none gets no bell and no actions. + unread: liveVerdict + ? change && 'unread' in change + ? change.unread + : liveVerdict.unread + : undefined, + clearable: liveVerdict?.clearable === true, + depth, + workers: node.children.flatMap((child) => descendants(child, depth + 1)) + } + } + const descendants = (node: AgentRowNode, depth: number): AgentListRow[] => { + const row = toRow(node, depth) + return row ? [{ ...row, workers: [] }, ...row.workers] : [] + } + // Lineage spans the desktop: a coordinator's workers often run in other workspaces. Desktop's + // own nesting wins where it gave a verdict. + const lineage = entries.map(({ agent }) => { + const verdict = listedAgentVerdict(agent) + return verdict ? { ...agent, parentPaneKey: verdict.childOf ?? null } : agent + }) + const roots = flattenAgentRowLineage(lineage) + .filter((node) => node.depth === 0) + .map((node) => toRow(node, 0)) + .filter((row): row is AgentListRow => row !== null) + return { hostId, roots, live, offline: !connected, seenAt: info?.countsProvenAt } +} + +export function everyRow(roots: readonly AgentListRow[]): AgentListRow[] { + return roots.flatMap((row) => [row, ...row.workers]) +} + +export const asTopLevel = (row: AgentListRow): AgentListRow => ({ ...row, depth: 0, workers: [] }) + +export const newestFirst = (a: AgentListRow, b: AgentListRow): number => b.timeAt - a.timeAt + +/** Desktop's status order, newest first within a status. */ +export const byStatusThenRecent = (a: AgentListRow, b: AgentListRow): number => + AGENT_LIST_STATUS_RANK[a.dotState] - AGENT_LIST_STATUS_RANK[b.dotState] || newestFirst(a, b) + +export function rowNeedsYou(row: AgentListRow): boolean { + return !row.stale && agentStatusGroup(row.dotState) === 'needs-you' +} + +/** Live agents that need the user, workers included: Feed's rows and both badge counts. */ +export function selectAgentsNeedingYou(input: AgentListInput): AgentListRow[] { + return input.hosts + .flatMap((host) => everyRow(hostAgents(input, host.id).roots)) + .filter(rowNeedsYou) + .map(asTopLevel) + .sort(byStatusThenRecent) +} + +export function countAgentsNeedingYouByHost( + rows: readonly AgentListRow[] +): Readonly> { + const counts: Record = {} + for (const row of rows) { + counts[row.hostId] = (counts[row.hostId] ?? 0) + 1 + } + return counts +} + +export type AgentListHostSummary = Readonly<{ + hostId: string + agents: number + needsYou: number + offline: boolean +}> + +export function summarizeAgentListHosts(input: AgentListInput): AgentListHostSummary[] { + return input.hosts.map((host) => { + const agents = hostAgents(input, host.id) + const rows = everyRow(agents.roots) + return { + hostId: host.id, + agents: rows.length, + needsYou: rows.filter(rowNeedsYou).length, + offline: agents.offline + } + }) +} diff --git a/mobile/src/agents/use-agent-activity-writes.ts b/mobile/src/agents/use-agent-activity-writes.ts new file mode 100644 index 00000000000..2adc52d6718 --- /dev/null +++ b/mobile/src/agents/use-agent-activity-writes.ts @@ -0,0 +1,133 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { z } from 'zod' +import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' +import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { AgentActivityChange, AgentListRow } from './agent-list-rows' + +// The host's bound on one request's pane keys. +const PANE_KEYS_PER_REQUEST = 500 +const applied = rpcResultVariant('applied', z.object({ applied: z.literal(true) })) + +const agentActivitySetReadWrite = bindDeferredRpcOperation( + defineRpcOperation({ + name: 'agentActivity.mobile-set-read', + method: 'agentActivity.setRead', + acceptance: 'require-result-or-throw', + barrier: 'after-caller-barrier', + read: applied + }) +) +const agentActivityClearWrite = bindDeferredRpcOperation( + defineRpcOperation({ + name: 'agentActivity.mobile-clear', + method: 'agentActivity.clear', + acceptance: 'require-result-or-throw', + barrier: 'after-caller-barrier', + read: applied + }) +) + +export type AgentActivityFailure = Readonly<{ hostId: string; needsDesktopWindow: boolean }> + +async function sendAgentActivity( + client: RpcClient, + paneKeys: string[], + change: AgentActivityChange +): Promise { + for (let start = 0; start < paneKeys.length; start += PANE_KEYS_PER_REQUEST) { + const chunk = paneKeys.slice(start, start + PANE_KEYS_PER_REQUEST) + if ('cleared' in change) { + agentActivityClearWrite.interpret( + await agentActivityClearWrite.request(client, { paneKeys: chunk }) + ) + } else { + agentActivitySetReadWrite.interpret( + await agentActivitySetReadWrite.request(client, { paneKeys: chunk, read: !change.unread }) + ) + } + } +} + +/** + * Sends read and clear changes to each row's desktop, showing them until that desktop's next + * list read carries them; a refused write rolls back to the desktop's list and reports which + * desktop refused. + */ +export function useAgentActivityWrites( + clients: readonly { hostId: string; client: RpcClient }[], + refetchHost: (hostId: string) => Promise +) { + const [pending, setPending] = useState< + Readonly> + >({}) + const tokenRef = useRef(0) + const clientsRef = useRef(clients) + useEffect(() => { + clientsRef.current = clients + }, [clients]) + + const apply = useCallback( + async ( + rows: readonly AgentListRow[], + change: AgentActivityChange + ): Promise => { + tokenRef.current += 1 + const token = tokenRef.current + const paneKeysByHost = new Map() + for (const row of rows) { + paneKeysByHost.set(row.hostId, [ + ...(paneKeysByHost.get(row.hostId) ?? []), + row.entry.agent.paneKey + ]) + } + setPending((previous) => ({ + ...previous, + ...Object.fromEntries(rows.map((row) => [row.key, { change, token }])) + })) + const settle = (hostId: string) => + setPending((previous) => + Object.fromEntries( + Object.entries(previous).filter( + ([key, entry]) => entry.token !== token || !key.startsWith(`${hostId}:`) + ) + ) + ) + const outcomes = await Promise.all( + [...paneKeysByHost].map( + async ([hostId, paneKeys]): Promise => { + try { + const client = clientsRef.current.find((entry) => entry.hostId === hostId)?.client + if (!client) { + throw new Error('desktop not connected') + } + await sendAgentActivity(client, paneKeys, change) + // The host's next list already carries the change; hold the guess until it lands. + await refetchHost(hostId) + return null + } catch (error) { + // A timeout or a partial batch may still have applied; roll back to what the desktop has. + await refetchHost(hostId) + return { + hostId, + needsDesktopWindow: + error instanceof Error && + error.message.includes('agent_activity_needs_desktop_window') + } + } finally { + settle(hostId) + } + } + ) + ) + return outcomes.filter((outcome): outcome is AgentActivityFailure => outcome !== null) + }, + [refetchHost] + ) + + const pendingActivity = useMemo( + () => Object.fromEntries(Object.entries(pending).map(([key, entry]) => [key, entry.change])), + [pending] + ) + return { pendingActivity, apply } +} diff --git a/mobile/src/agents/use-agent-list-row-actions.tsx b/mobile/src/agents/use-agent-list-row-actions.tsx index a86ee0c2b56..dcd191a4b6c 100644 --- a/mobile/src/agents/use-agent-list-row-actions.tsx +++ b/mobile/src/agents/use-agent-list-row-actions.tsx @@ -1,17 +1,28 @@ -import { ArrowUpRight, Copy, Folder } from 'lucide-react-native' +import { ArrowUpRight, Copy, Eye, EyeOff, Folder, X } from 'lucide-react-native' import { useCallback, useMemo, useState } from 'react' import { Alert } from 'react-native' -import { ActionSheetModal } from '../components/ActionSheetModal' +import { ActionSheetModal, type ActionSheetAction } from '../components/ActionSheetModal' import { TransientToast, useTransientToast } from '../components/TransientToast' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { useClipboardWriter } from '../platform/clipboard' import { useOpenMobileSession } from '../session/use-open-mobile-session' -import type { AgentListRow } from './agent-list-model' -import { agentListTitle } from './agent-list-row-text' +import type { HostProfile } from '../transport/hosts/host-profile' +import type { AgentActivityChange, AgentListRow } from './agent-list-rows' import type { AgentListRowHandlers } from './MobileAgentListRows' +import type { AgentActivityFailure } from './use-agent-activity-writes' -/** Tap opens the agent's tab; long-press offers it, its workspace and its title. Shared by Feed and Agents. */ -export function useAgentListRowActions(toastBottomInset: number) { +/** + * Tap opens the agent's tab and marks it read; long-press offers it, its workspace, its title and + * the desktop's read and clear. Shared by Feed and Agents. + */ +export function useAgentListRowActions( + toastBottomInset: number, + hosts: readonly HostProfile[], + applyActivity: ( + rows: readonly AgentListRow[], + change: AgentActivityChange + ) => Promise +) { const t = useMobileTranslation() const openMobileSession = useOpenMobileSession() const clipboard = useClipboardWriter() @@ -28,57 +39,118 @@ export function useAgentListRowActions(toastBottomInset: number) { }), [openMobileSession] ) + const change = useCallback( + (rows: readonly AgentListRow[], next: AgentActivityChange) => { + if (rows.length === 0) { + return + } + void applyActivity(rows, next).then((failures) => { + const failure = failures[0] + if (!failure) { + return + } + const desktop = hosts.find((host) => host.id === failure.hostId)?.name + showToast( + failure.needsDesktopWindow && desktop + ? t('agents.activity.needsWindow', 'Couldn’t update. Open Orca on {{desktop}}.', { + desktop + }) + : t('agents.activity.failed', 'Couldn’t update the agent list.') + ) + }) + }, + [applyActivity, hosts, showToast, t] + ) const handlers = useMemo( - () => ({ onOpen: (row) => open(row, true), onLongPress: setTarget }), - [open] + () => ({ + onOpen: (row) => { + // Like desktop opening a pane; a refusal here isn't worth interrupting the open. + if (row.unread) { + void applyActivity([row], { unread: false }) + } + open(row, true) + }, + onLongPress: setTarget, + // Only rows the desktop gave a verdict for; the phone never invents read state. + onSetRead: (rows, read) => + change( + rows.filter((row) => row.unread !== undefined), + { unread: !read } + ), + onClear: (rows) => + change( + rows.filter((row) => row.clearable), + { cleared: true } + ) + }), + [applyActivity, change, open] ) - const title = target ? agentListTitle(target.entry.agent) : undefined + const title = target?.title const offlineHint = target?.offline ? t('agents.actions.offlineHint', 'Its desktop is offline.') : undefined + const actions = (row: AgentListRow): ActionSheetAction[] => [ + { + id: 'open', + label: t('agents.actions.open', 'Open'), + icon: ArrowUpRight, + disabled: row.offline, + hint: offlineHint, + closeBeforePress: true, + onPress: () => handlers.onOpen(row) + }, + { + id: 'workspace', + label: t('agents.actions.goToWorkspace', 'Go to workspace'), + icon: Folder, + disabled: row.offline, + hint: offlineHint, + closeBeforePress: true, + onPress: () => open(row, false) + }, + ...(row.unread === undefined + ? [] + : [ + { + id: 'read', + label: row.unread + ? t('agents.actions.markRead', 'Mark as read') + : t('agents.actions.markUnread', 'Mark as unread'), + icon: row.unread ? Eye : EyeOff, + onPress: () => handlers.onSetRead([row], row.unread === true) + } + ]), + { + id: 'copy-title', + label: t('agents.actions.copyTitle', 'Copy title'), + icon: Copy, + closeBeforePress: true, + onPress: () => { + void clipboard.writeText(title ?? '').then( + () => showToast(t('agents.actions.copied', 'Copied')), + () => Alert.alert(t('agents.actions.copyFailed', 'Couldn’t copy the title')) + ) + } + }, + ...(row.clearable + ? [ + { + id: 'clear', + label: t('agents.actions.clear', 'Clear from list'), + icon: X, + onPress: () => handlers.onClear([row]) + } + ] + : []) + ] const sheet = ( <> open(target, true) - }, - { - id: 'workspace', - label: t('agents.actions.goToWorkspace', 'Go to workspace'), - icon: Folder, - disabled: target.offline, - hint: offlineHint, - closeBeforePress: true, - onPress: () => open(target, false) - }, - { - id: 'copy-title', - label: t('agents.actions.copyTitle', 'Copy title'), - icon: Copy, - closeBeforePress: true, - onPress: () => { - void clipboard.writeText(title ?? '').then( - () => showToast(t('agents.actions.copied', 'Copied')), - () => Alert.alert(t('agents.actions.copyFailed', 'Couldn’t copy the title')) - ) - } - } - ] - : [] - } + actions={target ? actions(target) : []} onClose={() => setTarget(null)} /> diff --git a/mobile/src/cache/worktree-cache.test.ts b/mobile/src/cache/worktree-cache.test.ts index fc47972a2a8..254efeee4ca 100644 --- a/mobile/src/cache/worktree-cache.test.ts +++ b/mobile/src/cache/worktree-cache.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { setCachedWorktrees, getCachedWorktrees, getProvenCachedWorktrees } from './worktree-cache' +import { setCachedWorktrees, getCachedWorktrees } from './worktree-cache' // Pin reconnect write-through to cache seeded by host detail (#8498), preventing stale reconnect snapshots. describe('worktree-cache write-through', () => { @@ -21,48 +21,23 @@ describe('worktree-cache write-through', () => { }) }) -// Only live worktree.ps can prove absence for Resume redirects; persisted cold-start seeds must never be authoritative (F7). +// A persisted cold-start seed must not truncate the rows a live worktree.ps listed. describe('worktree-cache provenance', () => { - it('withholds unmarked writes from the proven reader', () => { - const hostId = 'host-seeded' - const seeded = [{ worktreeId: 'a' }] - - setCachedWorktrees(hostId, seeded) - - expect(getCachedWorktrees(hostId)).toEqual(seeded) - expect(getProvenCachedWorktrees(hostId)).toBeNull() - }) - - it('exposes a host-listed catalog to the proven reader', () => { - const hostId = 'host-proven' - const listed = [{ worktreeId: 'a' }, { worktreeId: 'b' }] - - setCachedWorktrees(hostId, listed, { proven: true }) - - expect(getProvenCachedWorktrees(hostId)).toEqual(listed) - }) - - it('keeps a fresh proven catalog when an unproven seed lands after it', () => { + it('keeps a fresh host-listed catalog when a cold-start seed lands after it', () => { const hostId = 'host-kept' const listed = [{ worktreeId: 'a' }, { worktreeId: 'b' }] setCachedWorktrees(hostId, listed, { proven: true }) - // A cold-start snapshot seed must neither truncate nor de-prove the host-listed rows. setCachedWorktrees(hostId, [{ worktreeId: 'a' }]) - expect(getProvenCachedWorktrees(hostId)).toEqual(listed) + expect(getCachedWorktrees(hostId)).toEqual(listed) }) - it('lets an unproven seed replace another unproven entry', () => { + it('lets a seed replace another seed', () => { const hostId = 'host-reseeded' setCachedWorktrees(hostId, [{ worktreeId: 'a' }]) setCachedWorktrees(hostId, [{ worktreeId: 'b' }]) expect(getCachedWorktrees(hostId)).toEqual([{ worktreeId: 'b' }]) - expect(getProvenCachedWorktrees(hostId)).toBeNull() - }) - - it('reports nothing proven for a host it has never cached', () => { - expect(getProvenCachedWorktrees('host-never-seen')).toBeNull() }) }) diff --git a/mobile/src/cache/worktree-cache.ts b/mobile/src/cache/worktree-cache.ts index 2b7c8900782..ad05d45c98e 100644 --- a/mobile/src/cache/worktree-cache.ts +++ b/mobile/src/cache/worktree-cache.ts @@ -3,7 +3,7 @@ type CachedWorktrees = { worktrees: unknown[] at: number - // Only live host-listed rows can prove absence; persisted cold-start seeds cannot. + // Live host-listed rows; a persisted cold-start seed must not replace them. proven: boolean } @@ -17,13 +17,12 @@ export function setCachedWorktrees( worktrees: unknown[], options?: { proven?: boolean } ): void { - // Late cold-start seed must neither erase proof nor truncate live host-listed rows used by Resume. + // A late cold-start seed must not truncate live host-listed rows. if (options?.proven !== true && readFreshEntry(hostId)?.proven) { return } // Delete before Map.set to move key to newest position for LRU eviction. cache.delete(hostId) - // Default unproven: unknown row origin cannot justify redirecting user from workspace. cache.set(hostId, { worktrees, at: Date.now(), proven: options?.proven === true }) if (cache.size > MAX_ENTRIES) { const oldest = cache.keys().next().value @@ -37,12 +36,6 @@ export function getCachedWorktrees(hostId: string): unknown[] | null { return readFreshEntry(hostId)?.worktrees ?? null } -// Return live host-listed rows only; expired/unproven entries cannot establish absence. -export function getProvenCachedWorktrees(hostId: string): unknown[] | null { - const entry = readFreshEntry(hostId) - return entry?.proven ? entry.worktrees : null -} - function readFreshEntry(hostId: string): CachedWorktrees | null { const entry = cache.get(hostId) if (!entry) { diff --git a/mobile/src/components/AgentStateDot.tsx b/mobile/src/components/AgentStateDot.tsx index f9c67d3a3cf..bfa48b0a068 100644 --- a/mobile/src/components/AgentStateDot.tsx +++ b/mobile/src/components/AgentStateDot.tsx @@ -17,6 +17,7 @@ const dotColors = (): Record< done: '#10b981', blocked: '#ef4444', waiting: '#ef4444', + permission: '#ef4444', interrupted: colors.textMuted, failed: '#ef4444', unconfirmed: colors.statusAmber, diff --git a/mobile/src/components/SwipeRowActions.tsx b/mobile/src/components/SwipeRowActions.tsx new file mode 100644 index 00000000000..704077f636d --- /dev/null +++ b/mobile/src/components/SwipeRowActions.tsx @@ -0,0 +1,151 @@ +import type { LucideIcon } from 'lucide-react-native' +import type { ReactNode } from 'react' +import { Pressable, Text, View } from 'react-native' +import { Gesture, GestureDetector } from 'react-native-gesture-handler' +import Animated, { + Easing, + ReduceMotion, + useAnimatedStyle, + useSharedValue, + withTiming +} from 'react-native-reanimated' +import { feedback, typography } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { useDrawerReducedMotion } from './bottom-drawer/bottom-drawer-constants' +import { SHEET_CURVE } from './sheet-motion-values' + +// The width an action uncovers; a swipe past half of it settles open. +const ACTION_WIDTH = 84 +const SWIPE_SETTLE_MS = 250 +const DRAG_CLICK_WINDOW_MS = 400 + +export type SwipeRowAction = { + label: string + accessibilityLabel: string + icon: LucideIcon + background: string + foreground: string + onPress: () => void +} + +/** + * A row that slides to uncover an action: `leading` behind a right swipe, `trailing` behind a left + * one. Tapping the uncovered action runs it. Rows without either action render as they are; + * gaining or losing both remounts the row. + */ +export function SwipeRowActions({ + leading, + trailing, + enabled = true, + children +}: { + leading?: SwipeRowAction + trailing?: SwipeRowAction + enabled?: boolean + /** Gets a wrapper for the row's press: a tap on a swiped row closes it instead. */ + children: (guardPress: (onPress: () => void) => () => void) => ReactNode +}) { + useMobileColorScheme() + const reducedMotion = useDrawerReducedMotion() + const offset = useSharedValue(0) + const start = useSharedValue(0) + // When the last drag ended: on the web, releasing a mouse drag also clicks the row. + const dragEndedAt = useSharedValue(0) + const maxRight = leading ? ACTION_WIDTH : 0 + const maxLeft = trailing ? -ACTION_WIDTH : 0 + // Built per render: a module-level easing would run before a test's Reanimated mock can serve it. + const settle = (to: number) => { + 'worklet' + return withTiming( + to, + reducedMotion + ? { duration: 0, reduceMotion: ReduceMotion.Never } + : { duration: SWIPE_SETTLE_MS, easing: Easing.bezier(...SHEET_CURVE) } + ) + } + // Horizontal only, so the list keeps scrolling under a vertical drag. + const pan = Gesture.Pan() + .enabled(enabled) + .activeOffsetX([-12, 12]) + .failOffsetY([-10, 10]) + .onBegin(() => { + start.value = offset.value + }) + .onUpdate((event) => { + offset.value = Math.min(maxRight, Math.max(maxLeft, start.value + event.translationX)) + }) + .onEnd(() => { + // oxlint-disable-next-line react/purity -- runs when the drag ends, never during render. + dragEndedAt.value = Date.now() + offset.value = settle( + offset.value > ACTION_WIDTH / 2 ? maxRight : offset.value < -ACTION_WIDTH / 2 ? maxLeft : 0 + ) + }) + // Web has no worklet plugin; mapper hooks need this explicit dependency list. + const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }), [offset]) + // A tap on an open row closes it rather than pressing the row. + const guardPress = (onPress: () => void) => () => { + // The click a drag release produces belongs to the drag, not to the row. + if (Date.now() - dragEndedAt.value < DRAG_CLICK_WINDOW_MS) { + return + } + if (offset.value !== 0) { + offset.value = settle(0) + return + } + onPress() + } + if (!leading && !trailing) { + return children((onPress) => onPress) + } + const renderAction = (action: SwipeRowAction, side: 'leading' | 'trailing') => { + const Icon = action.icon + return ( + [ + styles.action, + side === 'leading' ? styles.leading : styles.trailing, + { backgroundColor: action.background }, + pressed && styles.actionPressed + ]} + disabled={!enabled} + onPress={() => { + offset.value = settle(0) + action.onPress() + }} + accessibilityRole="button" + accessibilityLabel={action.accessibilityLabel} + > + + {action.label} + + ) + } + return ( + + {leading ? renderAction(leading, 'leading') : null} + {trailing ? renderAction(trailing, 'trailing') : null} + {/* pan-y keeps the page scrolling vertically over the row on the web. */} + + {children(guardPress)} + + + ) +} + +const styles = themedStyleSheet(() => ({ + action: { + position: 'absolute', + top: 0, + bottom: 0, + width: ACTION_WIDTH, + alignItems: 'center', + justifyContent: 'center', + gap: 2 + }, + leading: { left: 0 }, + trailing: { right: 0 }, + actionPressed: { opacity: feedback.pressedOpacity }, + actionText: { fontSize: typography.metaSize, fontWeight: '600' } +})) diff --git a/mobile/src/home/MobileHomeNeedsYou.tsx b/mobile/src/home/MobileHomeNeedsYou.tsx index 5345ea8ac5d..e31ca0db5c1 100644 --- a/mobile/src/home/MobileHomeNeedsYou.tsx +++ b/mobile/src/home/MobileHomeNeedsYou.tsx @@ -1,5 +1,5 @@ import { memo } from 'react' -import type { AgentListRow } from '../agents/agent-list-model' +import type { AgentListRow } from '../agents/agent-list-rows' import { MobileAgentListRows, type AgentListRowHandlers } from '../agents/MobileAgentListRows' import { useMobileTranslation } from '../i18n/use-mobile-translation' import type { HostProfile } from '../transport/hosts/host-profile' @@ -10,14 +10,13 @@ import { MobileHomeSectionHeading } from './MobileHomeSectionHeading' const NEEDS_YOU_ROWS_SHOWN = 3 /** Feed's short list of agents waiting on the user; hidden when none are. */ -export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou( - props: AgentListRowHandlers & { - rows: readonly AgentListRow[] - hosts: readonly HostProfile[] - now: number - onSeeAll: () => void - } -) { +export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou(props: { + handlers: AgentListRowHandlers + rows: readonly AgentListRow[] + hosts: readonly HostProfile[] + now: number + onSeeAll: () => void +}) { const t = useMobileTranslation() if (props.rows.length === 0) { return null @@ -37,8 +36,7 @@ export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou( nameDesktop={props.hosts.length > 1} hosts={props.hosts} now={props.now} - onOpen={props.onOpen} - onLongPress={props.onLongPress} + handlers={props.handlers} /> ) diff --git a/mobile/src/home/MobileHomeScreen.tsx b/mobile/src/home/MobileHomeScreen.tsx index 205802355a2..fadfbfcd5aa 100644 --- a/mobile/src/home/MobileHomeScreen.tsx +++ b/mobile/src/home/MobileHomeScreen.tsx @@ -1,6 +1,7 @@ import { useFocusEffect } from 'expo-router' import { useCallback, useState } from 'react' import { Alert, BackHandler, View } from 'react-native' +import { GestureHandlerRootView } from 'react-native-gesture-handler' import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { useOpenMobileAccounts } from '../accounts/use-open-mobile-accounts' @@ -59,7 +60,11 @@ export function MobileHomeScreen() { const [visitedTabs, setVisitedTabs] = useState>(() => new Set(['feed'])) const [automationsHostId, setAutomationsHostId] = useState(null) const [tabBarHeight, setTabBarHeight] = useState(0) - const agentActions = useAgentListRowActions(tabBarHeight) + const agentActions = useAgentListRowActions( + tabBarHeight, + data.sortedHosts, + data.applyAgentActivity + ) const selectTab = useCallback((next: HomeTabId) => { setTab(next) @@ -165,121 +170,124 @@ export function MobileHomeScreen() { const contentBottom = spacing.xl + (fab ? FAB_CLEARANCE : 0) return ( - - - {HOME_TABS.map((id) => - visitedTabs.has(id) ? ( - - {id === 'feed' ? ( - - ) : id === 'agents' ? ( - - ) : id === 'usage' ? ( - - ) : id === 'automations' ? ( - openMobileAutomations(hostId)} - onHostChange={setAutomationsHostId} - /> - ) : ( - - )} - - ) : null - )} - - fab?.onPress()} - /> - setTabBarHeight(event.nativeEvent.layout.height)}> - + + + {HOME_TABS.map((id) => + visitedTabs.has(id) ? ( + + {id === 'feed' ? ( + + ) : id === 'agents' ? ( + + ) : id === 'usage' ? ( + + ) : id === 'automations' ? ( + openMobileAutomations(hostId)} + onHostChange={setAutomationsHostId} + /> + ) : ( + + )} + + ) : null + )} + + fab?.onPress()} /> - - {agentActions.sheet} - setActionTarget(null), - onReconnect: (hostId) => void forceReconnectHost?.(hostId), - onDisconnect: disconnectHostClient, - onDiagnostics: (hostId) => - data.router.push({ pathname: '/connection-log', params: { hostId } }), - onEdit: openMobileHostEdit, - onRemove: (host) => setConfirmRemove(host) - })} - onClose={() => setActionTarget(null)} - /> - void handleRemove()} - onCancel={() => setConfirmRemove(null)} - /> - + setTabBarHeight(event.nativeEvent.layout.height)}> + + + {agentActions.sheet} + setActionTarget(null), + onReconnect: (hostId) => void forceReconnectHost?.(hostId), + onDisconnect: disconnectHostClient, + onDiagnostics: (hostId) => + data.router.push({ pathname: '/connection-log', params: { hostId } }), + onEdit: openMobileHostEdit, + onRemove: (host) => setConfirmRemove(host) + })} + onClose={() => setActionTarget(null)} + /> + void handleRemove()} + onCancel={() => setConfirmRemove(null)} + /> + + ) } diff --git a/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx b/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx new file mode 100644 index 00000000000..04b40720156 --- /dev/null +++ b/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx @@ -0,0 +1,107 @@ +import { Monitor, WifiOff } from 'lucide-react-native' +import { useState } from 'react' +import type { AgentListHostSummary } from '../../agents/agent-list-rows' +import { PickerModal, type PickerOption } from '../../components/PickerModal' +import { hostPickerOptions } from '../../components/use-connected-host-picker' +import type { Translate } from '../../i18n/mobile-i18n' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { colors } from '../../theme/mobile-theme' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import type { HostProfile } from '../../transport/hosts/host-profile' +import { useHostDisplay } from '../../transport/hosts/use-host-display' +import { MobileHomePill } from './MobileHomeHostPill' + +const ALL_DESKTOPS = '__all__' + +/** The Agents tab's desktop filter: "All desktops" or one, each with its agent counts. */ +export function AgentsDesktopFilter(props: { + hosts: readonly HostProfile[] + selected: string | null + summaries: readonly AgentListHostSummary[] + onSelect: (hostId: string | null) => void +}) { + const t = useMobileTranslation() + const [open, setOpen] = useState(false) + return ( + <> + setOpen(true)} /> + props.onSelect(value === ALL_DESKTOPS ? null : value)} + onClose={() => setOpen(false)} + /> + + ) +} + +function desktopFilterOptions( + hosts: readonly HostProfile[], + summaries: readonly AgentListHostSummary[], + t: Translate +): PickerOption[] { + const agentCount = (count: number) => + count === 1 + ? t('agents.desktops.agents_one', '{{count}} agent', { count }) + : t('agents.desktops.agents_other', '{{count}} agents', { count }) + const total = summaries.reduce((sum, summary) => sum + summary.agents, 0) + const icon = (offline: boolean) => () => + offline ? ( + + ) : ( + + ) + return [ + { + value: ALL_DESKTOPS, + label: t('agents.desktops.all', 'All desktops'), + subtitle: agentCount(total), + renderIcon: icon(false) + }, + ...hostPickerOptions([...hosts]).map((option) => { + const summary = summaries.find((entry) => entry.hostId === option.value) + const needsYou = summary?.needsYou ?? 0 + return { + value: option.value, + label: option.label, + subtitle: summary?.offline + ? t('agents.desktops.offline', 'Offline') + : [ + agentCount(summary?.agents ?? 0), + needsYou > 0 + ? needsYou === 1 + ? t('agents.desktops.needsYou_one', '{{count}} needs you', { count: needsYou }) + : t('agents.desktops.needsYou_other', '{{count}} need you', { count: needsYou }) + : null + ] + .filter(Boolean) + .join(' · '), + renderIcon: icon(summary?.offline ?? false) + } + }) + ] +} + +function DesktopPill(props: { + hosts: readonly HostProfile[] + selected: string | null + onOpen: () => void +}) { + const t = useMobileTranslation() + useMobileColorScheme() + const selected = props.hosts.find((host) => host.id === props.selected) ?? null + const title = useHostDisplay(selected).title + const label = selected ? title : t('agents.desktops.all', 'All desktops') + return ( + } + accessibilityLabel={t('home.tabs.chooseDesktop', '{{desktop}}, choose another desktop', { + desktop: label + })} + onPress={props.onOpen} + /> + ) +} diff --git a/mobile/src/home/tabs/MobileHomeAgentsTab.tsx b/mobile/src/home/tabs/MobileHomeAgentsTab.tsx index eef7c90715d..c31b8a37079 100644 --- a/mobile/src/home/tabs/MobileHomeAgentsTab.tsx +++ b/mobile/src/home/tabs/MobileHomeAgentsTab.tsx @@ -1,22 +1,28 @@ -import { Bot, ChevronRight, Monitor, Search, SlidersHorizontal, WifiOff } from 'lucide-react-native' -import { useEffect, useMemo, useRef, useState } from 'react' -import { ScrollView, Text, View } from 'react-native' +import { + Bot, + CheckCheck, + ChevronRight, + Search, + SlidersHorizontal, + Trash2, + WifiOff +} from 'lucide-react-native' +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { ActivityIndicator, ScrollView, Text, View } from 'react-native' import { AGENT_LIST_GROUP_BY_CHOICES, + agentListRowsIn, buildAgentList, DEFAULT_AGENT_LIST_VIEW, - summarizeAgentListHosts, type AgentListGroupBy, type AgentListSection } from '../../agents/agent-list-model' +import { summarizeAgentListHosts } from '../../agents/agent-list-rows' import { loadAgentListView, saveAgentListView } from '../../agents/agent-list-preferences' import { MobileAgentListRows, type AgentListRowHandlers } from '../../agents/MobileAgentListRows' import type { ActionSheetAction } from '../../components/ActionSheetModal' import { MobileSearchField } from '../../components/MobileSearchField' import { PullDownMenu } from '../../components/nav-bar/PullDownMenu' -import { PickerModal, type PickerOption } from '../../components/PickerModal' -import { hostPickerOptions } from '../../components/use-connected-host-picker' -import type { Translate } from '../../i18n/mobile-i18n' import { useMobileTranslation } from '../../i18n/use-mobile-translation' import { useResponsiveLayout } from '../../layout/responsive-layout' import { useSerializedStoredState } from '../../storage/use-serialized-stored-state' @@ -29,11 +35,9 @@ import { formatTimeAgo } from '../../worktree/agent-row-display' import { homeListStyles } from '../home-list-styles' import { MobileHomeSectionHeading } from '../MobileHomeSectionHeading' import type { MobileHomeData } from '../use-mobile-home-data' -import { MobileHomePill } from './MobileHomeHostPill' +import { AgentsDesktopFilter } from './MobileHomeAgentsDesktopFilter' import { MobileHomeTabHeader, MobileHomeTabHeaderButton } from './MobileHomeTabHeader' -const ALL_DESKTOPS = '__all__' - /** Every agent on every paired desktop, grouped the way the user picked. */ export function MobileHomeAgentsTab(props: { data: MobileHomeData @@ -56,7 +60,6 @@ export function MobileHomeAgentsTab(props: { const [searchOpen, setSearchOpen] = useState(false) const [query, setQuery] = useState('') const [pickedHost, setPickedHost] = useState(null) - const [pickerOpen, setPickerOpen] = useState(false) const [menu, setMenu] = useState<'closed' | 'options' | 'group-by'>('closed') const optionsRef = useRef(null) // An unpaired desktop's filter falls back to every desktop. @@ -67,6 +70,16 @@ export function MobileHomeAgentsTab(props: { [data.agentList, view, hostFilter, query] ) const nameDesktops = hosts.length > 1 && hostFilter === null + const listed = useMemo(() => agentListRowsIn(list.sections), [list.sections]) + const unreadRows = listed.filter((row) => row.unread === true) + const clearableRows = listed.filter((row) => row.clearable) + const clearFinished = () => props.handlers.onClear(clearableRows) + // The Done heading's Clear acts on Done alone; a failed agent under Needs you stays. + const clearSection = (section: AgentListSection) => { + const rows = agentListRowsIn([section]).filter((row) => row.clearable) + return rows.length > 0 ? () => props.handlers.onClear(rows) : undefined + } + const hostSummaries = useMemo(() => summarizeAgentListHosts(data.agentList), [data.agentList]) const setView = (next: typeof view) => { stored.setValue(next) stored.persist(next) @@ -103,54 +116,112 @@ export function MobileHomeAgentsTab(props: { ), onPress: () => setMenu('group-by') }, + { + id: 'unread-only', + label: t('agents.options.unreadOnly', 'Unread only'), + checked: view.unreadOnly, + onPress: () => setView({ ...view, unreadOnly: !view.unreadOnly }) + }, { id: 'show-workers', label: t('agents.options.showWorkers', 'Show worker agents'), checked: view.showWorkers, onPress: () => setView({ ...view, showWorkers: !view.showWorkers }) } + ], + [ + { + id: 'mark-all-read', + label: t('agents.options.markAllRead', 'Mark all read'), + icon: CheckCheck, + disabled: unreadRows.length === 0, + onPress: () => props.handlers.onSetRead(unreadRows, true) + }, + { + id: 'clear-finished', + label: t('agents.options.clearFinished', 'Clear finished'), + icon: Trash2, + disabled: clearableRows.length === 0, + onPress: clearFinished + } ] ] - const body = !data.hostCatalogLoaded ? null : list.sections.length === 0 ? ( - - ) : ( - list.sections.map((section, index) => ( - - host.id === section.hostId) ?? null} - nameDesktop={nameDesktops} - first={index === 0} - now={now} + const filteredHosts = hosts.filter((host) => hostFilter === null || host.id === hostFilter) + // A desktop still connecting, or connected with its first list read pending, may yet have agents. + const awaitingDesktop = filteredHosts.some((host) => { + const state = data.hostStates[host.id] + return state === 'connected' + ? !data.worktreeInfo[host.id]?.catalogUnavailable + : state === undefined || state === 'connecting' || state === 'handshaking' + }) + const emptyState = (): ReactNode => { + const trimmed = query.trim() + if (trimmed) { + return ( + - - - )) - ) + ) + } + // "No agents running" is only true of a desktop that answered. + if (!list.anyLive) { + return awaitingDesktop ? ( + + + + ) : ( + + ) + } + return ( + + ) + } + + const body = !data.hostCatalogLoaded + ? null + : list.sections.length === 0 + ? emptyState() + : list.sections.map((section, index) => ( + + host.id === section.hostId) ?? null} + nameDesktop={nameDesktops} + first={index === 0} + now={now} + onClear={section.kind === 'done' ? clearSection(section) : undefined} + /> + + + )) return ( <> @@ -189,7 +260,12 @@ export function MobileHomeAgentsTab(props: { ) : null} {hosts.length > 1 ? ( - setPickerOpen(true)} /> + ) : null} setMenu('closed')} /> - {hosts.length > 1 ? ( - setPickedHost(value === ALL_DESKTOPS ? null : value)} - onClose={() => setPickerOpen(false)} - /> - ) : null} ) } -function desktopFilterOptions( - hosts: readonly HostProfile[], - summaries: ReturnType, - t: Translate -): PickerOption[] { - const agentCount = (count: number) => - count === 1 - ? t('agents.desktops.agents_one', '{{count}} agent', { count }) - : t('agents.desktops.agents_other', '{{count}} agents', { count }) - const total = summaries.reduce((sum, summary) => sum + summary.agents, 0) - const icon = (offline: boolean) => () => - offline ? ( - - ) : ( - - ) - return [ - { - value: ALL_DESKTOPS, - label: t('agents.desktops.all', 'All desktops'), - subtitle: agentCount(total), - renderIcon: icon(false) - }, - ...hostPickerOptions([...hosts]).map((option) => { - const summary = summaries.find((entry) => entry.hostId === option.value) - const needsYou = summary?.needsYou ?? 0 - return { - value: option.value, - label: option.label, - subtitle: summary?.offline - ? t('agents.desktops.offline', 'Offline') - : [ - agentCount(summary?.agents ?? 0), - needsYou > 0 - ? needsYou === 1 - ? t('agents.desktops.needsYou_one', '{{count}} needs you', { count: needsYou }) - : t('agents.desktops.needsYou_other', '{{count}} need you', { count: needsYou }) - : null - ] - .filter(Boolean) - .join(' · '), - renderIcon: icon(summary?.offline ?? false) - } - }) - ] -} - -function DesktopFilter(props: { - hosts: readonly HostProfile[] - selected: string | null - onOpen: () => void -}) { - const t = useMobileTranslation() - useMobileColorScheme() - const selected = props.hosts.find((host) => host.id === props.selected) ?? null - const title = useHostDisplay(selected).title - const label = selected ? title : t('agents.desktops.all', 'All desktops') - return ( - } - accessibilityLabel={t('home.tabs.chooseDesktop', '{{desktop}}, choose another desktop', { - desktop: label - })} - onPress={props.onOpen} - /> - ) -} - function AgentListSectionHeading(props: { section: AgentListSection host: HostProfile | null nameDesktop: boolean first: boolean now: number + /** The Done heading's "Clear": the same as Clear finished. */ + onClear?: () => void }) { const t = useMobileTranslation() const { section } = props @@ -336,8 +335,9 @@ function AgentListSectionHeading(props: { ) @@ -361,6 +361,7 @@ const styles = themedStyleSheet(() => ({ search: { marginHorizontal: spacing.lg, marginBottom: spacing.sm }, filters: { paddingHorizontal: spacing.lg }, menuValue: { flexDirection: 'row', alignItems: 'center', gap: 2 }, + connecting: { alignItems: 'center', paddingVertical: spacing.xl, marginTop: 32 }, menuValueText: { fontSize: 15, color: colors.textMuted }, empty: { alignItems: 'center', diff --git a/mobile/src/home/tabs/MobileHomeFeedTab.tsx b/mobile/src/home/tabs/MobileHomeFeedTab.tsx index abae60f97ab..68e1d7ad013 100644 --- a/mobile/src/home/tabs/MobileHomeFeedTab.tsx +++ b/mobile/src/home/tabs/MobileHomeFeedTab.tsx @@ -57,8 +57,7 @@ export function MobileHomeFeedTab(props: { rows={data.agentsNeedingYou} hosts={data.sortedHosts} now={data.agentList.now} - onOpen={props.agentHandlers.onOpen} - onLongPress={props.agentHandlers.onLongPress} + handlers={props.agentHandlers} onSeeAll={props.onSeeAllAgents} /> focusedRef.current, []) + // Drives the agent clock; Home stays mounted under other screens. + const [homeFocused, setHomeFocused] = useState(false) const hosts = useMemo(() => selectConnectableHostProfiles(hostCatalog), [hostCatalog]) const connections = useMobileHomeHostConnections(hosts, hostCatalog, hostSetters, isHomeFocused) const allClientsRef = useRef(connections.allClients) @@ -104,6 +107,7 @@ export function useMobileHomeData() { useCallback(() => { let stale = false focusedRef.current = true + setHomeFocused(true) void loadHostCatalog() // A failed read proves nothing about the desktops; keep the ones already shown. .catch((): HostCatalogEntry[] | null => null) @@ -134,6 +138,7 @@ export function useMobileHomeData() { return () => { stale = true focusedRef.current = false + setHomeFocused(false) } }, [router]) ) @@ -141,10 +146,24 @@ export function useMobileHomeData() { const sortedHosts = useMemo(() => sortHostsByLastConnected(hosts), [hosts]) const sortedHostCatalog = useMemo(() => sortHostsByLastConnected(hostCatalog), [hostCatalog]) // One clock for every agent count, so Feed, the Agents badge and each desktop agree. - const now = useNow(30_000) + const now = useNow(30_000, homeFocused) + const refetchHostAgents = useCallback((hostId: string) => { + const entry = allClientsRef.current.find((candidate) => candidate.hostId === hostId) + return entry?.client.getState() === 'connected' + ? fetchHomeHostWorktreeInfo(entry.client, hostId, setWorktreeInfo, () => false) + : Promise.resolve() + }, []) + const agentActivity = useAgentActivityWrites(connections.allClients, refetchHostAgents) + const { pendingActivity } = agentActivity const agentList = useMemo( - () => ({ hosts: sortedHosts, hostStates: connections.hostStates, worktreeInfo, now }), - [sortedHosts, connections.hostStates, worktreeInfo, now] + () => ({ + hosts: sortedHosts, + hostStates: connections.hostStates, + worktreeInfo, + now, + pendingActivity + }), + [sortedHosts, connections.hostStates, worktreeInfo, now, pendingActivity] ) const agentsNeedingYou = useMemo(() => selectAgentsNeedingYou(agentList), [agentList]) const needsYouByHost = useMemo( @@ -170,6 +189,7 @@ export function useMobileHomeData() { return { ...connections, accountsByHost, + applyAgentActivity: agentActivity.apply, agentList, agentsNeedingYou, connectedHosts, diff --git a/mobile/src/home/use-mobile-home-host-connections.ts b/mobile/src/home/use-mobile-home-host-connections.ts index 605bd45720f..f29fbdbe557 100644 --- a/mobile/src/home/use-mobile-home-host-connections.ts +++ b/mobile/src/home/use-mobile-home-host-connections.ts @@ -27,7 +27,9 @@ const HOME_WORKTREE_REFRESH_MIN_INTERVAL_MS = 3000 const WORKTREE_CHANGE_EVENTS: ReadonlySet = new Set([ 'sidebarInputsChanged', 'worktreesChanged', - 'reposChanged' + 'reposChanged', + // The desktop Agents list changed; worktree.ps carries its verdicts. + 'agentListChanged' ]) export type HomeAccountsSetter = ( diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index a81b470d601..9fad7a8ed7b 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -895,7 +895,8 @@ "hours_other": "{{count}}h", "days_one": "{{count}}d", "days_other": "{{count}}d", - "done": "Done" + "done": "Done", + "permission": "Needs attention" }, "hostWorkspaceListStates": { "checkHost": "Check that your computer is awake and Orca is running", @@ -4762,7 +4763,12 @@ "noMatches": "No agents match “{{query}}”", "emptyTitle": "No agents running", "pairDesktop": "Pair a desktop to see its agents here.", - "emptyBody": "Start an agent in any workspace and it shows up here." + "emptyBody": "Start an agent in any workspace and it shows up here.", + "unread": "Unread", + "noDesktopTitle": "No desktop connected", + "noDesktopBody": "Agents show up here once a desktop connects.", + "hideWorkers": "Hide {{workers}}", + "showWorkers": "Show {{workers}}" }, "actions": { "offlineHint": "Its desktop is offline.", @@ -4770,7 +4776,10 @@ "goToWorkspace": "Go to workspace", "copyTitle": "Copy title", "copied": "Copied", - "copyFailed": "Couldn’t copy the title" + "copyFailed": "Couldn’t copy the title", + "markRead": "Mark as read", + "markUnread": "Mark as unread", + "clear": "Clear from list" }, "groupBy": { "status": "Status", @@ -4782,7 +4791,10 @@ "options": { "groupBy": "Group by", "showWorkers": "Show worker agents", - "open": "Agent list options" + "open": "Agent list options", + "unreadOnly": "Unread only", + "markAllRead": "Mark all read", + "clearFinished": "Clear finished" }, "search": { "toggle": "Search agents", @@ -4805,7 +4817,17 @@ "offlineSeenAgo": "Offline · seen {{ago}} ago", "offlineSeenJustNow": "Offline · seen just now", "seenAgo": "Seen {{ago}} ago", - "seenJustNow": "Seen just now" + "seenJustNow": "Seen just now", + "clear": "Clear" + }, + "swipe": { + "read": "Read", + "unread": "Unread", + "clear": "Clear" + }, + "activity": { + "needsWindow": "Couldn’t update. Open Orca on {{desktop}}.", + "failed": "Couldn’t update the agent list." } } } diff --git a/mobile/src/source-control/MobileSourceControlFileRows.tsx b/mobile/src/source-control/MobileSourceControlFileRows.tsx index 869ce8c328d..71e04ff4603 100644 --- a/mobile/src/source-control/MobileSourceControlFileRows.tsx +++ b/mobile/src/source-control/MobileSourceControlFileRows.tsx @@ -1,15 +1,6 @@ import type { ReactNode } from 'react' import { ActivityIndicator, Pressable, Text, View } from 'react-native' -import { Gesture, GestureDetector } from 'react-native-gesture-handler' -import Animated, { - Easing, - ReduceMotion, - useAnimatedStyle, - useSharedValue, - withTiming -} from 'react-native-reanimated' -import { SHEET_CURVE } from '../components/sheet-motion-values' -import { useDrawerReducedMotion } from '../components/bottom-drawer/bottom-drawer-constants' +import { SwipeRowActions } from '../components/SwipeRowActions' import { Minus, Plus, Undo2 } from 'lucide-react-native' import { colors } from '../theme/mobile-theme' import { STATUS_LABELS } from '../../../src/shared/git/status/git-status-labels' @@ -114,101 +105,6 @@ function FileRowBody({ ) } -// The width the Discard action uncovers; a swipe past half of it settles open. -const DISCARD_WIDTH = 84 -const SWIPE_SETTLE_MS = 250 -const DRAG_CLICK_WINDOW_MS = 400 - -/** Discard sits behind a left swipe and still asks first; it is also on the diff screen. */ -function SwipeToDiscard({ - available, - enabled, - label, - accessibilityLabel, - onDiscard, - children -}: { - /** Only discardable rows get the swipe; toggling it would remount the row. */ - available: boolean - enabled: boolean - label: string - accessibilityLabel: string - onDiscard: () => void - /** Gets a wrapper for the row's press: a tap on a swiped row closes it instead. */ - children: (guardPress: (onPress: () => void) => () => void) => ReactNode -}) { - useMobileColorScheme() - const reducedMotion = useDrawerReducedMotion() - const offset = useSharedValue(0) - const start = useSharedValue(0) - // When the last drag ended: on the web, releasing a mouse drag also clicks the row. - const dragEndedAt = useSharedValue(0) - // Built per render: a module-level easing would run before a test's Reanimated mock can serve it. - const settle = (to: number) => { - 'worklet' - return withTiming( - to, - reducedMotion - ? { duration: 0, reduceMotion: ReduceMotion.Never } - : { duration: SWIPE_SETTLE_MS, easing: Easing.bezier(...SHEET_CURVE) } - ) - } - // Horizontal only, so the list keeps scrolling under a vertical drag. - const pan = Gesture.Pan() - .enabled(enabled) - .activeOffsetX([-12, 12]) - .failOffsetY([-10, 10]) - .onBegin(() => { - start.value = offset.value - }) - .onUpdate((event) => { - offset.value = Math.min(0, Math.max(-DISCARD_WIDTH, start.value + event.translationX)) - }) - .onEnd(() => { - // oxlint-disable-next-line react/purity -- runs when the drag ends, never during render. - dragEndedAt.value = Date.now() - offset.value = settle(offset.value < -DISCARD_WIDTH / 2 ? -DISCARD_WIDTH : 0) - }) - // Web has no worklet plugin; mapper hooks need this explicit dependency list. - const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }), [offset]) - // A tap on an open row closes it rather than opening the diff. - const guardPress = (onPress: () => void) => () => { - // The click a drag release produces belongs to the drag, not to the row. - if (Date.now() - dragEndedAt.value < DRAG_CLICK_WINDOW_MS) { - return - } - if (offset.value !== 0) { - offset.value = settle(0) - return - } - onPress() - } - if (!available) { - return children((onPress) => onPress) - } - return ( - - [styles.discardAction, pressed && styles.iconButtonPressed]} - disabled={!enabled} - onPress={() => { - offset.value = settle(0) - onDiscard() - }} - accessibilityRole="button" - accessibilityLabel={accessibilityLabel} - > - - {label} - - {/* pan-y keeps the page scrolling vertically over the row on the web. */} - - {children(guardPress)} - - - ) -} - export function ChangeFileRow({ item, state @@ -294,14 +190,23 @@ export function ChangeFileRow({ ) : null return ( - setDiscardTarget(item)} + trailing={ + item.canDiscard + ? { + label: t('sourceControl.fileRows.discard', 'Discard'), + accessibilityLabel: t('sourceControl.fileRows.discardFile', 'Discard {{path}}', { + path: item.path + }), + icon: Undo2, + background: colors.statusRed, + foreground: colors.onStatusRed, + onPress: () => setDiscardTarget(item) + } + : undefined + } > {(guardPress) => ( )} - + ) } diff --git a/mobile/src/source-control/mobile-source-control-list-styles.ts b/mobile/src/source-control/mobile-source-control-list-styles.ts index 6b43b3a73e7..2ee25cc000c 100644 --- a/mobile/src/source-control/mobile-source-control-list-styles.ts +++ b/mobile/src/source-control/mobile-source-control-list-styles.ts @@ -93,23 +93,6 @@ export const listStyles = themedStyleSheet(() => ({ alignItems: 'center', justifyContent: 'center' }, - // Behind the row's right end; the row slides left to uncover it. - discardAction: { - position: 'absolute', - top: 0, - right: 0, - bottom: 0, - width: 84, - alignItems: 'center', - justifyContent: 'center', - gap: 2, - backgroundColor: colors.statusRed - }, - discardActionText: { - color: colors.onStatusRed, - fontSize: typography.metaSize, - fontWeight: '600' - }, conflictActions: { flexDirection: 'row', flexWrap: 'wrap', diff --git a/mobile/src/worktree/agent-row-display.ts b/mobile/src/worktree/agent-row-display.ts index 164c4699422..5969f45afc0 100644 --- a/mobile/src/worktree/agent-row-display.ts +++ b/mobile/src/worktree/agent-row-display.ts @@ -3,20 +3,11 @@ import { isAgentStatusFresh } from '../../../src/shared/agent-status/contracts/a import { agentVerdictDisplayMark } from '../../../src/shared/agent-status/lifecycle/agent-main-agent-verdict' import { resolveDecayedAgentRowState } from '../../../src/shared/agent-status/presentation/agent-row-decay-state' import { getAgentRowPrimaryText } from '../../../src/shared/agent-status/presentation/agent-row-primary-text' +import type { AgentListStatus } from '../../../src/shared/agent-status/presentation/agent-list-status' import { translate } from '../i18n/mobile-i18n' -// Mirror desktop AgentStateDot vocabulary. -export type AgentDotState = - | 'working' - | 'monitoring' - | 'blocked' - | 'waiting' - | 'done' - | 'idle' - | 'unverifiable' - | 'interrupted' - | 'failed' - | 'unconfirmed' +// Desktop AgentStateDot's vocabulary. +export type AgentDotState = AgentListStatus // A session tab's AgentStatusEntry leaves `interrupted` optional; worktree rows always send it. type AgentRowVerdictSource = Pick & { @@ -69,6 +60,8 @@ export function agentStateLabel(state: AgentDotState): string { return translate('worktree.agentRowDisplay.idle', 'Idle') case 'unverifiable': return translate('worktree.agentRowDisplay.unverifiable', 'No recent update') + case 'permission': + return translate('worktree.agentRowDisplay.permission', 'Needs attention') } } From b4f198379a9771259b19269d736e376ceee16db5 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sun, 8 Nov 2026 11:43:36 -0800 Subject: [PATCH 13/23] test: remove 17 low-value mobile test cases (#39941) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- config/reliability-gates.jsonc | 7 +- .../mobile-markdown-visual-lines.test.ts | 14 --- .../pr-sidebar/pr-actions-state.test.ts | 8 -- ...le-structured-queued-message-cards.test.ts | 92 ------------------- ...obileNativeChatView.failure-banner.test.ts | 14 --- .../mobile-native-chat-image-preview.test.ts | 15 --- .../mobile-review-route.test.ts | 26 ------ mobile/src/stats/home-stats-total.test.ts | 24 +---- mobile/src/tasks/agent-launch-request.test.ts | 24 ----- .../terminal-live-accessory-raw-send.test.ts | 10 -- .../src/theme/mobile-theme-contrast.test.ts | 65 ------------- 11 files changed, 5 insertions(+), 294 deletions(-) delete mode 100644 mobile/src/session/mobile-structured-queued-message-cards.test.ts delete mode 100644 mobile/src/source-control/mobile-review-route.test.ts delete mode 100644 mobile/src/tasks/agent-launch-request.test.ts delete mode 100644 mobile/src/theme/mobile-theme-contrast.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index fee52a30d05..fa352785095 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -454,10 +454,10 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime", "mobile-relay"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Historical scope: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts: Loses configured retry gap and single-Enter agent selection alarms alongside forbidden timer-count checks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1383 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audits1340 and1348 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1316 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Production mobile controller, parser, presentation, overlay, view, question, permission and composer run with native surfaces mocked on macOS. Desktop selector groups traverse the real observed-write queue, verified helper, IPC chunker, SSH provider and transport callbacks; paired sends traverse the real dispatcher and runtime writer into that provider. Local/daemon contracts and released-version terminal codecs are covered. Provider labels describe contracts, not physical deployments; physical WSL/Linux/Windows remain gaps. Audit885 removes the isolated observed-send mock-call suite; no replacement-equivalence claim is made. Audit1107 removes the small healthy ordinary SSH-send byte/callback sample. Its exact clear/body/Enter sample alarm is lost; retained slow-answer, cancellation and simulated older-host sequence checks are not claimed as equivalent replacement coverage. The SSH delivery fixture uses controlled fake provider settlement, and its paired path uses the real runtime/dispatcher without a physical SSH or paired wire transport. Audit1278 removes the mobile Stop display/disabled/placeholder suite; its local Stop presentation, repeat-stop and dispatch-visibility alarms are intentionally lost. No equivalent replacement or runtime stopping proof is claimed. Audit1292: The blind OpenCode readiness warning and late launch success/failure content-plus-submit write samples are removed. Their mocked readiness/inspection/delivery alarms are lost; no real PTY delivery or equivalent replacement coverage is claimed. Audit1294 removes mobile/src/session/native-chat/input/mobile-native-chat-permission-send.test.ts. Its mock-only request/capability/private-state/copy alarms are intentionally lost. Remaining tests are not equivalent replacement coverage. Narrowed commands require fresh parent-owned validation; no new runtime, platform or physical mobile evidence is claimed. Audit1302: src/main/ipc/pty/ipc/write-input-acceptance.test.ts: Provider registry and write acceptance/refusal/unverifiable receipts are supplied by fixture; local/daemon/WSL/SSH labels use the same fake provider. Chunking/settlement/remount cases inspect delegated calls or canned receipts without actual provider acceptance/acknowledgement. Lose chunk/refusal/pending/remount and raw-pane routing alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1303 intentionally removes supplied-state/mock-callback component and hook examples in mobile/src/session/native-chat/input/use-mobile-native-chat-ask-dismiss.test.ts, mobile/src/session/native-chat/input/MobileNativeChatPromptCard.test.tsx. Their exact retired alarms are not equivalent to retained coverage; no new runtime, physical phone or deployed mixed-version evidence is claimed. Audit1310 removes the supplied-geometry/direct-callback chat history-paging suite. Its prepend/scroll-position examples are intentionally lost; no real rendered anchoring, equivalent replacement or physical phone proof is claimed. Narrowed commands need fresh validation. Audit1315 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.composer-lock.test.ts, mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1316: src/renderer/src/lib/agent-followup-delivery.test.ts removed. Interpreter wrapper/live child/shell readiness and final readiness recheck delivery mock samples lose alarms. No equivalent replacement coverage is claimed. Audit1322 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.tail-follow.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/mobile-native-chat-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1335 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/mobile-prompt-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1340: src/main/daemon/daemon-pty-write-settlement-recovery.test.ts removed. Ambiguous handoff settlement remains unverifiable when listener throws. No equivalent replacement coverage is claimed. Audit1348: src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts removed. Check-phase yielding and no-yield single-chunk scheduling work. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Lose admission provenance spy, direct local Escape write outcome matrix and separate client-side SSH no-evidence control. Provider writes mocked; retained tests protect observation order/facts only. No equivalent replacement coverage is claimed. Audit1401: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Loses local-only post-accept observation and refused/unverifiable settlement delivery alarms. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/native-chat/native-chat-runtime-send-launch-draft.test.ts removed. Intentionally loses clear-confirmation/body/submit and maximal-clear ordering, queued text/image send ordering, ordinary cursor-spanning draft replacement and oversized refusal/queue settlement alarms. No equivalent replacement or real terminal delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1426 removes NativeChatComposer.test.tsx. Local pane-remount, draft/cancel/confirmation sequencing and manual IME callback alarms are lost. No equivalent replacement coverage or provider delivery is claimed; historical receipts retain their original scope and the reduced selector has no new execution result.", + "coverageNotes": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Historical scope: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts: Loses configured retry gap and single-Enter agent selection alarms alongside forbidden timer-count checks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1383 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audits1340 and1348 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1316 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Production mobile controller, parser, presentation, overlay, view, question, permission and composer run with native surfaces mocked on macOS. Desktop selector groups traverse the real observed-write queue, verified helper, IPC chunker, SSH provider and transport callbacks; paired sends traverse the real dispatcher and runtime writer into that provider. Local/daemon contracts and released-version terminal codecs are covered. Provider labels describe contracts, not physical deployments; physical WSL/Linux/Windows remain gaps. Audit885 removes the isolated observed-send mock-call suite; no replacement-equivalence claim is made. Audit1107 removes the small healthy ordinary SSH-send byte/callback sample. Its exact clear/body/Enter sample alarm is lost; retained slow-answer, cancellation and simulated older-host sequence checks are not claimed as equivalent replacement coverage. The SSH delivery fixture uses controlled fake provider settlement, and its paired path uses the real runtime/dispatcher without a physical SSH or paired wire transport. Audit1278 removes the mobile Stop display/disabled/placeholder suite; its local Stop presentation, repeat-stop and dispatch-visibility alarms are intentionally lost. No equivalent replacement or runtime stopping proof is claimed. Audit1292: The blind OpenCode readiness warning and late launch success/failure content-plus-submit write samples are removed. Their mocked readiness/inspection/delivery alarms are lost; no real PTY delivery or equivalent replacement coverage is claimed. Audit1294 removes mobile/src/session/native-chat/input/mobile-native-chat-permission-send.test.ts. Its mock-only request/capability/private-state/copy alarms are intentionally lost. Remaining tests are not equivalent replacement coverage. Narrowed commands require fresh parent-owned validation; no new runtime, platform or physical mobile evidence is claimed. Audit1302: src/main/ipc/pty/ipc/write-input-acceptance.test.ts: Provider registry and write acceptance/refusal/unverifiable receipts are supplied by fixture; local/daemon/WSL/SSH labels use the same fake provider. Chunking/settlement/remount cases inspect delegated calls or canned receipts without actual provider acceptance/acknowledgement. Lose chunk/refusal/pending/remount and raw-pane routing alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1303 intentionally removes supplied-state/mock-callback component and hook examples in mobile/src/session/native-chat/input/use-mobile-native-chat-ask-dismiss.test.ts, mobile/src/session/native-chat/input/MobileNativeChatPromptCard.test.tsx. Their exact retired alarms are not equivalent to retained coverage; no new runtime, physical phone or deployed mixed-version evidence is claimed. Audit1310 removes the supplied-geometry/direct-callback chat history-paging suite. Its prepend/scroll-position examples are intentionally lost; no real rendered anchoring, equivalent replacement or physical phone proof is claimed. Narrowed commands need fresh validation. Audit1315 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.composer-lock.test.ts, mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1316: src/renderer/src/lib/agent-followup-delivery.test.ts removed. Interpreter wrapper/live child/shell readiness and final readiness recheck delivery mock samples lose alarms. No equivalent replacement coverage is claimed. Audit1322 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.tail-follow.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/mobile-native-chat-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1335 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/mobile-prompt-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1340: src/main/daemon/daemon-pty-write-settlement-recovery.test.ts removed. Ambiguous handoff settlement remains unverifiable when listener throws. No equivalent replacement coverage is claimed. Audit1348: src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts removed. Check-phase yielding and no-yield single-chunk scheduling work. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Lose admission provenance spy, direct local Escape write outcome matrix and separate client-side SSH no-evidence control. Provider writes mocked; retained tests protect observation order/facts only. No equivalent replacement coverage is claimed. Audit1401: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Loses local-only post-accept observation and refused/unverifiable settlement delivery alarms. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/native-chat/native-chat-runtime-send-launch-draft.test.ts removed. Intentionally loses clear-confirmation/body/submit and maximal-clear ordering, queued text/image send ordering, ordinary cursor-spanning draft replacement and oversized refusal/queue settlement alarms. No equivalent replacement or real terminal delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1426 removes NativeChatComposer.test.tsx. Local pane-remount, draft/cancel/confirmation sequencing and manual IME callback alarms are lost. No equivalent replacement coverage or provider delivery is claimed; historical receipts retain their original scope and the reduced selector has no new execution result. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/25761"], "invariant": "A prompt occurrence leaves the input region only when an accepted reply answers it (a current host's provider acknowledgment, or an older host's whole-write acceptance as before) or the user collapses it to a strip above the composer, which writes nothing and keeps the card mounted with its partial answer; status-backed occurrences are told apart by the host wait's start, so view toggles and remounts preserve them while real clear/replacement supersedes them, and a transcript-only one is dropped when the view stops observing it; obsolete results cannot change replacements; selector groups wait for complete writes before pacing; refusal or unknown handoff never causes replay; a card retires an unsubmitted composer send without writing under it or losing its text, and the hidden composer cannot send or interrupt; Collapse or Escape folds a card without writing, never during an in-flight answer, and a new occurrence shows expanded again; the phone blocks only Send while a card is expanded and shows one card per occurrence; cancellation stops unsent groups and active dictation can stop.", - "oracle": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it.", + "oracle": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-paste-draft.test.ts src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts mobile/src/session/mobile-prompt-controller.test.ts --maxWorkers=2", @@ -606,7 +606,8 @@ "Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed.", "Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts.", "Historical assertion references before mobile owner-layout policy; removed references have no replacement claim: [{\"file\":\"src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx\",\"assertions\":[\"ignores a raw acknowledgment from a rebound PTY\",\"sends only one cancellation, can cancel an answer, and permits retry after unknown\"]},{\"file\":\"mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts\",\"assertions\":[\"a late answer cannot reshow an answered replacement occurrence\",\"a late answer cannot dismiss a replacement session\"]},{\"file\":\"mobile/src/session/mobile-prompt-controller.test.ts\",\"assertions\":[\"finishes an older-host selector once and dismisses it like an acknowledged answer\",\"dismisses older-host approval choice %i like an acknowledged answer and restores Send\",\"retains permission choices on %s\",\"acknowledges the same pending %s after a view-only toggle\",\"shows a collapsed prompt again as a new wait\",\"keeps an acknowledged Deny hidden after the chat screen remounts on a lingering status\",\"drops an accepted result after real %s replacement\",\"keeps an agent notice answerable and retires only human input through the %s view\",\"retains exact cancelled calls through edits, prefix/ID replay, paging and new equal rows (%s)\",\"keeps structured %s admission separate from captured Cancel and delivered rows\",\"settles the terminal answer for Q1 after Q2 arrives without hiding Q2\",\"fences a late captured structured answer after %s replacement\",\"does not turn real %s host-result conversion into an answered question\",\"keeps later same-ID Cancel after eviction/reentry and old answer settlement\",\"keeps structured answer controls after a thrown send\",\"isolates equal portable IDs on two hosts and rejects the old host callback\"]},{\"file\":\"tests/e2e/native-chat-ssh-delivery.unit.test.ts\",\"assertions\":[\"serializes every chunk of a healthy large SSH answer before Enter and dismissal\",\"cancels remaining paced groups while an already-issued body still settles\",\"paired terminal.send uses provider settlement for accepted and lost acknowledgment\",\"older paired hosts keep their whole-write verdict for answers and ordinary sequences\",\"older paired hosts confirm ordinary chat sends and pasted answers as before\",\"finishes every older-host selector group once and settles the answer as delivered\"]},{\"file\":\"src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx\",\"assertions\":[\"keeps an in-flight message visible and never submits it into the approval\",\"routes no typing to the hidden composer until the card is answered\"]},{\"file\":\"src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx\",\"assertions\":[\"keeps an answered approval hidden across a chat view remount and a PTY rebind\"]},{\"file\":\"src/main/runtime/terminal/input/runtime-terminal-writer.test.ts\",\"assertions\":[\"waits for complete body settlement before Enter\",\"does not send the suffix after refusal or unknown settlement\",\"returns unknown after an acknowledged prefix followed by refusal or bookkeeping failure\",\"preserves legacy raw body and Enter writes\"]}]", - "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed." + "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed.", + "Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim." ], "promotionCriteria": [ "Record change-reverted red/green evidence and repeatable remote rendered approval/question/dictation journeys.", diff --git a/mobile/src/components/mobile-markdown-visual-lines.test.ts b/mobile/src/components/mobile-markdown-visual-lines.test.ts index b7380d337f5..62dd3318518 100644 --- a/mobile/src/components/mobile-markdown-visual-lines.test.ts +++ b/mobile/src/components/mobile-markdown-visual-lines.test.ts @@ -69,20 +69,6 @@ describe('native-chat visual lines in mobile markdown', () => { expect(directives).toEqual([{ file: 'after.html', title: null }]) }) - it('leaves malformed or path-like directives as literal text', () => { - for (const line of [ - '::orca-visual{file="../secret.html"}', - '::orca-visual{file="a.html" file="b.html"}', - '::orca-visual{file="a.htm"}', - '::orca-visual{file="a.html"', - '::orca-visual{file="a.html"} trailing words' - ]) { - const { directives, blocks } = blocksOf(line) - expect(directives, line).toEqual([]) - expect(blocks, line).toEqual([{ type: 'paragraph', text: line }]) - } - }) - it('renders directives past the per-message cap as text', () => { const lines = Array.from( { length: NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE + 1 }, diff --git a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts b/mobile/src/components/pr-sidebar/pr-actions-state.test.ts index ea067a09a8c..dfc489ea490 100644 --- a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts +++ b/mobile/src/components/pr-sidebar/pr-actions-state.test.ts @@ -21,14 +21,6 @@ describe('presentPrMerge', () => { mergeable: 'MERGEABLE' as const } - it('disables Merge with desktop copy when GitHub reports conflicts', () => { - expect(presentPrMerge(pr, 'squash')).toMatchObject({ - enabled: false, - label: 'Conflicts', - hint: 'GitHub reports merge conflicts' - }) - }) - it('lets a complete stack merge through, and names a blocking downstack PR', () => { const stack = { number: 51, diff --git a/mobile/src/session/mobile-structured-queued-message-cards.test.ts b/mobile/src/session/mobile-structured-queued-message-cards.test.ts deleted file mode 100644 index 20c7058de34..00000000000 --- a/mobile/src/session/mobile-structured-queued-message-cards.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { agentSessionFailureFact } from '../../../src/shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../../src/shared/agent-session/failures/agent-session-failure-words' -import { - QUEUED_MESSAGE_PAUSED_SEND_FAILED, - type AgentSessionQueuedMessage -} from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import { queuedMessagesQueuePause } from '../../../src/shared/agent-session/view/structured-agent-session-queued-cards' -import type { AgentJournalSubmission } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { mobileQueuedMessageCards } from './mobile-structured-queued-message-cards' - -function returnedAs(fact: Parameters[0]) { - const { reason, rejection } = agentSessionFailureWords(fact, { surface: 'rejection' }) - return { state: 'returned' as const, returnedReason: reason, returnedRejection: rejection } -} - -function draft(overrides: Partial & { messageId: string }) { - return { - position: 1, - body: { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: `body of ${overrides.messageId}` }] - }, - state: 'waiting' as const, - ...overrides - } -} - -describe('mobileQueuedMessageCards', () => { - it('finds waiting input for Resume past returned or failed cards', () => { - const resumable = (drafts: AgentSessionQueuedMessage[]) => - queuedMessagesQueuePause(mobileQueuedMessageCards(drafts, []), { reason: 'stopped' }) !== null - const returned = draft({ - messageId: 'r', - ...returnedAs(agentSessionFailureFact('hostRestarted')) - }) - const failed = draft({ - messageId: 'f', - paused: true, - pausedReason: QUEUED_MESSAGE_PAUSED_SEND_FAILED - }) - const waiting = draft({ messageId: 'w', position: 2 }) - expect(resumable([returned])).toBe(false) - expect(resumable([returned, waiting])).toBe(true) - expect(resumable([failed])).toBe(false) - expect(resumable([failed, waiting])).toBe(true) - expect(resumable([waiting, { ...returned, position: 3 }])).toBe(true) - }) - - it('hides a waiting card once its hand-off arrived, never a returned one', () => { - const cards = mobileQueuedMessageCards( - [ - draft({ messageId: 'returned', ...returnedAs(agentSessionFailureFact('hostRestarted')) }), - draft({ messageId: 'drained', position: 2 }), - draft({ messageId: 'waiting', position: 3 }) - ], - [handOff('returned', 'rejected'), handOff('drained', 'pending')] - ) - expect(cards.map((card) => card.messageId)).toEqual(['returned', 'waiting']) - }) - - it('shows a draft a Stop requeued beside its rejected hand-off', () => { - // Rejected hand-offs stay hidden in history; the requeued card is the only reachable copy of their text. - const cards = mobileQueuedMessageCards( - [ - draft({ messageId: 'requeued' }), - draft({ messageId: 'sending', position: 2 }), - draft({ messageId: 'sent', position: 3 }) - ], - [handOff('requeued', 'rejected'), handOff('sending', 'pending'), handOff('sent', 'accepted')] - ) - expect(cards.map((card) => card.messageId)).toEqual(['requeued']) - }) -}) - -function handOff( - queuedMessageId: string, - dispatchState: AgentJournalSubmission['dispatchState'] -): AgentJournalSubmission { - return { - clientMessageId: `${queuedMessageId}-handoff`, - queuedMessageId, - dispatchState, - fence: 1, - payloadFingerprint: 'fingerprint', - providerItemId: null, - reason: null, - submittedAt: 1, - resolvedAt: null - } -} diff --git a/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts b/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts index f923bf96d8e..6e7ba0d0431 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts +++ b/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts @@ -80,20 +80,6 @@ describe('MobileNativeChatView: send and read failure banners', () => { expect(banners()).toHaveLength(1) }) - it('retires the previous route banner when a new send starts', async () => { - const onClearSendError = vi.fn() - await render({ - onSend: vi.fn().mockResolvedValue(false), - sendErrorMessage: 'Stop failed', - onClearSendError - }) - await pressSend() - - expect(onClearSendError).toHaveBeenCalledOnce() - expect(banners()).toHaveLength(1) - expect(bannerText()).toBe('Stop failed') - }) - it('retires the previous banner before sending and preserves the new delivery notice', async () => { const onClearSendError = vi.fn() await render({ diff --git a/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts b/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts index c57802607e6..b43cccdae12 100644 --- a/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts +++ b/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts @@ -3,21 +3,6 @@ import { describe, expect, it } from 'vitest' import { isRenderableImageUri } from './mobile-native-chat-image-preview' describe('isRenderableImageUri', () => { - it('accepts local previews and real URLs the device can load', () => { - for (const uri of [ - 'file:///var/mobile/a.jpg', - 'FILE:///var/mobile/a.jpg', - 'HTTPS://host/a.png', - 'data:image/png;base64,AAAA', - 'content://media/1', - 'blob:abc', - 'http://host/a.png', - 'https://host/a.png' - ]) { - expect(isRenderableImageUri(uri)).toBe(true) - } - }) - it('rejects bare host paths (not loadable on the device) and empty values', () => { for (const uri of [ '/tmp/orca-attach.png', diff --git a/mobile/src/source-control/mobile-review-route.test.ts b/mobile/src/source-control/mobile-review-route.test.ts deleted file mode 100644 index 30f392df29f..00000000000 --- a/mobile/src/source-control/mobile-review-route.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { buildMobileReviewFileRoute } from './mobile-review-route' - -function queryParams(route: string): URLSearchParams { - const query = route.split('?')[1] ?? '' - return new URLSearchParams(query) -} - -describe('buildMobileReviewFileRoute', () => { - it('carries the commit for a file opened from a commit', () => { - const params = queryParams( - buildMobileReviewFileRoute({ - hostId: 'host', - worktreeId: 'wt', - worktreeName: '', - filePath: 'a.ts', - area: 'commit', - commitOid: 'c0ffee0123456789abcdef0123456789abcdef01' - }) - ) - - expect(params.get('area')).toBe('commit') - expect(params.get('commit')).toBe('c0ffee0123456789abcdef0123456789abcdef01') - }) -}) diff --git a/mobile/src/stats/home-stats-total.test.ts b/mobile/src/stats/home-stats-total.test.ts index 076d64b8a76..daff818e1fa 100644 --- a/mobile/src/stats/home-stats-total.test.ts +++ b/mobile/src/stats/home-stats-total.test.ts @@ -1,10 +1,5 @@ import { describe, expect, it } from 'vitest' -import { translate } from '../i18n/mobile-i18n' -import { formatHomeAgentTime, totalHomeStats } from './home-stats-total' - -const MINUTE = 60_000 -const HOUR = 60 * MINUTE -const DAY = 24 * HOUR +import { totalHomeStats } from './home-stats-total' describe('totalHomeStats', () => { it('sums every desktop instead of letting the last reply win', () => { @@ -46,20 +41,3 @@ describe('totalHomeStats', () => { expect(total).toEqual({ totalAgentsSpawned: 10, totalPRsCreated: 3, totalAgentTimeMs: 60_000 }) }) }) - -describe('formatHomeAgentTime', () => { - it('shows whole days once there is a day, without the hours', () => { - expect(formatHomeAgentTime(139 * DAY + 7 * HOUR + 30 * MINUTE, translate)).toBe('139d') - expect(formatHomeAgentTime(DAY, translate)).toBe('1d') - }) - - it('shows whole hours under a day', () => { - expect(formatHomeAgentTime(7 * HOUR + 59 * MINUTE, translate)).toBe('7h') - expect(formatHomeAgentTime(DAY - 1, translate)).toBe('23h') - }) - - it('shows minutes under an hour', () => { - expect(formatHomeAgentTime(42 * MINUTE + 59_000, translate)).toBe('42m') - expect(formatHomeAgentTime(0, translate)).toBe('0m') - }) -}) diff --git a/mobile/src/tasks/agent-launch-request.test.ts b/mobile/src/tasks/agent-launch-request.test.ts deleted file mode 100644 index 8ba6e67601e..00000000000 --- a/mobile/src/tasks/agent-launch-request.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readAgentLaunchCreateOutcome } from './agent-launch-request' - -const FALLBACK_DETAIL = - "Your default is a structured chat session, but its chat runtime isn't installed on this host (install it from a new chat tab in Orca); started a terminal agent instead." - -describe('readAgentLaunchCreateOutcome', () => { - it('surfaces why a chat default started a terminal', () => { - const reply = { - outcome: { kind: 'terminal', handle: 'term_1' }, - worktreeId: 'repo::/w', - receipt: { - mode: 'terminal', - preferred: 'structured', - reason: 'chat_runtime_not_installed', - detail: FALLBACK_DETAIL - } - } - expect(readAgentLaunchCreateOutcome(reply)).toEqual({ - worktreeId: 'repo::/w', - warning: FALLBACK_DETAIL - }) - }) -}) diff --git a/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts b/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts index e41c3e74fdf..82b0e0590ab 100644 --- a/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts +++ b/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts @@ -26,16 +26,6 @@ const BASE_ARGS = { } as const describe('terminal live accessory raw send', () => { - it('drops the bytes instead of sending while disconnected', async () => { - const { client, sendRequest } = captureClient() - - await expect( - sendTerminalLiveAccessoryRawBytes({ ...BASE_ARGS, client, connState: 'reconnecting' }) - ).resolves.toBe(false) - - expect(sendRequest).not.toHaveBeenCalled() - }) - it('drops the bytes when the terminal selection went stale mid-flush', async () => { const { client, sendRequest } = captureClient() diff --git a/mobile/src/theme/mobile-theme-contrast.test.ts b/mobile/src/theme/mobile-theme-contrast.test.ts deleted file mode 100644 index f1a9d94325a..00000000000 --- a/mobile/src/theme/mobile-theme-contrast.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { paletteForScheme } from './mobile-theme' - -function channelLuminance(channel: number): number { - const value = channel / 255 - return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4 -} - -function relativeLuminance(hex: string): number { - const red = Number.parseInt(hex.slice(1, 3), 16) - const green = Number.parseInt(hex.slice(3, 5), 16) - const blue = Number.parseInt(hex.slice(5, 7), 16) - return ( - 0.2126 * channelLuminance(red) + - 0.7152 * channelLuminance(green) + - 0.0722 * channelLuminance(blue) - ) -} - -function contrastRatio(foreground: string, background: string): number { - const lighter = Math.max(relativeLuminance(foreground), relativeLuminance(background)) - const darker = Math.min(relativeLuminance(foreground), relativeLuminance(background)) - return (lighter + 0.05) / (darker + 0.05) -} - -describe.each(['dark', 'light'] as const)('mobile text contrast (%s)', (scheme) => { - const colors = paletteForScheme(scheme) - - // Dark textMuted is desktop's --chat-foreground-faint (4.33:1 on bgRaised), so only page surfaces are held to 4.5. - it('keeps muted text readable on page and panel surfaces', () => { - for (const surface of [colors.bgBase, colors.bgPanel]) { - expect(contrastRatio(colors.textMuted, surface)).toBeGreaterThanOrEqual(4.5) - } - }) - - // WCAG 1.4.11: the edge is what marks a field, so it holds 3:1 on every surface fields sit on, and so does focus. - it('keeps a text field identifiable on the screen, a sheet and a sheet group', () => { - const surfaces = [ - colors.bgBase, - colors.bgPanel, - colors.sheetSurface, - colors.sheetGroup, - colors.composerSurface - ] - for (const surface of surfaces) { - expect(contrastRatio(colors.inputBorder, surface)).toBeGreaterThanOrEqual(3) - expect(contrastRatio(colors.accentBlue, surface)).toBeGreaterThanOrEqual(3) - } - expect(contrastRatio(colors.textMuted, colors.composerSurface)).toBeGreaterThanOrEqual(4.5) - }) - - // WCAG 1.4.11: the create button is an icon-only disc, so its glyph and its edge each hold 3:1. - it('keeps the floating create button and its glyph visible on the page', () => { - expect(contrastRatio(colors.createActionFill, colors.bgBase)).toBeGreaterThanOrEqual(3) - expect( - contrastRatio(colors.onCreateActionFill, colors.createActionFill) - ).toBeGreaterThanOrEqual(3) - }) - - it('keeps your own message readable on its bubble', () => { - expect( - contrastRatio(colors.chatForegroundStrong, colors.chatUserSurface) - ).toBeGreaterThanOrEqual(4.5) - }) -}) From 252b427dfd2481e19e9a9f496ff65424ad3a94e8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 11:58:15 -0800 Subject: [PATCH 14/23] Display private GitHub attachment images in fetched items (#39250) * Display private GitHub attachment images in fetched items * Keep attachment event identity aligned with committed renders * Complete GitHub image response type contracts * Return private image sources with accepted issue edits * Keep issue edits successful without optional display data * Cover unusable issue edit image responses * Keep optional GitHub image parsing from failing accepted saves * Fetch GitHub body images with the existing body read --- electron.vite.config.ts | 1 + .../github/body-image-read-adapters.test.ts | 154 ++++++++++++++ src/main/github/body-image-urls.test.ts | 138 +++++++++++++ src/main/github/body-image-urls.ts | 144 +++++++++++++ .../client-pr-conversation-requests.test.ts | 142 +++++++++++++ .../client/create/add-pr-review-comment.ts | 3 + .../github/client/fetch/get-pr-comments.ts | 11 +- .../client/fetch/pr-conversation-response.ts | 38 ++-- .../client/fetch/pr-review-threads-query.ts | 3 + .../client/map/review-comment-response.ts | 3 + src/main/github/issue-comment-image.test.ts | 74 +++++++ src/main/github/issue-comment.ts | 8 +- src/main/github/issue-details-query.ts | 10 +- src/main/github/issue-update.ts | 17 +- .../issue-work-item-details-fresh.test.ts | 101 ++++++++++ src/main/github/issue-work-item-details.ts | 83 +++++--- src/main/github/issues.test.ts | 50 +++++ .../project-view/body-image-mutations.test.ts | 170 ++++++++++++++++ .../project-view/issue-comment-mutations.ts | 4 + src/main/github/project-view/mutations.ts | 16 +- .../project-view/pull-request-mutation.ts | 19 +- .../github/project-view/work-item-details.ts | 54 +++-- src/main/github/pull-request-file-data.ts | 24 ++- src/main/github/work-item-details.ts | 38 ++-- .../api/gh-bridge-mutations-and-projects.ts | 5 +- src/preload/api/github-work-item-api.ts | 2 +- .../conversation-tab-comment-card.tsx | 1 + .../conversation-tab-description.tsx | 3 + .../conversation-tab-images.test.tsx | 110 ++++++++++ .../discuss-item/conversation-tab.tsx | 9 +- .../work-item-details-body-images.test.tsx | 155 ++++++++++++++ .../work-item-details-cache.ts | 8 +- .../github-item-dialog-issue-body.tsx | 5 +- .../github-item-dialog-pr-tabs.tsx | 5 +- .../SlugDialogBody.images.test.tsx | 106 ++++++++++ .../slug-dialog/SlugDialogBody.tsx | 10 +- .../github/github-work-item-edit-mutations.ts | 11 +- .../github-work-item-issue-target.test.ts | 101 +++++++++- .../conversation/comment-card.tsx | 1 + .../conversation/description.tsx | 3 + .../pull-request-page/conversation/tab.tsx | 9 +- .../pull-request-page/page/surface.tsx | 1 + .../pull-request-page/page/tabs-shell.tsx | 7 +- .../components/sidebar/CommentMarkdown.tsx | 95 ++++----- .../comment-markdown-element-renderers.tsx | 85 +++++--- ...mment-markdown-github-attachment-media.tsx | 41 +++- ...ent-markdown-github-image-sources.test.tsx | 189 ++++++++++++++++++ .../comment-markdown-github-image-urls.ts | 5 + .../store/github/comments/pr-comment-cache.ts | 1 + .../github/projects/project-row-actions.ts | 24 ++- .../task-records/github-task-records.test.ts | 44 ++++ src/shared/github/comment-types.ts | 2 + src/shared/github/project-result-types.ts | 2 +- src/shared/github/work-item-types.ts | 1 + 54 files changed, 2130 insertions(+), 216 deletions(-) create mode 100644 src/main/github/body-image-read-adapters.test.ts create mode 100644 src/main/github/body-image-urls.test.ts create mode 100644 src/main/github/body-image-urls.ts create mode 100644 src/main/github/issue-comment-image.test.ts create mode 100644 src/main/github/project-view/body-image-mutations.test.ts create mode 100644 src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-images.test.tsx create mode 100644 src/renderer/src/components/github-item-dialog/load-item-details/work-item-details-body-images.test.tsx create mode 100644 src/renderer/src/components/github-project/slug-dialog/SlugDialogBody.images.test.tsx create mode 100644 src/renderer/src/components/sidebar/comment-markdown-github-image-sources.test.tsx create mode 100644 src/renderer/src/components/sidebar/comment-markdown-github-image-urls.ts diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 23daba961e0..673eb8847e7 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -32,6 +32,7 @@ const BUNDLED_MAIN_DEPENDENCIES = new Set([ 'unified', 'remark-parse', 'remark-gfm', + 'hast-util-from-html-isomorphic', // Windows NSIS copies app.asar before external resources; bootstrap must not race resources/node_modules. 'zod' ]) diff --git a/src/main/github/body-image-read-adapters.test.ts b/src/main/github/body-image-read-adapters.test.ts new file mode 100644 index 00000000000..8dcd75701bc --- /dev/null +++ b/src/main/github/body-image-read-adapters.test.ts @@ -0,0 +1,154 @@ +import { beforeEach, expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ exec: vi.fn(), graphql: vi.fn() })) +vi.mock('./gh-utils', () => ({ + ghExecFileAsync: mocks.exec, + ghRepoExecOptions: () => ({}), + githubRepoContext: () => ({}) +})) +vi.mock('./rate-limit', () => ({ + repositoryRateLimitGuard: () => ({ blocked: false }), + noteRepositoryRateLimitSpend: () => {} +})) +vi.mock('./project-view/internals', () => ({ + assertPositiveInt: () => ({ ok: true }), + validateSlugArgs: () => ({ ok: true }), + projectGhExecOptions: () => ({}), + runGraphql: mocks.graphql +})) +import { getPRMetadata } from './pull-request-file-data' +import { getWorkItemDetailsBySlug } from './project-view/work-item-details' + +const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' +const html = + '' +const expectedMap = { + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' +} +beforeEach(() => { + mocks.exec.mockReset() + mocks.graphql.mockReset() +}) + +it('gets PR metadata images in its existing uncached full-media read', async () => { + mocks.exec.mockResolvedValueOnce({ + stdout: JSON.stringify({ body, body_html: html, head: { sha: 'head' } }) + }) + const metadata = await getPRMetadata('/repo', 7, { owner: 'acme', repo: 'widgets' }) + expect(metadata).toMatchObject({ body, headSha: 'head', bodyImageUrls: expectedMap }) + expect(mocks.exec).toHaveBeenCalledTimes(1) + expect(mocks.exec.mock.calls[0][0]).toEqual([ + 'api', + '-H', + 'Accept: application/vnd.github.full+json', + 'repos/acme/widgets/pulls/7' + ]) +}) + +it.each(['issue', 'pr'] as const)( + 'gets slug %s body and comment images in one existing read', + async (type) => { + mocks.graphql.mockResolvedValueOnce({ + ok: true, + data: { + repository: { + [type === 'issue' ? 'issue' : 'pullRequest']: { + id: 'ITEM', + body, + bodyHTML: html, + comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] } + } + } + } + }) + const result = await getWorkItemDetailsBySlug({ + owner: 'acme', + repo: 'widgets', + number: 7, + type + }) + expect(result.ok && result.details.body).toBe(body) + expect(result.ok && result.details.bodyImageUrls).toEqual(expectedMap) + expect(result.ok && result.details.comments[0].bodyImageUrls).toEqual(expectedMap) + expect(mocks.graphql).toHaveBeenCalledTimes(1) + expect(mocks.exec).not.toHaveBeenCalled() + } +) + +it.each(['issue', 'pr'] as const)( + 'recovers available slug %s data without trusting failed HTML', + async (type) => { + const root = type === 'issue' ? 'issue' : 'pullRequest' + mocks.graphql.mockResolvedValueOnce({ + ok: false, + error: { type: 'unknown', message: 'field error' }, + raw: { + stdout: JSON.stringify({ + data: { + repository: { + [root]: { + id: 'ITEM', + body, + bodyHTML: html, + comments: { + nodes: [ + { databaseId: 1, body, bodyHTML: html }, + { databaseId: 2, body, bodyHTML: html } + ] + } + } + } + }, + errors: [ + { path: ['repository', root, 'bodyHTML'] }, + { path: ['repository', root, 'comments', 'nodes', 0, 'bodyHTML'] } + ] + }), + stderr: '' + } + }) + const result = await getWorkItemDetailsBySlug({ + owner: 'acme', + repo: 'widgets', + number: 7, + type + }) + expect(result.ok && result.details.body).toBe(body) + expect(result.ok && result.details.bodyImageUrls).toBeUndefined() + expect(result.ok && result.details.comments[0].bodyImageUrls).toBeUndefined() + expect(result.ok && result.details.comments[1].bodyImageUrls).toEqual(expectedMap) + expect(mocks.graphql).toHaveBeenCalledTimes(1) + expect(mocks.exec).not.toHaveBeenCalled() + } +) + +it.each(['null parent', 'required field', 'pathless'] as const)( + 'keeps the original slug failure for %s', + async (input) => { + const error = { type: 'unknown', message: 'original failure' } + mocks.graphql.mockResolvedValueOnce({ + ok: false, + error, + raw: { + stderr: '', + stdout: JSON.stringify({ + data: { + repository: { issue: input === 'null parent' ? null : { body, bodyHTML: html } } + }, + errors: [ + { + path: + input === 'pathless' + ? undefined + : ['repository', 'issue', input === 'required field' ? 'body' : 'bodyHTML'] + } + ] + }) + } + }) + await expect( + getWorkItemDetailsBySlug({ owner: 'acme', repo: 'widgets', number: 7, type: 'issue' }) + ).resolves.toEqual({ ok: false, error: { type: 'unknown', message: 'original failure' } }) + } +) diff --git a/src/main/github/body-image-urls.test.ts b/src/main/github/body-image-urls.test.ts new file mode 100644 index 00000000000..a9cb4b32f46 --- /dev/null +++ b/src/main/github/body-image-urls.test.ts @@ -0,0 +1,138 @@ +import type * as HtmlParser from 'hast-util-from-html-isomorphic' +import type { Root, RootContent } from 'hast' +import { describe, expect, it, vi } from 'vitest' +const traversal = vi.hoisted(() => ({ enabled: false, parses: 0, children: 0, fail: false })) +vi.mock('hast-util-from-html-isomorphic', async (load) => { + const actual = await load() + return { + ...actual, + fromHtmlIsomorphic: (...args: Parameters) => { + if (traversal.fail) { + throw new Error('Optional image HTML could not be parsed') + } + const tree = actual.fromHtmlIsomorphic(...args) + if (!traversal.enabled) { + return tree + } + traversal.parses++ + const pending: (Root | RootContent)[] = [tree] + while (pending.length) { + const node = pending.pop()! + if (!('children' in node)) { + continue + } + const children = node.children + pending.push(...children) + Object.defineProperty(node, 'children', { + get: () => { + traversal.children++ + return children + } + }) + } + return tree + } + } +}) +import { githubBodyImageUrls } from './body-image-urls' + +const original = 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488' +const signed = + 'https://private-user-images.githubusercontent.com/1/2-ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST&download=1' + +describe('GitHub body image sources', () => { + it.each([ + { body: `![shot](${original})`, html: true }, + { body: true, html: `` } + ])('ignores unusable optional representations ($body, $html)', ({ body, html }) => { + expect(githubBodyImageUrls(body, html)).toBeUndefined() + }) + + it('skips HTML parsing when the Markdown has no attachment candidates', () => { + traversal.enabled = true + traversal.parses = 0 + try { + expect(githubBodyImageUrls('A plain comment', ``)).toBeUndefined() + expect(traversal.parses).toBe(0) + } finally { + traversal.enabled = false + } + }) + + it('leaves the optional map absent if HTML extraction fails', () => { + traversal.fail = true + try { + expect(githubBodyImageUrls(`![shot](${original})`, ``)).toBeUndefined() + } finally { + traversal.fail = false + } + }) + + it('matches rendered images to canonical assets without changing editable Markdown', () => { + const body = `![shot](${original})\n\n![missing](https://github.com/user-attachments/assets/cc11040a-fb66-4289-927f-547b16dfc488)\n\`https://github.com/user-attachments/assets/dd11040a-fb66-4289-927f-547b16dfc488\`` + const html = `https://private-user-images.githubusercontent.com/1/dd11040a-fb66-4289-927f-547b16dfc488.png` + expect(githubBodyImageUrls(body, html)).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': signed, + 'https://github.enterprise/team/repo/assets/42/ab11040a-fb66-4289-927f-547b16dfc488': + 'https://github.enterprise/storage/ab11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(githubBodyImageUrls(body, undefined)).toBeUndefined() + expect(githubBodyImageUrls(`![public](${original})`, ``)).toBeUndefined() + expect( + githubBodyImageUrls( + body, + '' + ) + ).toBeUndefined() + }) + + it('bounds candidate validation and indexed lookups at N and 10N', () => { + for (const n of [100, 1000]) { + const ids = Array.from( + { length: n }, + (_, i) => `ce11040a-fb66-4289-927f-${String(i).padStart(12, '0')}` + ) + const body = ids + .map((id) => `![shot](https://github.com/user-attachments/assets/${id})`) + .join('\n') + const html = ids + .map( + (id) => + `` + ) + .join('\n') + traversal.enabled = true + traversal.parses = 0 + traversal.children = 0 + const pathname = vi.spyOn(URL.prototype, 'pathname', 'get') + const originalGet = Map.prototype.get + let lookups = 0 + Map.prototype.get = function (this: Map, key: unknown) { + if (typeof key === 'string' && key.startsWith('ce11040a-')) { + lookups++ + } + return originalGet.call(this, key) + } + try { + const result = githubBodyImageUrls(body, html) + expect(Object.keys(result ?? {})).toHaveLength(n) + // Each candidate and original is checked once, then each original gets one indexed lookup. + expect(pathname.mock.calls.length).toBeLessThanOrEqual(3 * n) + expect(lookups).toBe(n) + expect(traversal.parses).toBe(1) + expect(traversal.children).toBeLessThanOrEqual(n + 1) + expect( + result?.[ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-000000000000' + ] + ).toBe( + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-000000000000.png?jwt=TEST' + ) + } finally { + traversal.enabled = false + Map.prototype.get = originalGet + pathname.mockRestore() + } + } + }) +}) diff --git a/src/main/github/body-image-urls.ts b/src/main/github/body-image-urls.ts new file mode 100644 index 00000000000..c81f9a7952e --- /dev/null +++ b/src/main/github/body-image-urls.ts @@ -0,0 +1,144 @@ +import { fromHtmlIsomorphic } from 'hast-util-from-html-isomorphic' +import type { Root, RootContent } from 'hast' + +const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' +const githubBodyAssetPath = new RegExp(`/assets/(?:\\d+/)?(${UUID})$`, 'i') + +export function githubBodyImageCandidates(body: string): Map { + const originals = new Map() + for (const match of body.matchAll(/https:\/\/[^\s<>"'`()[\]]+/g)) { + if (!match[0].includes('/assets/')) { + continue + } + try { + const url = new URL(match[0]) + if (githubBodyAssetPath.test(url.pathname)) { + originals.set(match[0], url) + } + } catch { + // An invalid Markdown URL cannot identify an attachment. + } + } + return originals +} + +const imageId = new RegExp(UUID, 'i') +export const GITHUB_BODY_MEDIA_TYPE = 'Accept: application/vnd.github.full+json' + +type GitHubBodyHtmlObject = Record + +function isGitHubBodyHtmlObject(value: unknown): value is GitHubBodyHtmlObject { + return value !== null && typeof value === 'object' +} + +export function removeFailedGitHubBodyHtml( + data: unknown, + errors: T[] | undefined +): T[] | undefined { + const isIndex = (value: unknown): boolean => + typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 + return errors?.filter((error) => { + if (!error || typeof error !== 'object' || !('path' in error)) { + return true + } + const path = error.path + if ( + !Array.isArray(path) || + path[0] !== 'repository' || + (path[1] !== 'issue' && path[1] !== 'pullRequest') || + path.at(-1) !== 'bodyHTML' + ) { + return true + } + const owned = + path.length === 3 || + (path.length === 6 && + (path[2] === 'comments' || (path[1] === 'pullRequest' && path[2] === 'reviews')) && + path[3] === 'nodes' && + isIndex(path[4])) || + (path.length === 9 && + path[1] === 'pullRequest' && + path[2] === 'reviewThreads' && + path[3] === 'nodes' && + isIndex(path[4]) && + path[5] === 'comments' && + path[6] === 'nodes' && + isIndex(path[7])) + if (!owned) { + return true + } + let target = data + for (const part of path.slice(0, -1)) { + if (!isGitHubBodyHtmlObject(target) || (typeof part === 'number' && !Array.isArray(target))) { + return true + } + target = target[part] + } + if (!isGitHubBodyHtmlObject(target) || typeof target.body !== 'string') { + return true + } + delete target.bodyHTML + return false + }) +} + +export function githubBodyMediaHeaders(body: string): string[] { + return githubBodyImageCandidates(body).size ? ['-H', GITHUB_BODY_MEDIA_TYPE] : [] +} + +/** Keep short-lived display URLs separate from editable Markdown and persisted item metadata. */ +export function githubBodyImageUrls( + body: unknown, + html: unknown +): Record | undefined { + if (typeof body !== 'string' || typeof html !== 'string' || !html) { + return undefined + } + try { + const originals = githubBodyImageCandidates(body) + if (!originals.size) { + return undefined + } + + const signed = new Map() + const pending: (Root | RootContent)[] = [fromHtmlIsomorphic(html, { fragment: true })] + while (pending.length) { + const node = pending.pop()! + if ('children' in node) { + pending.push(...node.children) + } + if (node.type !== 'element' || node.tagName !== 'img') { + continue + } + const src = node.properties.src + if (typeof src !== 'string') { + continue + } + try { + const url = new URL(src) + const id = url.pathname.match(imageId)?.[0].toLowerCase() + if (id && url.protocol === 'https:') { + signed.set(id, url) + } + } catch { + // Relative or malformed HTML sources do not supply a signed attachment URL. + } + } + + const result: Record = {} + for (const [original, url] of originals) { + const id = url.pathname.match(githubBodyAssetPath)![1].toLowerCase() + const display = signed.get(id) + if ( + display && + display.href !== original && + (display.hostname.endsWith('.githubusercontent.com') || display.host === url.host) + ) { + result[original] = display.href + } + } + return Object.keys(result).length ? result : undefined + } catch { + return undefined + } +} diff --git a/src/main/github/client-pr-conversation-requests.test.ts b/src/main/github/client-pr-conversation-requests.test.ts index 65a657cc6e5..84d729a97ec 100644 --- a/src/main/github/client-pr-conversation-requests.test.ts +++ b/src/main/github/client-pr-conversation-requests.test.ts @@ -98,6 +98,8 @@ describe('PR conversation request reuse', () => { expect(comments.map((c) => c.body)).toEqual(['Conversation', 'Review summary']) expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual([ 'api', + '-H', + 'Accept: application/vnd.github.full+json', 'repos/acme/widgets/pulls/7/reviews?per_page=100' ]) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) @@ -159,4 +161,144 @@ describe('PR conversation request reuse', () => { ['me', true] ]) }) + it.each([0, 100, 1000])( + 'gets image maps in the existing conversation request (%s bodies)', + async (n) => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const imageComments = Array.from({ length: n }, (_, i) => ({ + ...comment, + id: `IMAGE_${i}`, + databaseId: i, + body, + bodyHTML: + '', + path: 'file.ts' + })) + const threads = Array.from({ length: n / 100 }, (_, i) => ({ + id: `THREAD_${i}`, + isResolved: false, + line: 1, + startLine: null, + originalLine: 1, + originalStartLine: null, + comments: { nodes: imageComments.slice(i * 100, (i + 1) * 100) } + })) + ghExecFileAsyncMock.mockResolvedValueOnce( + response({ + comments: { nodes: [comment] }, + reviews: { nodes: [] }, + reviewThreads: { nodes: threads } + }) + ) + const result = await getPRComments('/repo', 7, { ...options, noCache: true }) + // One request owns all selected bodies, independent of their image population. + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(result.filter((c) => c.path === 'file.ts')).toHaveLength(n) + if (n === 0) { + return + } + expect(result.find((c) => c.id === 0)?.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(result.find((c) => c.id === 0)?.body).toBe(body) + } + ) + + it.each([false, true])( + 'holds the existing permit until the paired command settles (reject: %s)', + async (reject) => { + let settle!: (result: { stdout: string }) => void + let fail!: (error: Error) => void + const pending = new Promise<{ stdout: string }>((resolve, reject) => { + settle = resolve + fail = reject + }) + let started!: () => void + const commandStarted = new Promise((resolve) => { + started = resolve + }) + ghExecFileAsyncMock.mockImplementationOnce(() => { + started() + return pending + }) + const read = getPRComments('/repo', 7, { ...options, noCache: true }) + await commandStarted + expect(clientMocks.acquireMock).toHaveBeenCalledTimes(1) + expect(clientMocks.releaseMock).not.toHaveBeenCalled() + const raw = response({ + comments: { nodes: [comment] }, + reviews: { nodes: [] }, + reviewThreads: { nodes: [] } + }) + if (reject) { + fail(Object.assign(new Error('Partial GraphQL response'), raw)) + } else { + settle(raw) + } + const result = await read + expect(result).toMatchObject([{ body: 'Conversation' }]) + expect(clientMocks.releaseMock).toHaveBeenCalledTimes(1) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(result[0].bodyImageUrls).toBeUndefined() + } + ) + + it('keeps usable raw fields and siblings when optional HTML errors, without a fallback request', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const html = + '' + const partial = response( + { + comments: { nodes: [{ ...comment, body, bodyHTML: html }] }, + reviews: { nodes: [] }, + reviewThreads: { + nodes: [ + { + id: 'THREAD', + isResolved: false, + line: 1, + startLine: null, + originalLine: 1, + originalStartLine: null, + comments: { + nodes: [ + { ...comment, databaseId: 11, body, bodyHTML: html, path: 'file.ts' }, + { ...comment, databaseId: 12, body, bodyHTML: html, path: 'file.ts' } + ] + } + } + ] + } + }, + [ + { path: ['repository', 'pullRequest', 'comments', 'nodes', 0, 'bodyHTML'] }, + { + path: [ + 'repository', + 'pullRequest', + 'reviewThreads', + 'nodes', + 0, + 'comments', + 'nodes', + 0, + 'bodyHTML' + ] + } + ] + ) + ghExecFileAsyncMock.mockRejectedValueOnce(Object.assign(new Error('GraphQL error'), partial)) + const result = await getPRComments('/repo', 7, { ...options, noCache: true }) + expect(result.map((c) => c.body)).toEqual([body, body, body]) + expect(result.find((c) => c.id === 10)?.bodyImageUrls).toBeUndefined() + expect(result.find((c) => c.id === 11)?.bodyImageUrls).toBeUndefined() + expect(result.find((c) => c.id === 12)?.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + }) }) diff --git a/src/main/github/client/create/add-pr-review-comment.ts b/src/main/github/client/create/add-pr-review-comment.ts index 6b2f4016c66..25d298241ad 100644 --- a/src/main/github/client/create/add-pr-review-comment.ts +++ b/src/main/github/client/create/add-pr-review-comment.ts @@ -1,3 +1,4 @@ +import { githubBodyMediaHeaders } from '../../body-image-urls' import type { GitHubCommentResult, GitHubPRReviewCommentInput @@ -31,6 +32,7 @@ export async function addPRReviewComment( try { const fields = [ 'api', + ...githubBodyMediaHeaders(args.body), '-X', 'POST', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${args.prNumber}/comments`, @@ -97,6 +99,7 @@ export async function addPRReviewCommentReply( const { stdout } = await ghExecFileAsync( [ 'api', + ...githubBodyMediaHeaders(body), '-X', 'POST', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${prNumber}/comments/${commentId}/replies`, diff --git a/src/main/github/client/fetch/get-pr-comments.ts b/src/main/github/client/fetch/get-pr-comments.ts index 8401c219dbd..be44913966c 100644 --- a/src/main/github/client/fetch/get-pr-comments.ts +++ b/src/main/github/client/fetch/get-pr-comments.ts @@ -1,3 +1,4 @@ +import { GITHUB_BODY_MEDIA_TYPE } from '../../body-image-urls' import type { PRComment } from '../../../../shared/github/comment-types' import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' import { extractExecError } from '../../../git/exec-error' @@ -31,8 +32,6 @@ async function readPRComments( let restBudgetFailed = false try { if (ownerRepo) { - // Explicit refresh bypasses the polling cache. - const cacheArgs = options?.noCache ? [] : ['--cache', '60s'] const base = `repos/${ownerRepo.owner}/${ownerRepo.repo}` // Retain successful comment sources when another endpoint fails. @@ -60,9 +59,9 @@ async function readPRComments( ) } catch (error) { // gh exits nonzero for partial GraphQL errors; keep the successful sources. - const { stdout } = extractExecError(error) + const { stdout, stderr } = extractExecError(error) threadsResult = stdout ? { stdout } : null - console.warn('Failed to fetch review threads:', error) + console.warn('Failed to fetch review threads:', stderr) } } @@ -85,12 +84,12 @@ async function readPRComments( try { noteRepositoryRateLimitSpend(ownerRepo, 'core', reviews ? 1 : 2, ghOptions) const [{ stdout }, viewerLogin] = await Promise.all([ - ghExecFileAsync(['api', ...cacheArgs, endpoint], ghOptions), + ghExecFileAsync(['api', '-H', GITHUB_BODY_MEDIA_TYPE, endpoint], ghOptions), reviews ? null : readViewerLogin(ghOptions) ]) return parseRestPRComments(stdout, reviews, viewerLogin) } catch (error) { - console.warn('Failed to fetch PR conversation fallback:', error) + console.warn('Failed to fetch PR conversation fallback:', extractExecError(error).stderr) return [] } } diff --git a/src/main/github/client/fetch/pr-conversation-response.ts b/src/main/github/client/fetch/pr-conversation-response.ts index 7dfbac2e82a..1593a486f82 100644 --- a/src/main/github/client/fetch/pr-conversation-response.ts +++ b/src/main/github/client/fetch/pr-conversation-response.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../../body-image-urls' import type { Nodes } from 'mdast' import { z } from 'zod' import remarkParse from 'remark-parse' @@ -14,6 +15,7 @@ const commentSchema = z.object({ .object({ __typename: z.string().optional(), login: z.string(), avatarUrl: z.string() }) .nullable(), body: z.string().nullish(), + bodyHTML: z.unknown().optional(), createdAt: z.string(), submittedAt: z.string().nullish(), url: z.string(), @@ -82,11 +84,12 @@ function hasDatabaseId( function mapGraphQLComment( comment: z.infer & { databaseId: number } ): PRComment { - return { + const mapped: PRComment = { id: comment.databaseId, author: comment.author?.login ?? 'ghost', authorAvatarUrl: comment.author?.avatarUrl ?? '', body: comment.body ?? '', + bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML), createdAt: comment.submittedAt ?? comment.createdAt, url: comment.url, isBot: comment.author?.__typename === 'Bot', @@ -94,6 +97,7 @@ function mapGraphQLComment( reactionSubjectId: comment.id, reactions: mapGraphQLReactionGroups(comment.reactionGroups) } + return mapped } const reviewMarkdown = unified().use(remarkParse) @@ -123,10 +127,11 @@ export function parsePRConversationResponse(stdout: string): { reviewComments: PRComment[] } { const envelope = envelopeSchema.parse(JSON.parse(stdout)) + const errors = removeFailedGitHubBodyHtml(envelope.data, envelope.errors) const pr = envelope.data?.repository?.pullRequest const failed = (source: string): boolean => Boolean( - envelope.errors?.some( + errors?.some( (error) => !error.path?.length || !error.path.includes('pullRequest') || error.path[2] === source ) @@ -149,19 +154,20 @@ export function parsePRConversationResponse(stdout: string): { reviewComments: threads.success ? threads.data.nodes.flatMap((thread) => thread - ? thread.comments.nodes.filter(hasDatabaseId).map((c) => ({ - ...mapGraphQLComment(c), - // Left-side threads count old-file lines, which the shared tail numbering cannot place. - ...(c === thread.comments.nodes[0] && thread.diffSide !== 'LEFT' - ? rootDiffHunk(thread.rootHunk) - : {}), - path: c.path, - threadId: thread.id, - isResolved: thread.isResolved, - isOutdated: thread.line == null, - line: thread.line ?? thread.originalLine ?? undefined, - startLine: thread.startLine ?? thread.originalStartLine ?? undefined - })) + ? thread.comments.nodes.filter(hasDatabaseId).map((c) => + Object.assign(mapGraphQLComment(c), { + // Left-side threads count old-file lines, which the shared tail numbering cannot place. + ...(c === thread.comments.nodes[0] && thread.diffSide !== 'LEFT' + ? rootDiffHunk(thread.rootHunk) + : {}), + path: c.path, + threadId: thread.id, + isResolved: thread.isResolved, + isOutdated: thread.line == null, + line: thread.line ?? thread.originalLine ?? undefined, + startLine: thread.startLine ?? thread.originalStartLine ?? undefined + }) + ) : [] ) : [] @@ -181,6 +187,7 @@ const restCommentSchema = z.object({ .object({ login: z.string(), avatar_url: z.string(), type: z.string().optional() }) .nullable(), body: z.string().nullish(), + body_html: z.unknown().optional(), created_at: z.string().optional(), submitted_at: z.string().nullish(), html_url: z.string() @@ -200,6 +207,7 @@ export function parseRestPRComments( author: c.user?.login ?? 'ghost', authorAvatarUrl: c.user?.avatar_url ?? '', body: c.body ?? '', + bodyImageUrls: githubBodyImageUrls(c.body, c.body_html), createdAt: (reviews ? c.submitted_at : c.created_at) ?? '', url: c.html_url, isBot: c.user?.type === 'Bot', diff --git a/src/main/github/client/fetch/pr-review-threads-query.ts b/src/main/github/client/fetch/pr-review-threads-query.ts index d2ba6450133..0e608c43974 100644 --- a/src/main/github/client/fetch/pr-review-threads-query.ts +++ b/src/main/github/client/fetch/pr-review-threads-query.ts @@ -23,6 +23,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt url viewerDidAuthor @@ -44,6 +45,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt url viewerDidAuthor @@ -62,6 +64,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt submittedAt url diff --git a/src/main/github/client/map/review-comment-response.ts b/src/main/github/client/map/review-comment-response.ts index f13a69f3632..f17f653ba0e 100644 --- a/src/main/github/client/map/review-comment-response.ts +++ b/src/main/github/client/map/review-comment-response.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls } from '../../body-image-urls' import type { PRComment } from '../../../../shared/github/comment-types' export function mapReviewCommentResponse( data: { @@ -5,6 +6,7 @@ export function mapReviewCommentResponse( node_id?: string | null user: { login: string; avatar_url: string; type?: string } | null body?: string + body_html?: string | null created_at?: string html_url?: string path?: string @@ -22,6 +24,7 @@ export function mapReviewCommentResponse( author: data.user?.login ?? 'You', authorAvatarUrl: data.user?.avatar_url ?? '', body: data.body ?? body, + bodyImageUrls: githubBodyImageUrls(data.body ?? body, data.body_html), createdAt: data.created_at ?? new Date().toISOString(), url: data.html_url ?? '', isBot: data.user?.type === 'Bot', diff --git a/src/main/github/issue-comment-image.test.ts b/src/main/github/issue-comment-image.test.ts new file mode 100644 index 00000000000..c22f437bd88 --- /dev/null +++ b/src/main/github/issue-comment-image.test.ts @@ -0,0 +1,74 @@ +import { expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ exec: vi.fn() })) +vi.mock('./gh-utils', () => ({ + ghExecFileAsync: mocks.exec, + acquire: async () => {}, + release: () => {}, + classifyGhError: () => ({ type: 'unknown' }) +})) +vi.mock('./github-api-repository', () => ({ + resolveGitHubRepoExecution: async () => ({ + ownerRepo: { owner: 'acme', repo: 'widgets' }, + ghOptions: {} + }) +})) +import { addIssueComment } from './issue-comment' +import { addPRReviewComment, addPRReviewCommentReply } from './client/create/add-pr-review-comment' + +it('returns signed display sources immediately after posting the original Markdown', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + mocks.exec.mockResolvedValue({ + stdout: JSON.stringify({ + id: 1, + user: null, + body, + body_html: + '' + }) + }) + const result = await addIssueComment('/repo', 42, body) + expect(mocks.exec.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json') + expect(mocks.exec.mock.calls[0][1].stdin).toBe(JSON.stringify({ body })) + expect(result.ok && result.comment.body).toBe(body) + expect(result.ok && result.comment.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) +}) + +it.each(['review', 'reply'])( + 'returns paired image sources immediately for %s posts', + async (kind) => { + mocks.exec.mockClear() + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + mocks.exec.mockResolvedValue({ + stdout: JSON.stringify({ + id: 1, + body, + user: null, + body_html: + '' + }) + }) + const result = + kind === 'review' + ? await addPRReviewComment({ + repoPath: '/repo', + prNumber: 7, + body, + commitId: 'head', + path: 'file.ts', + line: 1 + }) + : await addPRReviewCommentReply('/repo', 7, 1, body) + expect(result.ok && result.comment.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(mocks.exec.mock.calls[0][0]).toContain( + 'body=![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + ) + } +) diff --git a/src/main/github/issue-comment.ts b/src/main/github/issue-comment.ts index 88f5f642c63..7f3c2a11f98 100644 --- a/src/main/github/issue-comment.ts +++ b/src/main/github/issue-comment.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from './body-image-urls' import type { GitHubCommentResult, PRComment } from '../../shared/github/comment-types' import type { IssueSourcePreference } from '../../shared/repo-types' import type { LocalGitExecOptions, OwnerRepo } from './gh-utils' @@ -41,6 +42,7 @@ export async function addIssueComment( const { stdout } = await ghExecFileAsync( [ 'api', + ...githubBodyMediaHeaders(body), '-X', 'POST', `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}/comments`, @@ -49,14 +51,15 @@ export async function addIssueComment( ], { ...ghOptions, stdin: JSON.stringify({ body }) } ) - const data = JSON.parse(stdout) as { + const data: { id?: number node_id?: string | null user: { login: string; avatar_url: string; type?: string } | null body?: string + body_html?: string | null created_at?: string html_url?: string - } + } = JSON.parse(stdout) if (typeof data.id !== 'number' || !Number.isSafeInteger(data.id) || data.id < 1) { return codeHostFailure('github.unexpectedResponse') } @@ -66,6 +69,7 @@ export async function addIssueComment( author: data.user?.login ?? 'You', authorAvatarUrl: data.user?.avatar_url ?? '', body: data.body ?? body, + bodyImageUrls: githubBodyImageUrls(data.body ?? body, data.body_html), createdAt: data.created_at ?? new Date().toISOString(), url: data.html_url ?? '', isBot: data.user?.type === 'Bot' diff --git a/src/main/github/issue-details-query.ts b/src/main/github/issue-details-query.ts index e22da93d914..5d6921884f0 100644 --- a/src/main/github/issue-details-query.ts +++ b/src/main/github/issue-details-query.ts @@ -14,6 +14,7 @@ export const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $numb pageInfo { hasNextPage } } body + bodyHTML assignees(first: 50) { nodes { login avatarUrl(size: 48) ... on User { name } } pageInfo { hasNextPage } @@ -26,6 +27,7 @@ export const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $numb nodes { databaseId body + bodyHTML createdAt url viewerDidAuthor @@ -62,13 +64,15 @@ export type GraphQLIssueDetailsResponse = { repository?: { issue?: { body?: string | null + bodyHTML?: unknown assignees?: { nodes?: (Partial | null)[] | null } participants?: { nodes?: GitHubAssignableUser[] } comments?: { pageInfo?: { hasNextPage: boolean } - nodes?: { + nodes?: ({ databaseId?: number | null body?: string | null + bodyHTML?: unknown createdAt?: string | null url?: string | null viewerDidAuthor?: boolean | null @@ -77,10 +81,10 @@ export type GraphQLIssueDetailsResponse = { avatarUrl?: string | null __typename?: string } | null - }[] + } | null)[] } } | null } | null } - errors?: { message?: string }[] + errors?: { message?: string; path?: unknown }[] } diff --git a/src/main/github/issue-update.ts b/src/main/github/issue-update.ts index fa72852bde7..4a5fbe0bb63 100644 --- a/src/main/github/issue-update.ts +++ b/src/main/github/issue-update.ts @@ -9,6 +9,7 @@ import { import { acquire, classifyGhError, ghExecFileAsync, release } from './gh-utils' import { codeHostFailure, combinedClassifiedFailure } from '../../shared/code-host-failure-copy' import type { ClassifiedError } from '../../shared/classified-error' +import { githubBodyImageUrls, githubBodyMediaHeaders } from './body-image-urls' export async function updateIssue( repoPath: string, @@ -18,7 +19,7 @@ export async function updateIssue( localGitOptions: LocalGitExecOptions = {}, preference?: IssueSourcePreference, ownerRepoOverride?: GitHubApiRepository | null -): Promise<{ ok: true } | { ok: false; error: string }> { +): Promise<{ ok: true; bodyImageUrls?: Record } | { ok: false; error: string }> { const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( repoPath, ownerRepoOverride ?? @@ -40,6 +41,7 @@ export async function updateIssue( const repo = `${ownerRepo.owner}/${ownerRepo.repo}` const errors: ClassifiedError[] = [] + let bodyImageUrls: Record | undefined if (updates.state) { await acquire() @@ -69,17 +71,26 @@ export async function updateIssue( if (updates.body !== undefined) { await acquire() try { - await ghExecFileAsync( + const { stdout } = await ghExecFileAsync( [ 'api', '-X', 'PATCH', `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}`, + ...githubBodyMediaHeaders(updates.body), '--input', '-' ], { ...ghOptions, stdin: JSON.stringify({ body: updates.body }) } ) + try { + const response: { body?: string; body_html?: string } = JSON.parse(stdout) + if (response?.body === updates.body) { + bodyImageUrls = githubBodyImageUrls(response.body, response.body_html) + } + } catch { + // Optional display data cannot turn an accepted edit into a failed write. + } } catch (err) { const stderr = err instanceof Error ? err.message : String(err) errors.push(classifyGhError(stderr)) @@ -127,5 +138,5 @@ export async function updateIssue( if (errors.length > 0) { return combinedClassifiedFailure(errors) } - return { ok: true } + return { ok: true, bodyImageUrls } } diff --git a/src/main/github/issue-work-item-details-fresh.test.ts b/src/main/github/issue-work-item-details-fresh.test.ts index 9bdecc5b75b..8d735c87693 100644 --- a/src/main/github/issue-work-item-details-fresh.test.ts +++ b/src/main/github/issue-work-item-details-fresh.test.ts @@ -127,3 +127,104 @@ describe('explicit task refresh conversation reads', () => { await expect(getIssueBodyAndComments('/repo', 42, repository, null, {}, true)).rejects.toThrow() }) }) + +it('pairs issue and comment image sources through collapsed and REST detail reads', async () => { + mocks.exec.mockReset() + mocks.guard.mockReturnValue({ blocked: false }) + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const html = + '' + mocks.exec.mockImplementation(async (args: string[]) => ({ + stdout: JSON.stringify( + args.includes('graphql') + ? { + data: { + repository: { + issue: { + body, + bodyHTML: html, + comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] } + } + } + } + } + : args.some((arg) => arg.includes('/timeline?')) + ? [] + : args.some((arg) => arg.includes('/comments?')) + ? [{ id: 1, user: null, body, body_html: html }] + : { body, body_html: html } + ) + })) + const collapsed = await getIssueDetailsViaGraphQL('/repo', 42, repository) + const rest = await getIssueBodyAndComments('/repo', 42, repository) + for (const details of [collapsed!, rest]) { + expect(details.body).toBe(body) + expect(details.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(details.comments[0].bodyImageUrls).toEqual(details.bodyImageUrls) + } + for (const [args] of mocks.exec.mock.calls.filter(([args]) => + args.some((arg: string) => /\/issues\/42(?:$|\/comments)/.test(arg)) + )) { + expect(args).toContain('Accept: application/vnd.github.full+json') + expect(args).not.toContain('--cache') + } +}) + +it.each(['optional HTML', 'required body', 'pathless', 'rejection without errors'] as const)( + 'admits rejected issue stdout only for available optional HTML failures (%s)', + async (input) => { + mocks.exec.mockReset() + mocks.guard.mockReturnValue({ blocked: false }) + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const html = + '' + mocks.exec.mockRejectedValueOnce( + Object.assign(new Error('GraphQL failed'), { + stdout: JSON.stringify({ + data: { + repository: { + issue: { + body, + bodyHTML: html, + comments: { + pageInfo: { hasNextPage: false }, + nodes: [{ databaseId: 1, body, bodyHTML: html }] + } + } + } + }, + errors: + input === 'rejection without errors' + ? undefined + : [ + { + path: + input === 'pathless' + ? undefined + : ['repository', 'issue', input === 'required body' ? 'body' : 'bodyHTML'] + } + ] + }) + }) + ) + mocks.exec.mockResolvedValueOnce({ stdout: '[]' }) + const result = await getIssueDetailsViaGraphQL('/repo', 42, repository, null, {}, false, true) + if (input !== 'optional HTML') { + expect(result).toBeNull() + expect(mocks.exec).toHaveBeenCalledTimes(1) + return + } + expect(result?.body).toBe(body) + expect(result?.bodyImageUrls).toBeUndefined() + expect(result?.comments[0].bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(mocks.exec).toHaveBeenCalledTimes(2) + } +) diff --git a/src/main/github/issue-work-item-details.ts b/src/main/github/issue-work-item-details.ts index e12b34ba0f9..7b44631ac7a 100644 --- a/src/main/github/issue-work-item-details.ts +++ b/src/main/github/issue-work-item-details.ts @@ -1,3 +1,9 @@ +import { + GITHUB_BODY_MEDIA_TYPE, + githubBodyImageUrls, + removeFailedGitHubBodyHtml +} from './body-image-urls' +import { extractExecError } from '../git/exec-error' import type { GitHubIssueTimelineItem, PRComment } from '../../shared/github/comment-types' import type { GitHubAssignableUser } from '../../shared/github/pull-request-types' import { @@ -19,6 +25,7 @@ import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-l export type CollapsedIssueDetails = { item?: MainWorkItem body: string + bodyImageUrls?: Record comments: PRComment[] assignees: string[] assigneeUsers: GitHubAssignableUser[] @@ -47,25 +54,33 @@ export async function getIssueDetailsViaGraphQL( } try { noteRepositoryRateLimitSpend(repository, 'graphql', 1, ghOptions) - const { stdout } = await ghExecFileAsync( - [ - 'api', - 'graphql', - '-f', - `query=${ISSUE_DETAILS_QUERY}`, - '-f', - `owner=${repository.owner}`, - '-f', - `repo=${repository.repo}`, - '-F', - `number=${issueNumber}`, - '-F', - `includeItem=${includeItem}` - ], - ghOptions - ) - const parsed = JSON.parse(stdout) as GraphQLIssueDetailsResponse - if (parsed.errors && parsed.errors.length > 0) { + let stdout: string + let rejected = false + try { + ;({ stdout } = await ghExecFileAsync( + [ + 'api', + 'graphql', + '-f', + `query=${ISSUE_DETAILS_QUERY}`, + '-f', + `owner=${repository.owner}`, + '-f', + `repo=${repository.repo}`, + '-F', + `number=${issueNumber}`, + '-F', + `includeItem=${includeItem}` + ], + ghOptions + )) + } catch (error) { + stdout = extractExecError(error).stdout + rejected = true + } + const parsed: GraphQLIssueDetailsResponse = JSON.parse(stdout) + const errors = removeFailedGitHubBodyHtml(parsed.data, parsed.errors) + if (errors?.length || (rejected && !parsed.errors?.length)) { return null } const issue = parsed.data?.repository?.issue @@ -85,12 +100,15 @@ export async function getIssueDetailsViaGraphQL( return null } const comments: PRComment[] = (issue.comments?.nodes ?? []) - .filter((comment) => typeof comment.databaseId === 'number') + .filter( + (comment): comment is NonNullable => typeof comment?.databaseId === 'number' + ) .map((comment) => ({ id: comment.databaseId as number, author: comment.author?.login ?? 'ghost', authorAvatarUrl: comment.author?.avatarUrl ?? '', body: comment.body ?? '', + bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML), createdAt: comment.createdAt ?? '', url: comment.url ?? '', isBot: comment.author?.__typename === 'Bot', @@ -112,7 +130,7 @@ export async function getIssueDetailsViaGraphQL( name: user.name ?? null, avatarUrl: user.avatarUrl ?? '' })) - return { + const details: CollapsedIssueDetails = { ...(itemData?.success ? { item: mapIssueWorkItem({ @@ -125,12 +143,14 @@ export async function getIssueDetailsViaGraphQL( } : {}), body: issue.body ?? '', + bodyImageUrls: githubBodyImageUrls(issue.body, issue.bodyHTML), comments, assignees: assigneeUsers.map((assignee) => assignee.login), assigneeUsers, participants, timelineItems: await getIssueTimelineItems(repository, issueNumber, ghOptions, fresh) } + return details } catch { return null } @@ -143,7 +163,9 @@ export async function getIssueBodyAndComments( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {}, fresh = false -): Promise> { +): Promise< + Pick +> { const ghOptions = { ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), ...githubHostExecOptions(repository) @@ -161,7 +183,8 @@ export async function getIssueBodyAndComments( ghExecFileAsync( [ 'api', - ...(fresh ? [] : ['--cache', '60s']), + '-H', + GITHUB_BODY_MEDIA_TYPE, `repos/${repository.owner}/${repository.repo}/issues/${issueNumber}` ], ghOptions @@ -169,7 +192,8 @@ export async function getIssueBodyAndComments( ghExecFileAsync( [ 'api', - ...(fresh ? [] : ['--cache', '60s']), + '-H', + GITHUB_BODY_MEDIA_TYPE, ...(fresh ? ['--paginate', '--slurp'] : []), `repos/${repository.owner}/${repository.repo}/issues/${issueNumber}/comments?per_page=100` ], @@ -178,14 +202,16 @@ export async function getIssueBodyAndComments( getIssueTimelineItems(repository, issueNumber, ghOptions, fresh), readViewerLogin(ghOptions) ]) - const issue = JSON.parse(issueResult.stdout) as { + const issue: { body?: string | null + body_html?: unknown assignees?: { login: string }[] - } + } = JSON.parse(issueResult.stdout) type RESTComment = { id: number user: { login: string; avatar_url: string; type?: string } | null body: string + body_html?: unknown created_at: string html_url: string } @@ -199,17 +225,20 @@ export async function getIssueBodyAndComments( author: comment.user?.login ?? 'ghost', authorAvatarUrl: comment.user?.avatar_url ?? '', body: comment.body ?? '', + bodyImageUrls: githubBodyImageUrls(comment.body, comment.body_html), createdAt: comment.created_at, url: comment.html_url, isBot: comment.user?.type === 'Bot', ...viewerAuthorship(comment.user?.login, viewerLogin) })) - return { + const details = { body: issue.body ?? '', + bodyImageUrls: githubBodyImageUrls(issue.body, issue.body_html), comments, assignees: (issue.assignees ?? []).map((assignee) => assignee.login), timelineItems } + return details } if (connectionId) { // A connection-backed lookup must not use ambient local GH_REPO/GH_HOST. diff --git a/src/main/github/issues.test.ts b/src/main/github/issues.test.ts index 55862e1f0a1..3beaf260cd7 100644 --- a/src/main/github/issues.test.ts +++ b/src/main/github/issues.test.ts @@ -216,6 +216,56 @@ describe('issue source operations', () => { ) }) + it('keeps the accepted issue body representation through a compound metadata edit', async () => { + const body = + '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + body, + body_html: + '' + }) + }) + .mockResolvedValueOnce({ stdout: '' }) + await expect(updateIssue('/repo-root', 924, { body, title: 'Updated' })).resolves.toEqual({ + ok: true, + bodyImageUrls: { + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + } + }) + expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain( + 'Accept: application/vnd.github.full+json' + ) + expect(ghExecFileAsyncMock.mock.calls[0][1].stdin).toBe(JSON.stringify({ body })) + }) + + it.each([ + '', + 'not JSON', + JSON.stringify({ + body: 'different ![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)', + body_html: + '' + }) + ])( + 'keeps an accepted issue edit successful without a usable paired response (%s)', + async (stdout) => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ stdout }) + await expect( + updateIssue('/repo-root', 924, { + body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + }) + ).resolves.toEqual({ + ok: true, + bodyImageUrls: undefined + }) + } + ) + it('reports a failed close whose gh error mentions "already"', async () => { getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) ghExecFileAsyncMock.mockRejectedValueOnce( diff --git a/src/main/github/project-view/body-image-mutations.test.ts b/src/main/github/project-view/body-image-mutations.test.ts new file mode 100644 index 00000000000..53c0925b77f --- /dev/null +++ b/src/main/github/project-view/body-image-mutations.test.ts @@ -0,0 +1,170 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + acquireMock, + ghExecFileAsyncMock, + noteRepositoryRateLimitSpendMock, + projectHostAuthenticationErrorMock, + repositoryRateLimitGuardMock, + releaseMock, + runGraphqlMock, + runRestMock +} = vi.hoisted(() => ({ + acquireMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + noteRepositoryRateLimitSpendMock: vi.fn(), + projectHostAuthenticationErrorMock: vi.fn(), + repositoryRateLimitGuardMock: vi.fn(), + releaseMock: vi.fn(), + runGraphqlMock: vi.fn(), + runRestMock: vi.fn() +})) + +vi.mock('./internals', () => ({ + acquire: acquireMock, + release: releaseMock, + extractExecError: (err: unknown) => ({ + stderr: err instanceof Error ? err.message : String(err), + stdout: '' + }), + ghExecFileAsync: ghExecFileAsyncMock, + rateLimitGuard: () => ({ blocked: false }), + noteRateLimitSpend: vi.fn(), + repositoryRateLimitGuard: repositoryRateLimitGuardMock, + noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock, + projectHostAuthenticationError: projectHostAuthenticationErrorMock, + projectGhExecOptions: (host?: string) => ({ host: host ?? 'github.com' }), + classifyProjectError: (stderr: string) => ({ type: 'unknown', message: stderr }), + rateLimitedError: () => ({ type: 'rate_limited', message: 'rate limited' }), + runGraphql: runGraphqlMock, + runRest: runRestMock, + validateSlugArgs: (owner: string, repo: string) => + owner && repo ? { ok: true } : { ok: false, error: { type: 'validation_error' } }, + assertPositiveInt: (value: number, name: string) => + Number.isInteger(value) && value > 0 + ? { ok: true, value } + : { ok: false, error: { type: 'validation_error', message: `${name} invalid` } } +})) + +import { updateIssueBySlug } from './mutations' +import { updatePullRequestBySlug } from './pull-request-mutation' +import { addIssueCommentBySlug } from './issue-comment-mutations' + +describe('Project accepted body representations', () => { + beforeEach(() => { + acquireMock.mockReset().mockResolvedValue(undefined) + ghExecFileAsyncMock.mockReset().mockResolvedValue({ stdout: '', stderr: '' }) + noteRepositoryRateLimitSpendMock.mockReset() + projectHostAuthenticationErrorMock.mockReset().mockResolvedValue(null) + repositoryRateLimitGuardMock.mockReset().mockReturnValue({ blocked: false }) + releaseMock.mockReset() + runRestMock.mockReset().mockResolvedValue({ ok: true, data: {} }) + }) + + it.each([updateIssueBySlug, updatePullRequestBySlug])( + 'returns paired image sources after a body edit', + async (update) => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + runRestMock.mockResolvedValueOnce({ + ok: true, + data: { + body, + body_html: + '' + } + }) + const result = await update({ owner: 'acme', repo: 'widgets', number: 12, updates: { body } }) + expect(result).toEqual({ + ok: true, + bodyImageUrls: { + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + } + }) + expect(runRestMock.mock.calls[0][0]).toContain(`body=${body}`) + expect(runRestMock.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json') + } + ) + + it('returns the paired source for a newly posted Project comment', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + runRestMock.mockResolvedValueOnce({ + ok: true, + data: { + id: 1, + body, + body_html: + '' + } + }) + const result = await addIssueCommentBySlug({ owner: 'acme', repo: 'widgets', number: 12, body }) + expect(result.ok && result.comment.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + }) + + it('does not attach a Project issue map from a different accepted body snapshot', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + runRestMock.mockResolvedValueOnce({ + ok: true, + data: { + body: `${body}\nchanged elsewhere`, + body_html: + '' + } + }) + await expect( + updateIssueBySlug({ owner: 'acme', repo: 'widgets', number: 12, updates: { body } }) + ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) + }) + + it('keeps an accepted PR body save successful without an optional representation', async () => { + runRestMock.mockResolvedValueOnce({ ok: true, data: null }) + await expect( + updatePullRequestBySlug({ + owner: 'acme', + repo: 'widgets', + number: 12, + updates: { + body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + } + }) + ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) + }) + + it.each([null, true])( + 'finishes a Project compound save with unusable optional HTML (%s)', + async (html) => { + const body = + '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + runRestMock.mockResolvedValueOnce({ + ok: true, + data: html === null ? null : { body, body_html: html } + }) + await expect( + updateIssueBySlug({ + owner: 'acme', + repo: 'widgets', + number: 12, + updates: { body, addLabels: ['saved-label'] } + }) + ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) + expect(runRestMock).toHaveBeenCalledWith( + [ + '-X', + 'POST', + 'repos/acme/widgets/issues/12/labels', + '--raw-field', + 'labels[]=saved-label' + ], + undefined, + 'core', + { host: 'github.com' } + ) + } + ) +}) diff --git a/src/main/github/project-view/issue-comment-mutations.ts b/src/main/github/project-view/issue-comment-mutations.ts index fa16455e66d..61dd68d32b9 100644 --- a/src/main/github/project-view/issue-comment-mutations.ts +++ b/src/main/github/project-view/issue-comment-mutations.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' import { assertPositiveInt, projectGhExecOptions, runRest, validateSlugArgs } from './internals' import type { PRComment } from '../../../shared/github/comment-types' import type { @@ -14,6 +15,7 @@ type RawIssueCommentResponse = { id?: number user?: { login?: string; avatar_url?: string; type?: string } | null body?: string + body_html?: string | null created_at?: string html_url?: string } @@ -24,6 +26,7 @@ function mapIssueComment(data: RawIssueCommentResponse, fallbackBody: string): P author: data.user?.login ?? 'You', authorAvatarUrl: data.user?.avatar_url ?? '', body: data.body ?? fallbackBody, + bodyImageUrls: githubBodyImageUrls(data.body ?? fallbackBody, data.body_html), createdAt: data.created_at ?? new Date().toISOString(), url: data.html_url ?? '', isBot: data.user?.type === 'Bot' @@ -55,6 +58,7 @@ export async function addIssueCommentBySlug( [ '-X', 'POST', + ...githubBodyMediaHeaders(args.body), `repos/${args.owner}/${args.repo}/issues/${args.number}/comments`, '--raw-field', `body=${args.body}` diff --git a/src/main/github/project-view/mutations.ts b/src/main/github/project-view/mutations.ts index 7388f7a3f99..4c31ac3a522 100644 --- a/src/main/github/project-view/mutations.ts +++ b/src/main/github/project-view/mutations.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' import { acquire, assertPositiveInt, @@ -46,15 +47,16 @@ export async function updateIssueBySlug( return stateResult } const { title, body } = args.updates + let bodyImageUrls: Record | undefined if (title !== undefined || body !== undefined) { const patchArgs = ['-X', 'PATCH', base] if (title !== undefined) { patchArgs.push('--raw-field', `title=${title}`) } if (body !== undefined) { - patchArgs.push('--raw-field', `body=${body}`) + patchArgs.push(...githubBodyMediaHeaders(body), '--raw-field', `body=${body}`) } - const result = await runRest( + const result = await runRest<{ body?: string; body_html?: string }>( patchArgs, undefined, 'core', @@ -63,12 +65,20 @@ export async function updateIssueBySlug( if (!result.ok) { return { ok: false, error: result.error } } + try { + if (body !== undefined && result.data?.body === body) { + bodyImageUrls = githubBodyImageUrls(body, result.data.body_html) + } + } catch { + // Optional display data cannot turn an accepted edit into a failed write. + } } const labelResult = await updateIssueLabels(args, base) if (!labelResult.ok) { return labelResult } - return updateIssueAssignees(args, base) + const assigneeResult = await updateIssueAssignees(args, base) + return assigneeResult.ok ? { ok: true, bodyImageUrls } : assigneeResult } function validateDuplicateUpdate(args: UpdateIssueBySlugArgs): GitHubProjectMutationResult | null { diff --git a/src/main/github/project-view/pull-request-mutation.ts b/src/main/github/project-view/pull-request-mutation.ts index 7a49d9cbf0e..def6756c126 100644 --- a/src/main/github/project-view/pull-request-mutation.ts +++ b/src/main/github/project-view/pull-request-mutation.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' import { assertPositiveInt, projectGhExecOptions, runRest, validateSlugArgs } from './internals' import type { GitHubProjectMutationResult } from '../../../shared/github/project-result-types' import type { UpdatePullRequestBySlugArgs } from '../../../shared/github/project-request-types' @@ -30,7 +31,11 @@ export async function updatePullRequestBySlug( fieldCount++ } if (args.updates.body !== undefined) { - patchArgs.push('--raw-field', `body=${args.updates.body}`) + patchArgs.push( + ...githubBodyMediaHeaders(args.updates.body), + '--raw-field', + `body=${args.updates.body}` + ) fieldCount++ } if (args.updates.state !== undefined) { @@ -40,11 +45,19 @@ export async function updatePullRequestBySlug( if (fieldCount === 0) { return { ok: true } } - const result = await runRest( + const result = await runRest<{ body?: string; body_html?: string }>( patchArgs, undefined, 'core', projectGhExecOptions(args.host) ) - return result.ok ? { ok: true } : { ok: false, error: result.error } + return result.ok + ? { + ok: true, + bodyImageUrls: + args.updates.body !== undefined + ? githubBodyImageUrls(result.data?.body ?? args.updates.body, result.data?.body_html) + : undefined + } + : { ok: false, error: result.error } } diff --git a/src/main/github/project-view/work-item-details.ts b/src/main/github/project-view/work-item-details.ts index e09a8a038cb..6323f722a13 100644 --- a/src/main/github/project-view/work-item-details.ts +++ b/src/main/github/project-view/work-item-details.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../body-image-urls' import { assertPositiveInt, projectGhExecOptions, runGraphql, validateSlugArgs } from './internals' import type { PRComment } from '../../../shared/github/comment-types' import type { GitHubAssignableUser } from '../../../shared/github/pull-request-types' @@ -11,6 +12,7 @@ type RawComment = { databaseId?: number author?: { login?: string; avatarUrl?: string; __typename?: string } | null body?: string + bodyHTML?: unknown createdAt?: string url?: string } @@ -24,6 +26,7 @@ type RawWorkItemContent = { isDraft?: boolean updatedAt?: string body?: string + bodyHTML?: unknown headRefName?: string baseRefName?: string author?: { login?: string } | null @@ -33,6 +36,13 @@ type RawWorkItemContent = { comments?: { nodes?: (RawComment | null)[] } } +type RawWorkItemDetailsResponse = { + repository?: { + issue?: RawWorkItemContent | null + pullRequest?: RawWorkItemContent | null + } | null +} + export async function getWorkItemDetailsBySlug( args: ProjectWorkItemDetailsBySlugArgs ): Promise { @@ -51,49 +61,63 @@ export async function getWorkItemDetailsBySlug( } } const contentFragment = args.type === 'issue' ? ISSUE_FRAGMENT : PULL_REQUEST_FRAGMENT - const result = await runGraphql<{ - repository?: { - issue?: RawWorkItemContent | null - pullRequest?: RawWorkItemContent | null - } | null - }>( + const result = await runGraphql( `query($owner:String!, $repo:String!, $num:Int!) { repository(owner:$owner, name:$repo) { ${contentFragment} } }`, { owner: args.owner, repo: args.repo, num: args.number }, projectGhExecOptions(args.host) ) - if (!result.ok) { + let data: RawWorkItemDetailsResponse | undefined + if (result.ok) { + data = result.data + } else { + try { + const response: { data?: RawWorkItemDetailsResponse; errors?: unknown[] } = JSON.parse( + result.raw.stdout + ) + if ( + !response.errors?.length || + removeFailedGitHubBodyHtml(response.data, response.errors)?.length + ) { + return { ok: false, error: result.error } + } + data = response.data + } catch { + return { ok: false, error: result.error } + } + } + const raw = args.type === 'issue' ? data?.repository?.issue : data?.repository?.pullRequest + if (!result.ok && typeof raw?.body !== 'string') { return { ok: false, error: result.error } } - const raw = - args.type === 'issue' ? result.data.repository?.issue : result.data.repository?.pullRequest if (!raw) { return { ok: false, error: { type: 'not_found', message: 'Item not found.', reason: 'item_not_found' } } } - return { ok: true, details: mapWorkItemDetails(raw, args) } + const details = mapWorkItemDetails(raw, args) + return { ok: true, details } } const ISSUE_FRAGMENT = `issue(number:$num) { - id number title url state stateReason updatedAt body author { login } + id number title url state stateReason updatedAt body bodyHTML author { login } labels(first:50) { nodes { name } } assignees(first:50) { nodes { login } } participants(first:50) { nodes { login name avatarUrl } } comments(first:100) { - nodes { databaseId author { login avatarUrl __typename } body createdAt url } + nodes { databaseId author { login avatarUrl __typename } body bodyHTML createdAt url } } }` const PULL_REQUEST_FRAGMENT = `pullRequest(number:$num) { - id number title url state isDraft updatedAt headRefName baseRefName body author { login } + id number title url state isDraft updatedAt headRefName baseRefName body bodyHTML author { login } labels(first:50) { nodes { name } } assignees(first:50) { nodes { login } } participants(first:50) { nodes { login name avatarUrl } } comments(first:100) { - nodes { databaseId author { login avatarUrl __typename } body createdAt url } + nodes { databaseId author { login avatarUrl __typename } body bodyHTML createdAt url } } }` @@ -117,6 +141,7 @@ function mapWorkItemDetails( author: comment.author?.login ?? '', authorAvatarUrl: comment.author?.avatarUrl ?? '', body: comment.body, + bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML), createdAt: typeof comment.createdAt === 'string' ? comment.createdAt : '', url: typeof comment.url === 'string' ? comment.url : '', isBot: comment.author?.__typename === 'Bot' @@ -161,6 +186,7 @@ function mapWorkItemDetails( args.type === 'pr' && typeof raw.baseRefName === 'string' ? raw.baseRefName : undefined }, body: typeof raw.body === 'string' ? raw.body : '', + bodyImageUrls: githubBodyImageUrls(raw.body, raw.bodyHTML), comments, participants, assignees diff --git a/src/main/github/pull-request-file-data.ts b/src/main/github/pull-request-file-data.ts index d6c42f0b392..e4406581f91 100644 --- a/src/main/github/pull-request-file-data.ts +++ b/src/main/github/pull-request-file-data.ts @@ -1,3 +1,4 @@ +import { GITHUB_BODY_MEDIA_TYPE, githubBodyImageUrls } from './body-image-urls' import type { GitHubPRFile } from '../../shared/github/pull-request-types' import type { PRFileViewedStatesResult } from './pull-request-detail-context' import { ghExecFileAsync, ghRepoExecOptions, githubRepoContext } from './gh-utils' @@ -49,7 +50,12 @@ export async function getPRMetadata( repository: GitHubApiRepository | null, connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} -): Promise<{ body: string; headSha?: string; baseSha?: string }> { +): Promise<{ + body: string + bodyImageUrls?: Record + headSha?: string + baseSha?: string +}> { if (!repository) { return { body: '' } } @@ -63,19 +69,27 @@ export async function getPRMetadata( try { noteRepositoryRateLimitSpend(repository, 'core', 1, ghOptions) const { stdout } = await ghExecFileAsync( - ['api', '--cache', '60s', `repos/${repository.owner}/${repository.repo}/pulls/${prNumber}`], + [ + 'api', + '-H', + GITHUB_BODY_MEDIA_TYPE, + `repos/${repository.owner}/${repository.repo}/pulls/${prNumber}` + ], ghOptions ) - const data = JSON.parse(stdout) as { + const data: { body?: string | null + body_html?: unknown head?: { sha?: string } base?: { sha?: string } - } - return { + } = JSON.parse(stdout) + const metadata = { body: data.body ?? '', + bodyImageUrls: githubBodyImageUrls(data.body, data.body_html), ...(data.head?.sha ? { headSha: data.head.sha } : {}), ...(data.base?.sha ? { baseSha: data.base.sha } : {}) } + return metadata } catch { return { body: '' } } diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-item-details.ts index 4c94c58a912..3db15194c9e 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-item-details.ts @@ -156,29 +156,31 @@ export async function getWorkItemDetails( ...collapsed.assigneeUsers ]), body: collapsed.body, + bodyImageUrls: collapsed.bodyImageUrls, comments: collapsed.comments, assignees: item.assignees?.map((user) => user.login) ?? collapsed.assignees, participants: collapsed.participants, timelineItems: collapsed.timelineItems } } - const [{ body, comments, assignees, timelineItems }, participants] = await Promise.all([ - getIssueBodyAndComments( - repoPath, - item.number, - resolvedRepository, - connectionId, - localGitOptions, - canonical - ), - getWorkItemParticipants( - repoPath, - item, - resolvedRepository, - connectionId, - localGitOptions - ) - ]) + const [{ body, bodyImageUrls, comments, assignees, timelineItems }, participants] = + await Promise.all([ + getIssueBodyAndComments( + repoPath, + item.number, + resolvedRepository, + connectionId, + localGitOptions, + canonical + ), + getWorkItemParticipants( + repoPath, + item, + resolvedRepository, + connectionId, + localGitOptions + ) + ]) const mentionParticipants = await getMentionParticipants( repoPath, item, @@ -191,6 +193,7 @@ export async function getWorkItemDetails( return { item: enrichItemDisplayAvatars(item, mentionParticipants), body, + bodyImageUrls, comments, assignees: item.assignees?.map((user) => user.login) ?? assignees, participants: mentionParticipants, @@ -256,6 +259,7 @@ export async function getWorkItemDetails( mentionParticipants ), body: metadata.body, + bodyImageUrls: metadata.bodyImageUrls, comments, headSha: metadata.headSha, baseSha: metadata.baseSha, diff --git a/src/preload/api/gh-bridge-mutations-and-projects.ts b/src/preload/api/gh-bridge-mutations-and-projects.ts index f687a91f02d..a057485be6d 100644 --- a/src/preload/api/gh-bridge-mutations-and-projects.ts +++ b/src/preload/api/gh-bridge-mutations-and-projects.ts @@ -94,8 +94,9 @@ export const ghMutationsAndProjectsApi = { sourceContext?: TaskSourceContext | null number: number updates: unknown - }): Promise<{ ok: true } | { ok: false; error: string }> => - ipcRenderer.invoke('gh:updateIssue', args), + }): Promise< + { ok: true; bodyImageUrls?: Record } | { ok: false; error: string } + > => ipcRenderer.invoke('gh:updateIssue', args), addIssueComment: (args: { repoPath: string repoId?: string | null diff --git a/src/preload/api/github-work-item-api.ts b/src/preload/api/github-work-item-api.ts index 52c6a93314f..f4ce0fc4d66 100644 --- a/src/preload/api/github-work-item-api.ts +++ b/src/preload/api/github-work-item-api.ts @@ -120,7 +120,7 @@ export type GithubWorkItemApi = { updates: GitHubIssueUpdate ownerRepo?: GitHubOwnerRepo } - ) => Promise<{ ok: true } | { ok: false; error: string }> + ) => Promise<{ ok: true; bodyImageUrls?: Record } | { ok: false; error: string }> addIssueComment: ( args: GitHubRepoSelectorArgs & { number: number diff --git a/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx b/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx index f7afff82f5b..eedfbceef48 100644 --- a/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx +++ b/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx @@ -148,6 +148,7 @@ export function renderCommentCard( /> resolvedBodyDraft: string markdownGitHubRepo: GitHubOwnerRepo | null setBodyDraft: (value: string) => void @@ -136,6 +138,7 @@ export function ConversationTabDescription({ ) : body.trim() ? ( ({ update: vi.fn().mockResolvedValue(undefined) })) +vi.mock('@/components/github/github-work-item-edit-mutations', () => ({ + runWorkItemBodyUpdate: mocks.update +})) +vi.mock('@/store', () => ({ + useAppStore: { getState: () => ({ recordFeatureInteraction: () => {} }) } +})) +vi.mock('@/lib/pr-bot-author-overrides', () => ({ usePRBotAuthorOverrides: () => ({}) })) +vi.mock('./conversation-tab-activity', () => ({ ConversationTabActivity: () => null })) +vi.mock('./conversation-tab-pr-sidebar', () => ({ ConversationTabPRSidebar: () => null })) +vi.mock('./gh-comment-composer', () => ({ GHCommentComposer: () => null })) +vi.mock('@/components/github/GitHubMarkdownComposer', () => ({ + GitHubMarkdownComposer: ({ + value, + onChange + }: { + value: string + onChange: (value: string) => void + }) => ( +