Merge origin/main into profile-snapshot-writes (picks up #40951)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Brennan Benson
2026-11-10 17:23:04 -08:00
co-authored by Claude Opus 5.5
132 changed files with 1597 additions and 5634 deletions
@@ -116,6 +116,43 @@ describe('relay edge fence after a host leaves', () => {
})
})
describe('relay edge fence over a same-epoch conflict', () => {
it('fences once more one epoch above a conflict at its epoch, and never bumps over a stale answer', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const h = await harness()
h.edge.answers = ['conflict', 'applied']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 9)).toBe(true)
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([9, 10])
expect(h.edge.calls.every((call) => call.body.cellId === 'us-c1')).toBe(true)
expect(logged(warn, 'orca_relay_edge_fence_above_conflict')).toEqual([
{ event: 'orca_relay_edge_fence_above_conflict', outcome: 'applied', assignmentEpoch: 10 }
])
expect(await h.pending()).toEqual([])
// Stale: the edge holds a newer epoch (the host may be back there); no bump, recorded for retry.
h.edge.calls = []
h.edge.answers = ['stale']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 11)).toBe(false)
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([11])
})
it('a pending fence retried into a same-epoch conflict lands one epoch above the row', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
const h = await harness()
await h.placeRow('us-c1', 7)
h.edge.answers = ['down', 'down', 'down', 'down', 'down', 'down', 'down', 'down', 'down', 'down']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 7)).toBe(false)
expect(await h.pending()).toHaveLength(1)
h.edge.calls = []
h.edge.answers = ['conflict', 'applied']
h.clock.now += 60_000
await h.retry()
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([7, 8])
expect(await h.pending()).toEqual([])
})
})
describe('relay edge pending fence retries', () => {
it('re-fences to the current row, not the recorded one, and clears the record once it lands', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+23 -2
View File
@@ -41,6 +41,27 @@ export async function recordPendingFence(
)
}
// One fence call. `conflict` means the edge holds this very epoch for another placement (a move onto
// the edge whose push landed though the director counted it as failed, then a placement elsewhere
// minted the same epoch). No later move can produce that (a later move has a higher epoch, which
// answers `stale`), so the fence goes once more one epoch above: it lands, and a later move onto
// the edge re-mints above it as for any edge epoch (moveToEdge).
async function assignFence(
admin: EdgeAdmin,
fence: Identity & { cellId: string; assignmentEpoch: number }
): Promise<{ outcome: string; assignmentEpoch: number }> {
const first = await admin.assign(fence)
if (first.outcome !== 'conflict' || first.assignmentEpoch !== fence.assignmentEpoch) {
return { outcome: first.outcome, assignmentEpoch: fence.assignmentEpoch }
}
const above = fence.assignmentEpoch + 1
const second = await admin.assign({ ...fence, assignmentEpoch: above })
console.warn(
JSON.stringify({ event: 'orca_relay_edge_fence_above_conflict', outcome: second.outcome, assignmentEpoch: above })
)
return { outcome: second.outcome, assignmentEpoch: above }
}
// The fence right after a host left (EdgeAssignments.fenceAway). Anything but applied/unchanged
// fails: unavailable, `conflict`, or `stale` (the edge holds a newer epoch, so it still claims the
// host); the failure is logged and recorded for retry. Returns whether the fence landed.
@@ -55,7 +76,7 @@ export async function fenceEdge(
let outcome = 'unavailable'
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
outcome = (await admin.assign(fence)).outcome
outcome = (await assignFence(admin, fence)).outcome
} catch (error) {
if (!(error instanceof EdgeAdminUnavailableError)) { throw error }
outcome = error.message
@@ -138,7 +159,7 @@ async function retryOne(
const assignmentEpoch = integer(row, 'assignment_epoch')
let outcome: string
try {
outcome = (await admin.assign({ ...identity, cellId, assignmentEpoch })).outcome
outcome = (await assignFence(admin, { ...identity, cellId, assignmentEpoch })).outcome
} catch (error) {
if (!(error instanceof EdgeAdminUnavailableError)) { throw error }
outcome = error.message
-1
View File
@@ -29,7 +29,6 @@
1 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-idle-arbitration.test.ts
3 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts
1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts
1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts
1 test-no-polling-loop:src/main/browser/cookies/browser-cookie-import-concurrency.test.ts
1 test-no-polling-loop:src/main/claude/claude-stop-ack-race.test.ts
1 test-no-polling-loop:src/main/claude/claude-stream-json-connection.test.ts
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -18,7 +18,7 @@
3 src/renderer/src/components/worktree-jump/worktree-jump-palette-status-inputs.ts
1 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.ts
4 src/renderer/src/components/floating-terminal/floating-workspace-terminal-actions.ts
1 src/renderer/src/lib/pane-manager/client-hosted-browser-row-state.ts
1 src/renderer/src/runtime/browser/client-hosting/client-hosted-browser-row-state.ts
4 src/renderer/src/lib/workspace/persistence/session-write-subscriber.ts
1 src/renderer/src/lib/workspace/persistence/workspace-session-browser-tabs.ts
7 src/renderer/src/lib/workspace/persistence/workspace-session-host-hydration.ts
@@ -4744,7 +4744,6 @@
"src/renderer/src/components/browser-pane/history/use-browser-history-shortcut.test.tsx": 1990,
"src/renderer/src/components/browser-pane/host-guest/agent-input-focus-guard.test.ts": 228,
"src/renderer/src/components/browser-pane/host-guest/browser-automation-visibility.test.ts": 45,
"src/renderer/src/components/browser-pane/host-guest/browser-guest-eviction-veto.test.ts": 1724,
"src/renderer/src/components/browser-pane/host-guest/browser-page-evicted-guest-recovery.test.ts": 1839,
"src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts": 515,
"src/renderer/src/components/browser-pane/host-guest/browser-page-registration-ownership.test.ts": 2197,
@@ -5366,7 +5365,6 @@
"src/renderer/src/components/right-sidebar/checks-panel/gitlab-review-client.test.ts": 321,
"src/renderer/src/components/right-sidebar/checks-panel/comments/review-comment-markdown.test.tsx": 2171,
"src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-manual-refresh-recovery.test.tsx": 2909,
"src/renderer/src/lib/repository-refresh/coalesced-poll-runner.test.ts": 61,
"src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx": 2023,
"src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts": 1767,
"src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-directory-listing.test.ts": 2072,
@@ -5631,7 +5629,6 @@
"src/renderer/src/components/status-bar/use-resource-usage-derived-model.test.tsx": 742,
"src/renderer/src/components/tab-bar/CopyTabIdMenuItem.test.tsx": 428,
"src/renderer/src/components/tab-bar/TabBarCreateEntry.search.test.tsx": 3224,
"src/renderer/src/components/tab-bar/TabBarItemRow.test.tsx": 2116,
"src/renderer/src/components/tab-bar/TabBarQuickCommandItem.test.tsx": 384,
"src/renderer/src/components/tab-bar/TabBarQuickCommandsMenu.virtualization.test.tsx": 1644,
"src/renderer/src/components/tab-bar/TabStripScrollIndicator.test.tsx": 356,
@@ -5656,8 +5653,6 @@
"src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.test.ts": 261,
"src/renderer/src/components/tab-bar/use-tab-bar-quick-command-search-input.test.tsx": 536,
"src/renderer/src/components/tab-group/RetainedPaneHost.test.tsx": 340,
"src/renderer/src/components/tab-group/TabGroupPanel.os-file-drop.test.tsx": 1711,
"src/renderer/src/components/tab-group/TabGroupPanel.pane-actions.test.tsx": 1419,
"src/renderer/src/components/tab-group/tab-drag-pointer-sensor.test.ts": 187,
"src/renderer/src/components/tab-group/tab-drag-preview-activation.test.ts": 1785,
"src/renderer/src/components/tab-group/tab-drag-retained-guest-passthrough.test.tsx": 2104,
@@ -6118,12 +6113,10 @@
"src/renderer/src/hooks/useIpcEvents-agent-status-connection-attribution.test.ts": 5510,
"src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts": 5268,
"src/renderer/src/hooks/useIpcEvents-agent-status-queue-ordering.test.ts": 3680,
"src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts": 7403,
"src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts": 4119,
"src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts": 3310,
"src/renderer/src/hooks/useIpcEvents-browser-certificate-failure.test.ts": 2981,
"src/renderer/src/hooks/useIpcEvents-browser-navigation.test.ts": 1511,
"src/renderer/src/hooks/useIpcEvents-client-hosted-browser-rows.test.ts": 1894,
"src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts": 5812,
"src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts": 2326,
"src/renderer/src/hooks/useIpcEvents-new-workspace-shortcut.test.ts": 72,
@@ -6254,7 +6247,6 @@
"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-new-tab-host-route-readiness.test.ts": 489,
"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-picker-contract.test.ts": 3592,
"src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation-toast.test.tsx": 2347,
"src/renderer/src/lib/launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation.test.ts": 2266,
"src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-accepted.test.tsx": 2754,
"src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-defaults.test.ts": 1594,
"src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx": 3435,
@@ -6359,7 +6351,7 @@
"src/renderer/src/lib/review-owner.test.ts": 238,
"src/renderer/src/lib/runtime-host-copy.test.ts": 317,
"src/renderer/src/components/sidebar/sidebar-feed/sidebar-pending-layer.test.ts": 338,
"src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.test.ts": 1728,
"src/renderer/src/components/sidebar/worktree-list/parity/sidebar-workspace-activity.test.ts": 1728,
"src/renderer/src/lib/simulator/launch/simulator-launch-coordination.test.ts": 43,
"src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts": 515,
"src/renderer/src/lib/simulator/tabs/simulator-pane-shutdown-scheduler.test.ts": 1679,
@@ -6379,9 +6371,8 @@
"src/renderer/src/lib/text-input/paste/text-control-paste-ownership.test.ts": 217,
"src/renderer/src/lib/text-input/paste/text-control-paste.test.ts": 222,
"src/renderer/src/lib/text-generation-error-copy.test.ts": 466,
"src/renderer/src/lib/typing-latency/echo-instrumentation.test.ts": 145,
"src/renderer/src/lib/typing-latency/renderer-long-tasks.test.ts": 75,
"src/renderer/src/lib/typing-latency/sample-window.test.ts": 77,
"src/renderer/src/diagnostics/typing-latency/echo-instrumentation.test.ts": 145,
"src/renderer/src/diagnostics/typing-latency/renderer-long-tasks.test.ts": 75,
"src/renderer/src/attention/unread/unread-badge-count-selector.test.ts": 1930,
"src/renderer/src/lib/agent-session/tab-identity/use-tab-agent-observed-signal-dispatch.test.tsx": 1971,
"src/renderer/src/lib/agent-session/tab-identity/use-tab-agent.test.ts": 1961,
@@ -6488,7 +6479,6 @@
"src/renderer/src/runtime/browser/creation/web-runtime-browser-creation-placement.test.ts": 1927,
"src/renderer/src/runtime/browser/creation/web-runtime-browser-link-open.test.ts": 2217,
"src/renderer/src/runtime/web-session-tabs-sync/closing/web-session-close-replay.test.ts": 1119,
"src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-open-files-batch-equivalence.test.ts": 1478,
"src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-restored-placeholder-identity.test.ts": 985,
"src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-agent-completion-notifications.test.ts": 1953,
"src/renderer/src/runtime/web-session-tabs-sync/tracking/web-session-tabs-removed-frame-retires-live-publisher.test.ts": 854,
@@ -6692,14 +6682,11 @@
"src/renderer/src/store/slices/settings/settings-terminal-quick-commands.test.ts": 1734,
"src/renderer/src/store/slices/settings/settings.test.ts": 1938,
"src/renderer/src/store/slices/worktrees/create/sparse-presets.test.ts": 217,
"src/renderer/src/store/slices/ssh/ssh.test.ts": 1843,
"src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts": 1867,
"src/renderer/src/store/terminals/store-create-tab-start-in-main.test.ts": 1801,
"src/renderer/src/store/slices/tabs/store-open-to-side-layout-owner.test.ts": 1919,
"src/renderer/src/store/repos/store-session-cascades.test.ts": 1775,
"src/renderer/src/store/slices/editor/hydration/store-session-editor-hydration.test.ts": 1719,
"src/renderer/src/store/terminals/store-session-terminal-reconnect.test.ts": 2279,
"src/renderer/src/store/terminals/store-session-workspace-hydration.test.ts": 1733,
"src/renderer/src/store/terminals/store-sleep-agent-status-retention.test.ts": 7641,
"src/renderer/src/store/terminals/store-sleep-exact-runtime-stop.test.ts": 1842,
"src/renderer/src/store/terminals/store-sleep-pane-hibernation.test.ts": 1932,
@@ -6719,7 +6706,6 @@
"src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1703,
"src/renderer/src/store/terminals/terminal-layout-pty-ownership.test.ts": 1734,
"src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts": 1627,
"src/renderer/src/store/terminals/terminal-pane-detach-agent-retention.test.ts": 2846,
"src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts": 1751,
"src/renderer/src/store/terminals/terminal-quick-command-hosts.test.ts": 1759,
"src/renderer/src/store/terminals/terminal-tab-owner-index.test.ts": 50,
@@ -6768,7 +6754,6 @@
"src/renderer/src/store/slices/worktrees/metadata/worktrees-linked-review-push-target.test.ts": 1186,
"src/renderer/src/store/slices/worktrees/metadata/worktrees-multiple-attachments.test.ts": 1132,
"src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts": 1132,
"src/renderer/src/store/slices/worktrees/teardown/worktrees-purge-terminal-state.test.ts": 1133,
"src/renderer/src/store/slices/worktrees/create/worktrees-remote-runtime-create.test.ts": 1244,
"src/renderer/src/store/slices/worktrees/teardown/worktrees-remote-runtime-removal.test.ts": 1227,
"src/renderer/src/store/slices/worktrees/teardown/worktrees-removal-state-cleanup.test.ts": 1229,
+1 -1
View File
@@ -36,7 +36,7 @@
1 src/renderer/src/lib/workspace/ownership/resolved-worktree-execution-host.ts # P5b-2 must clear: loosely typed state param
2 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts # P5b-2 must clear: optional state fields default to empty
2 src/renderer/src/lib/workspace/ownership/terminal-worktree-route.ts # P5b-2 must clear: the unattributed-twin check reads both catalogs directly
3 src/renderer/src/lib/typing-latency/diagnostic-summary.ts # P5b-2 must clear: optional state field
3 src/renderer/src/diagnostics/typing-latency/diagnostic-summary.ts # P5b-2 must clear: optional state field
2 src/renderer/src/attention/unread/unread-badge-count.ts # reads a passed-in copy
1 src/renderer/src/lib/workspace/paths/workspace-directory.ts # P5b-2 must clear: optional state field defaults to empty
2 src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.ts # P5b-2 must clear: optional state fields
@@ -0,0 +1,96 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createHookListenerState } from '../../../../../../shared/agent-hook-listener/listener-state'
import { normalizeHookPayload } from '../../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload'
import { AgentHookServer } from '../../../agent-hook-server'
import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures'
const ROOT_ID = '5883db93-32ca-48da-ba29-db952021d273'
const WORKER_ID = 'dc08d047-adfd-4190-a0f4-6c3f7167d394'
describe('Droid mission resume identity', () => {
let dir: string
let server: AgentHookServer
beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), 'orca-droid-server-'))
server = new AgentHookServer()
await server.start({ env: 'production' })
})
afterEach(() => {
server.stop()
rmSync(dir, { recursive: true, force: true })
})
// Droid writes `callingSessionId` on the first transcript record of sub-sessions only.
function transcript(id: string, callingSessionId?: string): string {
const path = join(dir, `${id}.jsonl`)
const start = { type: 'session_start', id, ...(callingSessionId ? { callingSessionId } : {}) }
writeFileSync(path, `${JSON.stringify(start)}\n`)
return path
}
function body(sessionId: string, transcriptPath: string, event: string) {
return buildBody(
{
hook_event_name: event,
session_id: sessionId,
transcript_path: transcriptPath,
tool_name: 'Execute',
prompt: 'run the mission'
},
{ launchToken: 'droid-token' }
)
}
async function post(sessionId: string, transcriptPath: string, event: string) {
expect(
(await postHookEvent(server, body(sessionId, transcriptPath, event), '/hook/droid')).status
).toBe(204)
}
const resumeId = () => server.getStatusSnapshotForPane(PANE)[0]?.providerSession?.id
it('keeps the orchestrator as the resume target while its workers report', async () => {
const rootPath = transcript(ROOT_ID)
const workerPath = transcript(WORKER_ID, ROOT_ID)
await post(WORKER_ID, workerPath, 'PreToolUse')
expect(resumeId()).toBeUndefined()
await post(ROOT_ID, rootPath, 'UserPromptSubmit')
await post(WORKER_ID, workerPath, 'PreToolUse')
await post(WORKER_ID, workerPath, 'Stop')
expect(resumeId()).toBe(ROOT_ID)
// Dismissing the row keeps only the resume identity; the mission is still running.
server.dropStatusEntry(PANE)
await post(WORKER_ID, workerPath, 'PreToolUse')
expect(resumeId()).toBe(ROOT_ID)
})
it('keeps the orchestrator when a restarted relay forwards a worker hook', () => {
// A cold relay has no pane row, so it forwards the worker hook with no session.
const relayed = (sessionId: string, transcriptPath: string) => {
const event = normalizeHookPayload(
createHookListenerState(),
'droid',
body(sessionId, transcriptPath, 'PreToolUse'),
'production'
)
if (!event) {
throw new Error('Missing Droid event')
}
return event
}
server.ingestRemote(relayed(ROOT_ID, transcript(ROOT_ID)), 'host-1')
const worker = relayed(WORKER_ID, transcript(WORKER_ID, ROOT_ID))
expect(worker.providerSession).toBeUndefined()
server.ingestRemote(worker, 'host-1')
expect(resumeId()).toBe(ROOT_ID)
})
})
@@ -108,7 +108,8 @@ function readOptions(journal: AgentSessionJournal, agents: StructuredAgentRegist
},
serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
openConversation: async () => running,
conversation: async () => running
conversation: async () => running,
sessions: new Map([[SESSION, running]])
} as unknown as StructuredAgentSessionMutationContext
return readStructuredAgentSessionOptions(context, SESSION, { readsWithoutModel: true })
}
@@ -41,11 +41,19 @@ export function beginClaudeOptionMutation(session: ClaudeSession, key: string):
return sequence
}
/** Until a turn carries the pick, the running process's answers name the model it replaced. */
export function noteClaudeModelPick(session: ClaudeSession, model: string): void {
session.modelPickAwaitingTurn = model
delete session.reportedOptions.reportedModel
}
/** An init names execution; a control answer only acknowledges its input. */
export function observeClaudeExecutionModel(session: ClaudeSession, model: string): boolean {
const previous = claudeExecutionObservations(session).model
const previousResponse = session.reportedOptions.reportedModel
session.reportedOptions.reportedModel = model
if (!session.modelPickAwaitingTurn) {
session.reportedOptions.reportedModel = model
}
if (previous !== model) {
delete session.appliedOptions
}
@@ -93,7 +101,7 @@ function observeClaudeResponseModel(
: null,
responseModel: response
}) ?? response
if (model === session.reportedOptions.reportedModel) {
if (session.modelPickAwaitingTurn || model === session.reportedOptions.reportedModel) {
return false
}
session.reportedOptions.reportedModel = model
@@ -152,3 +152,50 @@ it('keeps a model picked during a turn over that turn’s later replies until a
await adapter.closeAll()
}
})
it('retires the answered model on a saved pick until a turn carries that pick', async () => {
const claude = fakeClaude({ initModel: 'claude-opus-5-5' })
const adapter = await acquired(claude)
const connection = claude.connections[0]!
const read = async () => (await adapter.readOptions({ sessionId: 'session-1', fence: 7 })).current
const answer = (uuid: string, model: string) =>
claudeFrame(connection, {
type: 'assistant',
uuid,
message: { role: 'assistant', model, content: [] }
})
const turn = async (clientMessageId: string, model: string) => {
claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' })
await adapter.dispatch({
sessionId: 'session-1',
clientMessageId,
body: USER_MESSAGE,
executionOptions: { model },
fence: 7
})
}
try {
claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5-5' })
answer('fallback', 'claude-opus-4-8')
expect((await read()).reportedModel).toBe('claude-opus-4-8')
adapter.noteOptionPick({ sessionId: 'session-1', fence: 7, key: 'model', value: 'sonnet' })
answer('same-turn', 'claude-opus-4-8')
expect((await read()).reportedModel).toBeUndefined()
expect((await read()).confirmed ?? []).not.toContain('model')
// A message accepted before the pick runs the model it captured.
await turn('queued-before-pick', 'opus')
claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5-5' })
answer('queued-answer', 'claude-opus-5-5')
expect((await read()).reportedModel).toBeUndefined()
await turn('carries-pick', 'sonnet')
expect(connection.calls).toContainEqual({ subtype: 'set_model', params: { model: 'sonnet' } })
claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-sonnet-5-5' })
answer('next-fallback', 'claude-opus-4-8')
expect((await read()).reportedModel).toBe('claude-opus-4-8')
} finally {
await adapter.closeAll()
}
})
@@ -18,6 +18,7 @@ import { supportsClaudeStructuredLocation } from './launch/claude-structured-loc
import * as claudeOptions from './launch/claude-structured-options'
import { dispatchClaudeMessage } from './launch/claude-structured-message-options'
import { readClaudeStructuredSessionOptions } from './launch/claude-structured-session-options'
import { noteClaudeModelPick } from './claude-structured-execution-observations'
import {
ClaudeAcquisitionRegistry,
type ClaudeSession,
@@ -231,6 +232,12 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda
deps: this.deps,
emit: (session, event) => this.emit(session, event)
})
noteOptionPick: NonNullable<StructuredAgentSessionAdapter['noteOptionPick']> = (input) => {
const session = this.sessions.get(input.sessionId)
if (session?.fence === input.fence && input.key === 'model' && input.value) {
noteClaudeModelPick(session, input.value)
}
}
readOptions = (input: { sessionId: string; fence: number }) =>
readClaudeStructuredSessionOptions(this.session(input.sessionId))
releaseAcquisition = (input: ClaudeReleaseRequest): Promise<boolean> => {
@@ -135,6 +135,8 @@ export type ClaudeSession = {
fastModePerSessionOptIn?: boolean
/** Mutation sequence of the last model report; newer writes outrank it. */
reportedModelMutation: number
/** A saved model pick no turn of this process has carried; its reports predate the pick. */
modelPickAwaitingTurn?: string
/** `dispatchSequence` at the last model write; that turn's replies predate the pick. */
modelMutationDispatch?: number
/** Options whose recorded value the provider reported, not merely accepted. */
@@ -30,6 +30,10 @@ export async function applyClaudeMessageOptions(
): Promise<void> {
throwIfSignalAborted(signal)
const model = options.model
// Only a turn carrying the newest pick reports on it; earlier captured sends run the replaced model.
if (model === session.modelPickAwaitingTurn) {
delete session.modelPickAwaitingTurn
}
if (model && session.appliedInputOptions.get('model') !== model) {
await waitForPromiseWithSignal(
setClaudeStructuredOption(session, { key: 'model', value: model }, timeoutMs),
@@ -213,6 +213,7 @@ export function claudeStructuredSessionOptionsFrom(
const discovered = listedModels(catalog ? { models: catalog } : null)
const listed = discovered.length > 0 ? discovered : seedModels()
const current = readClaudeCurrentModel(session)
const reportsPick = !session.modelPickAwaitingTurn
const model = current.id === 'default' ? undefined : current.id
const models = structuredAgentSessionOptionModels(listed, model, (row) => ({
...row,
@@ -230,7 +231,7 @@ export function claudeStructuredSessionOptionsFrom(
session.reportedOptions.fastMode ??
(session.fastModeState === undefined ? undefined : session.fastModeState !== 'off')
const confirmed = [
...(current.confirmed ? ['model'] : []),
...(current.confirmed && reportsPick ? ['model'] : []),
...(effort && session.confirmedOptions.has('effort') ? ['effort'] : []),
...(fastMode !== undefined &&
(session.confirmedOptions.has('fastMode') || !session.options.has('fastMode'))
@@ -243,7 +244,7 @@ export function claudeStructuredSessionOptionsFrom(
...(changesLive ? {} : { effortFixed: true as const }),
current: {
model,
reportedModel: session.reportedOptions.reportedModel,
reportedModel: reportsPick ? session.reportedOptions.reportedModel : undefined,
reportedPermissionMode: session.reportedOptions.reportedPermissionMode,
...(effort ? { effort } : {}),
...(fastMode !== undefined ? { fastMode } : {}),
@@ -106,7 +106,8 @@ export function piOptionRefreshHost(sessionId = 'session-1') {
},
serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
openConversation: async () => conversation,
conversation: async () => conversation
conversation: async () => conversation,
sessions: new Map([[sessionId, conversation]])
} as unknown as StructuredAgentSessionMutationContext
return readStructuredAgentSessionOptions(context, sessionId, { readsWithoutModel: true })
},
@@ -0,0 +1,182 @@
import { expect, it } from 'vitest'
import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire'
import type { StructuredAgentSessionMutationContext } from '../../operations/structured-agent-session-mutation-context'
import type {
StructuredAgentSessionHostSession,
StructuredAgentSessionProviderChild
} from '../structured-agent-session-host-types'
import { readStructuredAgentSessionOptions } from '../../options/structured-agent-session-options-read'
import { noteStructuredAgentSessionOptionPick } from '../../options/structured-agent-session-option-intent'
import {
hostTestCatalogReadOperation,
hostTestOptionsReadStore,
hostTestRestingOptionsJournal,
hostTestRestingOptionsRecord,
HOST_TEST_NOW as NOW,
HOST_TEST_SESSION as SESSION,
hostTestOperationId
} from './structured-agent-session-host-test-data'
import {
createQueuedMessageTestRig,
QUEUED_RIG_CALLER
} from './structured-agent-session-queued-message-rig.test-fixture'
import { appendUsageLimitedTurn } from './structured-agent-session-rewind-usage-limit.test-fixture'
const RESPONSE_REPORT = { model: 'opus[1m]', reportedModel: 'claude-opus-4-8' }
// Claude's confirmed init model stands in for a report when no response named one.
const CONFIRMED_INIT = { model: 'opus[1m]', confirmed: ['model'] }
function claudeOptionsRead(answer: Record<string, unknown> = RESPONSE_REPORT) {
const record = {
...hostTestRestingOptionsRecord('session-1'),
provider: 'claude',
options: { model: 'opus[1m]' }
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the reader and pick counter use only the child's identity, fence and phase.
const child = { fence: 2, phase: 'ready' } as unknown as StructuredAgentSessionProviderChild
const conversation = {
child,
params: { provider: 'claude' },
journal: hostTestRestingOptionsJournal()
}
// Picks serialize with the live read, so they can land only after it, as the answer is assembled.
const entered = Promise.withResolvers<void>()
const assembled = Promise.withResolvers<void>()
const home: AgentSessionModelCatalogResult = { origin: 'probe', fetchedAt: 1, models: [] }
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: picks and the reader read only the session's current child.
const session = { child } as unknown as StructuredAgentSessionHostSession
const sessions = new Map([['session-1', session]])
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real reader accesses only these injected ports; no provider process is launched.
const context = {
deps: {
adapter: {
readOptions: async () => ({
models: [],
current: answer
})
},
agents: { definition: () => null, capabilities: () => null },
store: hostTestOptionsReadStore(() => record),
modelCatalog: {
captureRead: hostTestCatalogReadOperation,
read: async () => home
}
},
serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
openConversation: async () => conversation,
conversation: async () => {
entered.resolve()
await assembled.promise
return conversation
},
sessions
} as unknown as StructuredAgentSessionMutationContext
const pick = (model: string) => {
record.options.model = model
noteStructuredAgentSessionOptionPick(
{ deps: { adapter: {} }, sessions },
{ sessionId: 'session-1', fence: 2 },
{ key: 'model', value: model },
true
)
}
/** Run `during` while the read is between its live snapshot and its answer. */
const read = async (during: () => void = () => {}) => {
const answer = readStructuredAgentSessionOptions(context, 'session-1', {
readsWithoutModel: true
})
await entered.promise
during()
assembled.resolve()
return (await answer).current
}
return { read, pick, sessions, session }
}
it('keeps a live fallback report that no pick has replaced', async () => {
expect(await claudeOptionsRead(CONFIRMED_INIT).read()).toMatchObject({
reportedModel: 'opus[1m]'
})
expect(await claudeOptionsRead().read()).toMatchObject({
model: 'opus[1m]',
reportedModel: 'claude-opus-4-8'
})
})
it.each([
['picks back to the same model', ['sonnet', 'opus[1m]'], RESPONSE_REPORT],
['re-picks the shown model', ['opus[1m]'], RESPONSE_REPORT],
['picks back while only the init model confirms', ['sonnet', 'opus[1m]'], CONFIRMED_INIT]
])(
'drops a report captured before the user %s while the read is in flight',
async (_, models, answer) => {
const host = claudeOptionsRead(answer)
const current = await host.read(() => models.forEach((model) => host.pick(model)))
expect(current.model).toBe('opus[1m]')
expect(current.reportedModel).toBeUndefined()
}
)
it('drops a report from a child that ended or was replaced while the read was in flight', async () => {
for (const next of [null, { fence: 3, phase: 'ready' }]) {
const host = claudeOptionsRead()
const current = await host.read(() => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only child identity matters to the reader.
host.sessions.set('session-1', {
...host.session,
child: next
} as unknown as StructuredAgentSessionHostSession)
})
expect(current.reportedModel).toBeUndefined()
}
})
it.each([
[
'retires the report when the user picks back to it',
QUEUED_RIG_CALLER,
['sonnet', 'opus[1m]'],
undefined
],
[
'keeps the report through an old client empty no-op',
{ ...QUEUED_RIG_CALLER, readsOptionsWithoutModel: false },
[''],
'claude-opus-4-8'
]
] as const)(
'after a usage-limited turn, a pick made while recovery choices load %s',
async (_, caller, models, reportedModel) => {
const rig = await createQueuedMessageTestRig({ agent: 'claude' })
try {
const pick = async (value: string) => {
const fields = { key: 'model', value }
return rig.host.setOption(caller, {
envelope: rig.envelope(fields, 'agentSession.setOption', hostTestOperationId()),
...fields
})
}
expect(await pick('opus[1m]')).toMatchObject({ ok: true })
rig.host.deps.adapter.readOptions = async () => ({ models: [], current: RESPONSE_REPORT })
const journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal
await appendUsageLimitedTurn(journal, NOW, 'quota')
const recovering = Promise.withResolvers<void>()
const released = Promise.withResolvers<undefined>()
rig.host.deps.resolveLaunchEnv = () => {
recovering.resolve()
return released.promise
}
const answer = rig.host.readOptions(SESSION)
await recovering.promise
for (const model of models) {
expect(await pick(model)).toMatchObject({ ok: true })
}
released.resolve(undefined)
const { current } = await answer
expect(current.model).toBe('opus[1m]')
expect(current.reportedModel).toBe(reportedModel)
} finally {
await rig.dispose()
}
}
)
@@ -55,7 +55,10 @@ import { openWithReadyStructuredAgentSessionChild } from './structured-agent-ses
import type { StructuredAgentSessionCaller } from '../host/structured-agent-session-host-types'
import '../options/structured-agent-session-options-read'
import { recordStructuredAgentSessionOptionIntent } from '../options/structured-agent-session-option-intent'
import {
noteStructuredAgentSessionOptionPick,
recordStructuredAgentSessionOptionIntent
} from '../options/structured-agent-session-option-intent'
import { confirmIdleStructuredAgentSessionOption } from '../options/structured-agent-session-idle-option'
export function sendStructuredAgentSessionTurn(
@@ -265,6 +268,7 @@ export async function setStructuredAgentSessionOption(
readsWithoutModel: caller.readsOptionsWithoutModel !== false
})
if (picked.ok) {
noteStructuredAgentSessionOptionPick(context, ctx, params, !noChoice)
confirmIdleStructuredAgentSessionOption(context, ctx, params)
}
return picked
@@ -19,6 +19,10 @@ import {
} from './structured-agent-session-pick-reply'
import type { StructuredAgentSessionAdapter } from '../providers/structured-agent-session-adapter'
import { pickAgentSessionOption } from '../../../runtime/agent-session/records/agent-session-record-options'
import type {
StructuredAgentSessionHostSession,
StructuredAgentSessionProviderChild
} from '../host/structured-agent-session-host-types'
function acceptsOptionPick(
agents: Pick<StructuredAgentRegistry, 'definition'>,
@@ -103,3 +107,34 @@ export async function recordStructuredAgentSessionOptionIntent(
}
}
}
const modelPicks = new WeakMap<StructuredAgentSessionProviderChild, number>()
/** Counts saved model picks per child, so a read can tell its captured report predates one. */
export function structuredAgentSessionModelPicks(
child: StructuredAgentSessionProviderChild
): number {
return modelPicks.get(child) ?? 0
}
/** A saved pick retires the current child's earlier reports, including ones a read already captured. */
export function noteStructuredAgentSessionOptionPick(
context: {
deps: { adapter: Pick<StructuredAgentSessionAdapter, 'noteOptionPick'> }
sessions: ReadonlyMap<string, StructuredAgentSessionHostSession>
},
ctx: Pick<AgentSessionTurnContext, 'sessionId' | 'fence'>,
input: { key: string; value: string },
saved: boolean
): void {
const { sessionId, fence } = ctx
// An old client's empty model clears nothing, so it retires no report.
if (!saved) {
return
}
const child = context.sessions.get(sessionId)?.child
if (input.key === 'model' && child?.fence === fence) {
modelPicks.set(child, structuredAgentSessionModelPicks(child) + 1)
}
context.deps.adapter.noteOptionPick?.({ sessionId, fence, ...input })
}
@@ -30,12 +30,13 @@ import { structuredAgentSessionImmediatePermission } from './structured-agent-se
import type { StructuredAgentSessionMutationContext } from '../operations/structured-agent-session-mutation-context'
import { readStructuredSessionRecovery } from '../recovery/structured-agent-session-recovery-read'
import { fillUnknownModelEfforts } from '../../../../shared/agent-session/options/agent-session-model-efforts'
import { structuredAgentSessionModelPicks } from './structured-agent-session-option-intent'
/** A live child's own answer, or the answer at rest; the goal, usage and rewind either way. */
export async function readStructuredAgentSessionOptions(
context: Pick<
StructuredAgentSessionMutationContext,
'deps' | 'serialize' | 'openConversation' | 'conversation'
'deps' | 'serialize' | 'openConversation' | 'conversation' | 'sessions'
> &
Partial<Pick<StructuredAgentSessionMutationContext, 'deliveryOrder'>>,
sessionId: string,
@@ -71,6 +72,7 @@ export async function readStructuredAgentSessionOptions(
child && child.phase !== 'starting'
? await adapter.readOptions?.({ sessionId, fence: child.fence })
: undefined
const modelPicks = child ? structuredAgentSessionModelPicks(child) : 0
const scope = () =>
structuredAgentSessionCatalogScopeOwned(
context.deps,
@@ -93,7 +95,8 @@ export async function readStructuredAgentSessionOptions(
records,
session,
child,
options: observed ?? null
options: observed ?? null,
modelPicks
}
})
let started = await readCurrent(true)
@@ -132,6 +135,7 @@ export async function readStructuredAgentSessionOptions(
const floor = session.journal.context.floor()
const contextFloor = floor ? { contextFloor: floor } : {}
const restingOptions = await atRest()
const recovery = await readStructuredSessionRecovery(session, context, sessionId)
if (live && usesModelSpecificAcpEfforts(agent)) {
options = {
...options,
@@ -159,12 +163,17 @@ export async function readStructuredAgentSessionOptions(
const model = saved.model ?? (options.current.model || selected.current.model || displayDefault)
const projected = live?.projectCurrent?.({ ...saved, ...(model ? { model } : {}) })
const reportedEffort = projected?.confirmed?.includes('effort') ? projected.effort : undefined
const reportedModel = live
? (options.current.reportedModel ??
(agent === 'claude' && options.current.confirmed?.includes('model')
? options.current.model
: undefined))
: undefined
// After every await: a pick or a replaced child since the live read retires its report.
const reportedModel =
live &&
started.kind === 'live' &&
context.sessions.get(sessionId)?.child === started.child &&
started.modelPicks === structuredAgentSessionModelPicks(started.child)
? (options.current.reportedModel ??
(agent === 'claude' && options.current.confirmed?.includes('model')
? options.current.model
: undefined))
: undefined
const current = {
...selected.current,
...options.current,
@@ -236,7 +245,6 @@ export async function readStructuredAgentSessionOptions(
current.serviceTier = projected.options.serviceTier
}
}
const recovery = await readStructuredSessionRecovery(session, context, sessionId)
return {
...options,
...recovery,
@@ -258,7 +266,7 @@ export async function readStructuredAgentSessionOptions(
current: {
...current,
acceptedInputSources,
...(reportedModel ? { reportedModel } : {}),
reportedModel,
...(reportedEffort !== undefined ? { reportedEffort } : {}),
defaulted,
confirmed,
@@ -204,6 +204,8 @@ export class StructuredAgentSessionAdapterRouter implements Adapter {
canSetOptionWhileIdle: Adapter['canSetOptionWhileIdle'] = (input) =>
this.liveOwnerOrNull(input.sessionId)?.canSetOptionWhileIdle?.(input) === true
noteOptionPick: Adapter['noteOptionPick'] = (input) =>
this.liveOwnerOrNull(input.sessionId)?.noteOptionPick?.(input)
readAppliedInputOptions: Adapter['readAppliedInputOptions'] = (input) =>
this.liveOwnerOrNull(input.sessionId)?.readAppliedInputOptions?.(input) ?? null
@@ -304,6 +304,8 @@ export type StructuredAgentSessionAdapter = StructuredAgentSessionAdapterStop &
): Promise<void | Readonly<Record<string, string>>>
/** Opt in only when setOption can update idle metadata without a provider turn. */
canSetOptionWhileIdle?(input: StructuredAgentSessionSetOptionInput): boolean
/** A saved pick retires this child's earlier execution reports until a turn carries it. */
noteOptionPick?(input: { sessionId: string; fence: number; key: string; value: string }): void
/** Applied inputs for this exact child; observations never decide message admission. */
readAppliedInputOptions?(input: {
sessionId: string
@@ -13,6 +13,11 @@ import {
} from '../../../../../shared/source-control/ai/recipes/source-control-action-options'
import { encodeCatalogOptionValue } from '../../../../../shared/agent-session/options/structured-agent-session-option-codec'
import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent'
import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire'
import {
agentPickerEntryOptions,
agentPickerModels
} from '../../../../../shared/agent-launch/picker/agent-launch-picker-catalog'
import { AgentChoiceMenu } from './AgentChoiceMenu'
import { sourceControlActionRouteHint } from './agent-choice-route-hint'
import { useTranslate } from '@/i18n/use-translate'
@@ -27,6 +32,10 @@ export type AgentChoiceControlsProps = {
optionIds?: readonly string[]
defaultLabels?: { model?: string; options?: Record<string, string> }
layout?: 'stacked' | 'contents' | 'rows'
/** The host's own list; without a listing the fields keep the release's seed models. */
liveCatalog?: AgentSessionModelCatalogResult
/** Tells the reader this list is the release's, because the host gave none. */
usesSeedModels?: boolean
onChange: (value: AgentDedicatedChoices | undefined) => void
}
@@ -61,6 +70,8 @@ export function AgentChoiceFields({
optionIds,
defaultLabels,
layout = 'stacked',
liveCatalog,
usesSeedModels,
onSelect
}: Omit<AgentChoiceControlsProps, 'onChange'> & {
onSelect: (patch: AgentChoicePatch) => void
@@ -73,13 +84,34 @@ export function AgentChoiceFields({
const catalog = picksModel ? getAgentSessionOptionLaunchCatalog(agent) : null
const selected = value
const model = catalog && selected?.model ? findCatalogModel(catalog, selected.model) : undefined
const unlistedModel = catalog && selected?.model && !model ? selected.model : undefined
const options = sourceControlActionOptions(agent, selected?.model ?? '').filter(
const live =
liveCatalog && liveCatalog.origin !== 'unknown' && liveCatalog.models.length
? { agent, catalog: liveCatalog, terminal: {} }
: null
const listedModels = live
? agentPickerModels(live).filter(({ hidden }) => !hidden)
: (catalog?.models ?? [])
const unlistedModel =
selected?.model && !(live ? listedModels.some(({ id }) => id === selected.model) : model)
? selected.model
: undefined
const liveEffort = live
? agentPickerEntryOptions(live, selected?.model, 'terminal').find(({ id }) => id === 'effort')
: undefined
const options = sourceControlActionOptions(agent, selected?.model ?? '').flatMap((row) => {
// CLI carrier mappings remain available to Args badges without advertising a mode control.
({ option }) =>
(Boolean(model) || option.category !== 'mode') &&
(!optionIds || optionIds.includes(option.id))
)
if (
(!model && row.option.category === 'mode') ||
(optionIds && !optionIds.includes(row.option.id))
) {
return []
}
if (!live || row.option.id !== 'effort') {
return [row]
}
// A listed model with no reasoning levels gets no effort menu.
return liveEffort ? [{ ...row, option: { ...row.option, kind: liveEffort.kind } }] : []
})
const defaultLabel = t('settings.sourceControl.actionModel.effortDefault', 'Default')
return (
<div className={layout === 'contents' ? 'contents' : 'grid min-w-0 grid-cols-1 gap-2'}>
@@ -97,12 +129,20 @@ export function AgentChoiceFields({
defaultLabels?.model ??
t('settings.sourceControl.actionModel.agentDefault', 'Agent default')
},
...catalog.models.map(({ id, label }) => ({ value: id, label })),
...listedModels.map(({ id, label }) => ({ value: id, label })),
...(unlistedModel ? [{ value: unlistedModel, label: unlistedModel }] : [])
]}
onChange={(model) => onSelect({ model: model === AGENT_DEFAULT_VALUE ? null : model })}
/>
) : null}
{catalog?.models.length && usesSeedModels ? (
<p data-agent-model-list-fallback className="text-xs text-muted-foreground">
{t(
'settings.agents.modelListFallback',
'Built-in list. Orca could not get a model list from this host.'
)}
</p>
) : null}
{options.map(({ option, route }) => {
const choices =
option.kind.type === 'select'
@@ -0,0 +1,168 @@
// @vitest-environment happy-dom
import { act, cleanup, render, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { getDefaultSettings } from '../../../../../shared/constants'
import {
forgetHostModelCatalogSnapshots,
recordHostModelCatalogSnapshot,
resetHostModelCatalogSnapshotsForTests
} from '@/runtime/native-chat/model-catalogs/host-model-catalog-snapshots'
import { useAppStore } from '@/store'
import { TooltipProvider } from '../../ui/tooltip'
import { AgentLaunchChoiceEditor } from './AgentLaunchChoiceEditor'
const call = vi.hoisted(() => vi.fn())
const menus = vi.hoisted(() => new Map<string, string[]>())
vi.mock('@/runtime/native-chat/requests/structured-agent-session-call', () => ({
callStructuredAgentSession: call
}))
vi.mock('./AgentChoiceMenu', () => ({
AgentChoiceMenu: ({
label,
choices
}: {
label: string
choices: readonly { value: string }[]
}) => {
menus.set(
label,
choices.map(({ value }) => value)
)
return null
}
}))
// A Codex account answer: its models are scoped, so no new chat in another workspace may reuse it.
const LISTED = {
origin: 'probe',
modelsDifferByWorkspace: true,
models: [
{
id: 'gpt-6-astra',
label: 'GPT-6-Astra',
isDefault: true,
efforts: [
{ value: 'low', label: 'Low' },
{ value: 'ultra', label: 'Ultra' }
]
},
{ id: 'gpt-reserve', label: 'GPT-Reserve', hidden: true, efforts: [] }
]
}
const HOST = { kind: 'environment', environmentId: 'env-1' } as const
function renderEditor(model?: string): void {
render(
<TooltipProvider>
<AgentLaunchChoiceEditor
agent="codex"
label="Codex"
choices={model ? { model } : undefined}
userArgs=""
permission={undefined}
catalogTarget={HOST}
save={async () => {}}
/>
</TooltipProvider>
)
}
describe('AgentLaunchChoiceEditor model list', () => {
const initialSettings = useAppStore.getState().settings
beforeEach(() => {
call.mockReset()
menus.clear()
resetHostModelCatalogSnapshotsForTests()
})
afterEach(() => {
cleanup()
useAppStore.setState({ settings: initialSettings })
})
it('lists the host models and the picked model efforts, keeping a saved unlisted model', async () => {
call.mockResolvedValue(LISTED)
renderEditor('gpt-6-astra')
await waitFor(() => expect(menus.get('Model')).toEqual(['__agent_default__', 'gpt-6-astra']))
expect(menus.get('Reasoning effort')).toEqual(['__agent_default__', 'low', 'ultra'])
expect(call).toHaveBeenCalledWith(HOST, 'agentSession.modelCatalog', { agent: 'codex' })
expect(document.querySelector('[data-agent-model-list-fallback]')).toBeNull()
cleanup()
renderEditor('gpt-old')
await waitFor(() =>
expect(menus.get('Model')).toEqual(['__agent_default__', 'gpt-6-astra', 'gpt-old'])
)
})
it('shows the refreshed model after the agent command changes and ignores the older answer', async () => {
let answerOlder: (catalog: unknown) => void = () => {}
call.mockReturnValueOnce(new Promise((resolve) => (answerOlder = resolve)))
call.mockResolvedValueOnce({
...LISTED,
models: [{ id: 'gpt-wrapped', label: 'GPT Wrapped', efforts: [] }]
})
const settings = getDefaultSettings('')
useAppStore.setState({ settings })
renderEditor()
act(() => {
useAppStore.setState({
settings: { ...settings, agentCmdOverrides: { codex: 'wrapped-codex' } }
})
})
await waitFor(() => expect(menus.get('Model')).toEqual(['__agent_default__', 'gpt-wrapped']))
await act(async () => answerOlder(LISTED))
expect(menus.get('Model')).toEqual(['__agent_default__', 'gpt-wrapped'])
})
it('shows the new account models when the host drops its lists while the row stays open', async () => {
call.mockResolvedValueOnce(LISTED)
renderEditor()
await waitFor(() => expect(menus.get('Model')).toEqual(['__agent_default__', 'gpt-6-astra']))
call.mockResolvedValueOnce({
...LISTED,
models: [{ id: 'gpt-other-account', label: 'GPT Other Account', efforts: [] }]
})
act(() => forgetHostModelCatalogSnapshots(HOST))
await waitFor(() =>
expect(menus.get('Model')).toEqual(['__agent_default__', 'gpt-other-account'])
)
})
it('waits for a listing the host is still running, again when one wait runs out', async () => {
call.mockResolvedValueOnce({ origin: 'unknown', listingInProgress: true })
call.mockResolvedValueOnce({ origin: 'unknown', listingInProgress: true, waitExpired: true })
call.mockResolvedValueOnce(LISTED)
renderEditor()
await waitFor(() => expect(menus.get('Model')).toEqual(['__agent_default__', 'gpt-6-astra']))
expect(call).toHaveBeenLastCalledWith(HOST, 'agentSession.modelCatalog', {
agent: 'codex',
waitForListing: true
})
expect(call).toHaveBeenCalledTimes(3)
expect(document.querySelector('[data-agent-model-list-fallback]')).toBeNull()
})
it('says the list is built in once the host fails to answer, even with an older answer', async () => {
recordHostModelCatalogSnapshot(HOST, 'codex', null, {
origin: 'probe',
fetchedAt: 1,
models: [{ id: 'gpt-older', label: 'GPT Older', isDefault: false, efforts: [] }]
})
call.mockRejectedValue(new Error('offline'))
renderEditor()
expect(menus.get('Model')).toContain('gpt-older')
expect(document.querySelector('[data-agent-model-list-fallback]')).toBeNull()
await waitFor(() =>
expect(document.querySelector('[data-agent-model-list-fallback]')).not.toBeNull()
)
expect(menus.get('Model')).toContain('gpt-5.6-sol')
expect(menus.get('Model')).not.toContain('gpt-older')
})
})
@@ -12,7 +12,9 @@ import { useAgentLaunchFieldWrite } from './use-agent-launch-field-write'
import { reconcileAgentChoiceArgs } from '../../../../../shared/agent-launch/choices/agent-choice-reconciliation'
import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent'
import { useTranslate } from '@/i18n/use-translate'
import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target'
import { AgentChoiceFields } from './AgentChoiceControls'
import { useAgentSettingsModelCatalog } from './use-agent-settings-model-catalog'
export function AgentLaunchChoiceEditor({
agent,
@@ -22,9 +24,12 @@ export function AgentLaunchChoiceEditor({
permission,
permissionControlRef,
save,
catalogTarget,
showArguments = true
}: {
showArguments?: boolean
/** The host whose models this editor lists; null keeps the release's seed models. */
catalogTarget: RuntimeClientTarget | null
agent: TuiAgent
label: string
choices: AgentModelOptionChoices | undefined
@@ -34,6 +39,10 @@ export function AgentLaunchChoiceEditor({
save: (patch: AgentChoicePatch | undefined, userArgs: string) => Promise<void>
}): React.JSX.Element {
const t = useTranslate()
const { catalog: liveCatalog, usesSeedModels } = useAgentSettingsModelCatalog(
agent,
catalogTarget
)
const menu = useRef({ open: false, committed: false })
const editorRef = useRef<HTMLDivElement>(null)
const [draft, setDraft] = useState<string | null>(null)
@@ -101,6 +110,8 @@ export function AgentLaunchChoiceEditor({
value={choices}
disabled={pending}
layout="rows"
liveCatalog={liveCatalog}
usesSeedModels={usesSeedModels}
onOpenChange={onOpenChange}
optionIds={['effort']}
onSelect={(patch) => commit(patch)}
@@ -0,0 +1,112 @@
import { useEffect, useState, useSyncExternalStore } from 'react'
import { useShallow } from 'zustand/react/shallow'
import type { AgentSessionModelCatalogResult } from '../../../../../shared/agent-session/agent-session-wire'
import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent'
import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target'
import {
HOST_MODEL_CATALOG_ACCOUNT_SETTINGS,
withoutUnprovenNewLaunchDefault
} from '../../../../../shared/agent-session/options/host-model-catalog-snapshot-rules'
import { sourceControlActionAgentPicksModel } from '../../../../../shared/source-control/ai/recipes/source-control-action-options'
import {
hostModelCatalogGeneration,
readHostModelCatalogSnapshot,
subscribeHostModelCatalogForgotten
} from '@/runtime/native-chat/model-catalogs/host-model-catalog-snapshots'
import { subscribeHostAgentLaunchSettings } from '@/runtime/agent-launch-settings/agent-launch-settings-transport'
import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call'
import { structuredAgentSessionHostKey } from '@/runtime/native-chat/host-capabilities/structured-agent-session-host-capability'
import { useAppStore } from '@/store'
const SETTINGS_LAUNCH = { newLaunch: true, seedsModel: true }
/** The host's account models for a Settings default. `usesSeedModels` says the release's list stands in. */
export function useAgentSettingsModelCatalog(
agent: TuiAgent,
target: RuntimeClientTarget | null
): { catalog: AgentSessionModelCatalogResult | undefined; usesSeedModels: boolean } {
const key = target ? `${structuredAgentSessionHostKey(target)}\u0000${agent}` : null
// Same array until one changes: a new account or command lists different models.
const accountSettings = useAppStore(
useShallow((state) => HOST_MODEL_CATALOG_ACCOUNT_SETTINGS.map((name) => state.settings?.[name]))
)
// A host can change account with no setting changing here, such as a paired host reconnecting.
const readGeneration = (): number => (target ? hostModelCatalogGeneration(target) : 0)
const generation = useSyncExternalStore(subscribeHostModelCatalogForgotten, readGeneration)
// A paired host's command and environment live in its own settings; re-read, keeping the shown list meanwhile.
const [hostRevision, setHostRevision] = useState(0)
const environmentId = target?.kind === 'environment' ? target.environmentId : null
const isLocal = target?.kind === 'local'
useEffect(
() =>
environmentId
? subscribeHostAgentLaunchSettings((owner) => {
if (owner.environmentId === environmentId) {
setHostRevision((revision) => revision + 1)
}
})
: undefined,
[environmentId]
)
const [answer, setAnswer] = useState<{
key: string
accountSettings: readonly unknown[]
generation: number
catalog: AgentSessionModelCatalogResult | undefined
} | null>(null)
useEffect(() => {
// Rebuilt from primitives: callers pass a new target object every render.
const readTarget: RuntimeClientTarget | null = environmentId
? { kind: 'environment', environmentId }
: isLocal
? { kind: 'local' }
: null
if (!readTarget || !key || !sourceControlActionAgentPicksModel(agent)) {
return
}
let stale = false
// Not recorded in the new-chat snapshot: an account answer there would drop newer workspace answers.
// Old hosts refuse waitForListing, so wait only once the host says a listing is running.
const read = (wait: boolean): void => {
void callStructuredAgentSession<AgentSessionModelCatalogResult>(
readTarget,
'agentSession.modelCatalog',
wait ? { agent, waitForListing: true } : { agent }
)
.then((catalog) => {
if (stale) {
return
}
if (wait ? catalog.waitExpired : catalog.listingInProgress) {
read(true)
return
}
setAnswer({ key, accountSettings, generation, catalog })
})
// Why not the snapshot: an unanswered read can't vouch for an older list.
.catch(() => {
if (!stale) {
setAnswer({ key, accountSettings, generation, catalog: undefined })
}
})
}
read(false)
return () => {
stale = true
}
}, [agent, key, environmentId, isLocal, accountSettings, generation, hostRevision])
const settled =
answer?.key === key &&
answer.accountSettings === accountSettings &&
answer.generation === generation
? answer
: null
// Why not the snapshot once answered: it serves new chats, so it refuses workspace-scoped lists.
const catalog = settled
? settled.catalog && withoutUnprovenNewLaunchDefault(settled.catalog)
: target
? readHostModelCatalogSnapshot(target, agent, SETTINGS_LAUNCH)
: undefined
const listed = catalog && catalog.origin !== 'unknown' && catalog.models.length > 0
return { catalog, usesSeedModels: !listed && (!target || settled !== null) }
}
@@ -15,7 +15,7 @@ import {
isClientHostedBrowserRowSelectionLive,
useClientHostedBrowserRowSelection,
useClientHostedBrowserRows
} from '@/lib/pane-manager/client-hosted-browser-row-state'
} from '@/runtime/browser/client-hosting/client-hosted-browser-row-state'
import { ClientHostedBrowserHostRowPane } from '../client-hosted-browser-host-row-pane'
import { useAnyBrowserPageMountAdmission } from '../host-guest/browser-page-mount-admission'
@@ -69,8 +69,9 @@ vi.mock('./browser-page-pane', () => ({
return <span data-browser-page-id={props.browserTab.id} />
}
}))
import { hydrateBrowserDrivers } from '@/lib/pane-manager/browser-mobile-driver-state'
import { hydrateBrowserRemoteViewerPages } from '@/lib/pane-manager/browser-remote-viewer-state'
import { hydrateBrowserDrivers } from '@/runtime/browser/ownership/browser-mobile-driver-state'
import '@/runtime/browser/ownership/browser-remote-viewer-state'
import { hydrateBrowserRemoteViewerPages } from '@/runtime/browser/ownership/browser-remote-viewer-store'
import BrowserPane from './browser-workspace-pane'
const WORKSPACE_ID = 'ws-1'
@@ -11,8 +11,8 @@ import {
IDLE_BROWSER_DRIVER,
useBrowserDriverForPage,
useBrowserMobileDrivenPageIds
} from '@/lib/pane-manager/browser-mobile-driver-state'
import { useBrowserRemotelyViewedPageIds } from '@/lib/pane-manager/browser-remote-viewer-state'
} from '@/runtime/browser/ownership/browser-mobile-driver-state'
import { useBrowserRemotelyViewedPageIds } from '@/runtime/browser/ownership/browser-remote-viewer-state'
import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour'
import { getBrowserPageRuntimeEnvironmentId } from '../describe-page/browser-page-url-display'
import type { BrowserChromeShortcutScope } from '../describe-page/browser-page-types'
@@ -3,7 +3,7 @@ import { isWebviewDragPassthroughActive } from './host-guest/webview-drag-passth
import {
isBrowserPageRemotelyViewed,
onBrowserRemoteViewerChange
} from '../../lib/pane-manager/browser-remote-viewer-store'
} from '../../runtime/browser/ownership/browser-remote-viewer-store'
import type { BrowserClientRetainedRendererPage } from './browser-client-page-retained-state'
export function syncBrowserClientPagePaintRetention(page: BrowserClientRetainedRendererPage): void {
@@ -1,76 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { BrowserWorkspace } from '../../../../../shared/browser-workspace-types'
import { browserTabsVetoGuestEviction } from './browser-guest-eviction-veto'
import { selectBrowserGuestEvictionWorktreeIds } from './browser-guest-worktree-retention'
import { hydrateBrowserDrivers } from '../../../lib/pane-manager/browser-mobile-driver-state'
import { hydrateBrowserRemoteViewerPages } from '../../../lib/pane-manager/browser-remote-viewer-state'
import { installBrowserPageDownloadActivityTracking } from '../navigate/browser-page-download-activity'
// Eviction destroys guests, permanently ending paired-client streams; paint retention must veto it too.
const WATCHED_PAGE = 'page-watched'
const WATCHED_WORKTREE = 'wt-watched'
function tabsFor(pageId: string): BrowserWorkspace[] {
return [{ id: 'tab-1', pageIds: [pageId] } as unknown as BrowserWorkspace]
}
/** Six over-budget hidden worktrees, so only the veto can spare the watched one. */
function evictionRun(tabs: readonly BrowserWorkspace[]): string[] {
return selectBrowserGuestEvictionWorktreeIds({
orderedWorktreeIds: ['wt-a', 'wt-b', 'wt-c', 'wt-d', 'wt-e', WATCHED_WORKTREE],
activeWorktreeId: 'wt-active',
isRetained: () => true,
holdsLiveGuests: () => true,
isEvictable: (worktreeId) =>
worktreeId === WATCHED_WORKTREE ? !browserTabsVetoGuestEviction(tabs) : true
})
}
describe('browser guest eviction veto', () => {
beforeEach(() => {
hydrateBrowserDrivers([])
hydrateBrowserRemoteViewerPages([])
})
// Parking preserves downloads; eviction unregisters the guest and main cancels them as on tab close.
it('spares a page that is still writing a download', () => {
let emitDownloadRequested: (event: {
downloadId: string
browserPageId: string
}) => void = () => {}
const noop = (): void => {}
vi.stubGlobal('window', {
api: {
browser: {
onDownloadRequested: (callback: typeof emitDownloadRequested) => {
emitDownloadRequested = callback
return noop
},
onDownloadProgress: () => noop,
onDownloadFinished: () => noop
}
}
})
const stopDownloadTracking = installBrowserPageDownloadActivityTracking()
try {
expect(browserTabsVetoGuestEviction(tabsFor(WATCHED_PAGE))).toBe(false)
expect(evictionRun(tabsFor(WATCHED_PAGE))).toContain(WATCHED_WORKTREE)
emitDownloadRequested({ downloadId: 'dl-1', browserPageId: WATCHED_PAGE })
expect(browserTabsVetoGuestEviction(tabsFor(WATCHED_PAGE))).toBe(true)
expect(evictionRun(tabsFor(WATCHED_PAGE))).not.toContain(WATCHED_WORKTREE)
} finally {
stopDownloadTracking()
vi.unstubAllGlobals()
}
})
it('holds the veto for a viewer on a non-active page of the same tab', () => {
const tabs = [
{ id: 'tab-1', activePageId: 'page-front', pageIds: ['page-front', WATCHED_PAGE] }
] as unknown as BrowserWorkspace[]
hydrateBrowserRemoteViewerPages([WATCHED_PAGE])
expect(evictionRun(tabs)).not.toContain(WATCHED_WORKTREE)
})
})
@@ -5,12 +5,12 @@ import {
isBrowserPageMobileDriven,
onBrowserDriverChange,
useBrowserMobileDriverForAny
} from '../../../lib/pane-manager/browser-mobile-driver-state'
} from '../../../runtime/browser/ownership/browser-mobile-driver-state'
import { useBrowserRemoteViewerForAny } from '../../../runtime/browser/ownership/browser-remote-viewer-state'
import {
isBrowserPageRemotelyViewed,
onBrowserRemoteViewerChange,
useBrowserRemoteViewerForAny
} from '../../../lib/pane-manager/browser-remote-viewer-state'
onBrowserRemoteViewerChange
} from '../../../runtime/browser/ownership/browser-remote-viewer-store'
import {
isBrowserAutomationVisible,
onBrowserAutomationVisibilityChange,
@@ -11,7 +11,7 @@ import {
import {
createCoalescedPollRunner,
type CoalescedPollRunner
} from '../../../../lib/repository-refresh/coalesced-poll-runner'
} from '../../../../lib/source-control/refresh/coalesced-poll-runner'
import type { ChecksPanelControllerState } from '../use-checks-panel-controller-state'
import type { ChecksPanelReviewState } from '../use-checks-panel-review-state'
import type { ChecksPanelContextState } from '../use-checks-panel-context-state'
@@ -1,7 +1,7 @@
import {
slowTaskRequiredIdleMs,
type SlowTaskBackoffOptions
} from '../../../../lib/repository-refresh/coalesced-poll-runner'
} from '../../../../lib/source-control/refresh/coalesced-poll-runner'
export type GitStatusRefreshReason = 'activity' | 'safety'
@@ -7,7 +7,7 @@ import { getRuntimeGitConflictOperation } from '@/runtime/source-control/git/run
import {
createCoalescedPollRunner,
type SlowTaskBackoffOptions
} from '../../../../lib/repository-refresh/coalesced-poll-runner'
} from '../../../../lib/source-control/refresh/coalesced-poll-runner'
import {
installWindowVisibilityInterval,
isWindowVisible
@@ -8,7 +8,7 @@ import { useAppStore } from '@/store/index'
import { createLoadingBranchCompareSummary } from '@/store/slices/editor/git/branch-compare-state'
import type { GitUpstreamStatus } from '../../../../../../shared/git/status/git-status-types'
import { shouldClearBranchCompareForMissingBase } from '../../../../../../shared/source-control/decisions/source-control-base-ref-resolution'
import { slowTaskRequiredIdleMs } from '../../../../lib/repository-refresh/coalesced-poll-runner'
import { slowTaskRequiredIdleMs } from '../../../../lib/source-control/refresh/coalesced-poll-runner'
import { useBranchCompareRefreshTriggers } from './use-branch-compare-refresh-triggers'
// Slow polls idle for their own duration; explicit mutation/base/manual refreshes remain immediate.
@@ -257,6 +257,13 @@ export function AgentLaunchSettingsCatalog({
<AgentLaunchChoiceEditor
permissionControlRef={permissionControlRef}
showArguments={isDetected}
catalogTarget={
detectionTarget.kind === 'ssh'
? null
: detectionTarget.kind === 'runtime'
? { kind: 'environment', environmentId: detectionTarget.environmentId }
: { kind: 'local' }
}
agent={agent.id}
label={agent.label}
choices={settings.agentChoices?.defaults[agent.id]}
@@ -1,78 +0,0 @@
// @vitest-environment happy-dom
import { act, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
import { expect, it, vi } from 'vitest'
import type { AppState } from '@/store/types'
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
import type { WorktreeContextMenuModel } from './use-worktree-context-menu-model'
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: replaced before rendering with every store field read by the production selector.
const mocks = vi.hoisted(() => ({ state: {} as AppState }))
vi.mock('@/store', () => ({
useAppStore: (select: (s: AppState) => unknown) => select(mocks.state)
}))
vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => '⌘⇧⌫' }))
vi.mock('@/i18n/use-translate', () => ({
useTranslate: () => (_key: string, fallback: string) => fallback
}))
vi.mock('@/components/ui/dropdown-menu', () => ({
DropdownMenuItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuShortcut: ({ children }: { children: ReactNode }) => <kbd>{children}</kbd>
}))
import { WorktreeContextMenuDeleteItems } from './WorktreeContextMenuDeleteItems'
it('advertises the shortcut only on the committed paired copy when physical host and instance match', () => {
const inactive = makeWorktree({
id: 'repo::/checkout',
repoId: 'repo',
hostId: 'ssh:builder',
runtimeOwnerEnvironmentId: 'server-b'
})
const active = { ...inactive, runtimeOwnerEnvironmentId: 'server-a' }
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the isolated store mock supplies every field read by the production selector.
mocks.state = {
activeView: 'terminal',
activeWorktreeId: active.id,
activeWorkspaceExecutionHostId: 'runtime:server-a',
activePendingCreationId: null,
pendingWorktreeCreations: {},
worktreesByRepo: { repo: [inactive, active] },
repos: [],
folderWorkspaces: [],
projectGroups: [],
deleteStateByWorktreeId: {}
} as unknown as AppState
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const model = (worktree: typeof inactive) =>
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture supplies every model field read by DeleteItems; other menu sections never render.
({
worktree,
batchDeleteWorktrees: [],
contextDeletePending: false,
handleDelete: vi.fn(),
isMultiContext: false,
lineageDescendantCount: 0,
removesProject: false
}) as unknown as WorktreeContextMenuModel
try {
act(() =>
root.render(
<>
<section data-copy="inactive">
<WorktreeContextMenuDeleteItems model={model(inactive)} />
</section>
<section data-copy="active">
<WorktreeContextMenuDeleteItems model={model(active)} />
</section>
</>
)
)
expect(container.querySelector('[data-copy="inactive"] kbd')).toBeNull()
expect(container.querySelector('[data-copy="active"] kbd')).not.toBeNull()
} finally {
act(() => root.unmount())
container.remove()
}
})
@@ -1,283 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AppState } from '@/store/types'
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture'
import { TEST_REPO } from '@/store/repos/repo.test-fixture'
const mocks = vi.hoisted(() => ({
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: replaced before each test with every store field read by these shortcut callers.
state: {} as AppState,
deleteWorktree: vi.fn(),
folder: vi.fn()
}))
vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.state } }))
vi.mock('./delete-worktree-flow', () => ({ runWorktreeDelete: mocks.deleteWorktree }))
vi.mock('./folder-workspace-delete', () => ({ deleteFolderWorkspaceUnlessUnsaved: mocks.folder }))
vi.mock('@/components/floating-terminal/floating-workspace-terminal-actions', () => ({
isFloatingWorkspacePanelFocused: () => false
}))
import { createAppCommandHandlers, type AppShortcutState } from '@/app-shell/app-command-handlers'
import { registerWorkspaceShortcutIpcBridge } from '@/hooks/ipc-events/workspace-shortcut-ipc-bridge'
import {
createWorktreeContextMenuDeleteIntent,
runWorktreeContextMenuDeleteIntent
} from '../context-menu/worktree-context-menu-delete-intent'
const active = makeWorktree({ id: 'active', repoId: 'repo1', hostId: 'local', instanceId: 'a' })
const other = makeWorktree({ id: 'other', repoId: 'repo1', hostId: 'local', instanceId: 'b' })
let ipcDelete: () => void
function runRenderer(): void {
const state: AppShortcutState = {
activeView: 'terminal',
activeWorktreeId: 'active',
actions: {
toggleSidebar: vi.fn(),
toggleRightSidebar: vi.fn(),
setRightSidebarOpen: vi.fn(),
setRightSidebarTab: vi.fn(),
showRightSidebarFiles: vi.fn(),
showRightSidebarSearch: vi.fn(),
openDiffNotesSendMenuForActiveWorktree: vi.fn()
},
creationLayoutActive: false,
floatingTerminalEnabled: false,
floatingTerminalOpen: false,
floatingVisibleTabCount: 0,
keybindings: {},
openFloatingWorkspaceMaximized: vi.fn(),
pluginCommands: [],
setFloatingTerminalOpen: vi.fn(),
terminalShortcutPolicy: 'orca-first',
workspaceChromeActive: true
}
createAppCommandHandlers(state, undefined, 'app', true).get('workspace.delete')?.()
}
beforeEach(() => {
vi.clearAllMocks()
mocks.folder.mockReturnValue(null)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this isolated store mock supplies every field read by the tested production paths.
mocks.state = {
activeView: 'terminal',
activeModal: 'none',
activeWorktreeId: 'active',
activeWorkspaceExecutionHostId: 'local',
activePendingCreationId: null,
pendingWorktreeCreations: {},
repos: [TEST_REPO],
worktreesByRepo: { repo1: [active, other] },
folderWorkspaces: [],
projectGroups: [],
deleteStateByWorktreeId: {}
} as unknown as AppState
const noop = () => () => {}
Object.defineProperty(window, 'api', {
configurable: true,
value: {
ui: {
onOpenQuickOpen: noop,
onToggleQuickCommandsMenu: noop,
onOpenNewWorkspace: noop,
onDeleteCurrentWorkspace: (callback: () => void) => {
ipcDelete = callback
return () => {}
},
onOpenTasks: noop,
onJumpToWorktreeIndex: noop,
onJumpToTabIndex: noop,
onWorktreeHistoryNavigate: noop,
onToggleStatusBar: noop
}
}
})
registerWorkspaceShortcutIpcBridge([])
const query = document.querySelectorAll.bind(document)
vi.spyOn(document, 'querySelectorAll').mockImplementation((selector) =>
query(selector.replace(':hover', '[data-hovered]'))
)
document.body.innerHTML =
'<div data-worktree-sidebar><div role="option" data-worktree-id="other" data-worktree-host-identity="local|other" data-hovered></div></div>'
})
afterEach(() => {
document.body.innerHTML = ''
vi.restoreAllMocks()
})
describe.each([
['renderer', runRenderer],
['main IPC', () => ipcDelete()]
] as const)('%s delete shortcut', (_name, run) => {
it('targets the active instance while a different row is hovered, but menu clicks keep their row', () => {
run()
expect(mocks.deleteWorktree).toHaveBeenCalledExactlyOnceWith('active', {
expectedHostId: 'local',
expectedInstanceId: 'a'
})
runWorktreeContextMenuDeleteIntent(
createWorktreeContextMenuDeleteIntent({
worktree: other,
batchDeleteWorktrees: [],
isMultiContext: false
})
)
expect(mocks.deleteWorktree).toHaveBeenLastCalledWith('other', {
expectedHostId: 'local',
expectedInstanceId: 'b'
})
})
it('works with no sidebar or hovered row', () => {
document.body.innerHTML = ''
run()
expect(mocks.deleteWorktree).toHaveBeenCalledExactlyOnceWith('active', {
expectedHostId: 'local',
expectedInstanceId: 'a'
})
})
it('pins the active host when another host publishes the same ID', () => {
mocks.state.worktreesByRepo = {
repo1: [active, { ...active, hostId: 'ssh:builder', instanceId: 'remote' }]
}
mocks.state.activeWorkspaceExecutionHostId = 'ssh:builder'
run()
expect(mocks.deleteWorktree).toHaveBeenCalledExactlyOnceWith('active', {
expectedHostId: 'ssh:builder',
expectedInstanceId: 'remote'
})
})
it('resolves legacy local ownership without inventing a stamped host', () => {
mocks.state.worktreesByRepo = { repo1: [{ ...active, hostId: undefined }] }
run()
expect(mocks.deleteWorktree).toHaveBeenCalledExactlyOnceWith('active', {
expectedInstanceId: 'a'
})
})
it('keeps a paired logical host bound to its physical row', () => {
mocks.state.worktreesByRepo = {
repo1: [{ ...active, hostId: 'ssh:builder', runtimeOwnerEnvironmentId: 'build' }]
}
mocks.state.activeWorkspaceExecutionHostId = 'runtime:build'
run()
expect(mocks.deleteWorktree).toHaveBeenCalledExactlyOnceWith('active', {
expectedHostId: 'ssh:builder',
expectedInstanceId: 'a'
})
})
it('refuses an ambiguous unqualified active ID', () => {
mocks.state.activeWorkspaceExecutionHostId = null
mocks.state.worktreesByRepo = { repo1: [active, { ...active, hostId: 'ssh:builder' }] }
run()
expect(mocks.deleteWorktree).not.toHaveBeenCalled()
})
it('routes the active folder to its qualified owner', () => {
mocks.state.activeWorktreeId = 'folder:folder-1'
mocks.state.activeWorkspaceExecutionHostId = 'ssh:builder'
mocks.state.folderWorkspaces = [
makeFolderWorkspace({ executionHostId: 'local' }),
makeFolderWorkspace({ executionHostId: 'ssh:builder' })
]
run()
expect(mocks.folder).toHaveBeenCalledExactlyOnceWith(
expect.any(Function),
'folder-1',
'ssh:builder'
)
expect(mocks.deleteWorktree).not.toHaveBeenCalled()
})
it.each(['settings', 'activity', 'space', 'tasks'] as const)(
'refuses behind the %s view',
(activeView) => {
mocks.state.activeView = activeView
run()
expect(mocks.deleteWorktree).not.toHaveBeenCalled()
}
)
it('refuses while a creation surface owns the workspace', () => {
mocks.state.activePendingCreationId = 'pending'
mocks.state.pendingWorktreeCreations = {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: creation eligibility reads only status and loaderVisible.
pending: {
status: 'error',
loaderVisible: true
} as AppState['pendingWorktreeCreations'][string]
}
run()
expect(mocks.deleteWorktree).not.toHaveBeenCalled()
})
it('refuses a local dialog with button focus even when activeModal is none', () => {
const dialog = document.createElement('div')
dialog.role = 'dialog'
dialog.innerHTML = '<button>Cancel</button>'
document.body.append(dialog)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: overlay visibility reads only the returned rectangle count.
vi.spyOn(dialog, 'getClientRects').mockReturnValue([
new DOMRect(0, 0, 300, 200)
] as unknown as DOMRectList)
dialog.querySelector('button')?.focus()
run()
expect(mocks.deleteWorktree).not.toHaveBeenCalled()
})
it('allows an ordinary context menu without changing the active target', () => {
document.body.insertAdjacentHTML(
'beforeend',
'<div role="menu"><button role="menuitem">Delete</button></div>'
)
const menu = document.querySelector('[role="menu"]')
if (!menu) {
throw new Error('Missing menu')
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: overlay visibility reads only the returned rectangle count.
vi.spyOn(menu, 'getClientRects').mockReturnValue([
new DOMRect(0, 0, 300, 200)
] as unknown as DOMRectList)
document.querySelector('button')?.focus()
run()
expect(mocks.deleteWorktree).toHaveBeenCalledExactlyOnceWith('active', {
expectedHostId: 'local',
expectedInstanceId: 'a'
})
})
it.each(['missing', 'primary', 'deleting', 'modal', 'editable'] as const)(
'refuses %s targets or focus',
(guard) => {
if (guard === 'missing') {
mocks.state.activeWorktreeId = 'missing'
}
if (guard === 'primary') {
mocks.state.worktreesByRepo = { repo1: [{ ...active, isMainWorktree: true }] }
}
if (guard === 'deleting') {
mocks.state.deleteStateByWorktreeId = {
'local|active': {
isDeleting: true,
error: null,
canForceDelete: false,
forceDeleteReason: null
}
}
}
if (guard === 'modal') {
mocks.state.activeModal = 'delete-worktree'
}
if (guard === 'editable') {
document.body.insertAdjacentHTML('beforeend', '<input>')
document.querySelector('input')?.focus()
}
run()
expect(mocks.deleteWorktree).not.toHaveBeenCalled()
}
)
})
@@ -9,9 +9,9 @@ import {
parseExecutionHostId,
toRuntimeExecutionHostId,
toSshExecutionHostId
} from '../../../../shared/execution-host'
import type { DesktopSidebarFacts } from '../../../../shared/sidebar-list/desktop-sidebar-facts'
import { folderWorkspaceKey } from '../../../../shared/workspace-scope'
} from '../../../../../../shared/execution-host'
import type { DesktopSidebarFacts } from '../../../../../../shared/sidebar-list/desktop-sidebar-facts'
import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope'
type WindowFactsState = Pick<
AppState,
@@ -33,12 +33,12 @@ import { sidebarWorkspaceRowFilters } from '../controls/sidebar-filter-actions'
import {
readWindowWorkspaceActivityFacts,
toLocallyOwnedRows
} from '@/lib/sidebar-shadow/workspace-activity-shadow'
import { readWindowDesktopSidebarFacts } from '@/lib/sidebar-shadow/desktop-facts-shadow'
} from '@/components/sidebar/worktree-list/parity/sidebar-workspace-activity.test-fixture'
import { readWindowDesktopSidebarFacts } from '@/components/sidebar/worktree-list/parity/sidebar-desktop-facts.test-fixture'
import {
readWindowPairedServerHosts,
readWindowPairedServerRows
} from '@/lib/sidebar-shadow/paired-server-rows-shadow'
} from '@/components/sidebar/worktree-list/parity/sidebar-paired-server-rows.test-fixture'
import type { SidebarInputsFeedDomain } from '../../../../../../main/runtime/sidebar-inputs/sidebar-inputs-feed'
import type { SidebarFeedDomains } from '../../../../../../shared/sidebar-list/sidebar-feed-domains'
import { buildSidebarFeedCatalog } from '../../../../../../shared/sidebar-list/sidebar-feed-catalog'
@@ -5,22 +5,22 @@ import {
import type { AppState } from '@/store/types'
import { getIndexedAllWorktrees } from '@/store/slices/worktrees/listing/worktree-catalog-index'
import { getIndexedRepoMap } from '@/store/repos/repository-catalog-index'
import { projectResolvedWorktreeLineage } from '../../../../shared/resolved-worktree-lineage'
import type { WorktreeLineage } from '../../../../shared/worktree/lineage-types'
import { folderWorkspaceToWorktree } from '../../../../shared/folder-workspaces/folder-workspace-worktree'
import { projectResolvedWorktreeLineage } from '../../../../../../shared/resolved-worktree-lineage'
import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types'
import { folderWorkspaceToWorktree } from '../../../../../../shared/folder-workspaces/folder-workspace-worktree'
import {
pairedServerRowOfWorktree,
type PairedServerHostFacts,
type PairedServerWorkspaceRow
} from '../../../../shared/sidebar-list/paired-server-rows'
import { describePairedServerHosts } from '../../../../shared/remote-runtime/host-catalog/paired-server-hosts'
import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-overrides'
import { getWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity'
import type { Worktree } from '../../../../shared/worktree/types'
import { lineageStoreKeyOfRow } from '../../../../shared/worktree/cross-store-lineage-resolution'
import { validCrossStoreLineage } from '../../../../shared/worktree/cross-store-lineage-records'
import { worktreeWorkspaceKey } from '../../../../shared/workspace-scope'
import { folderLineageEdgeOf } from '../../../../shared/worktree/folder-lineage-parents'
} from '../../../../../../shared/sidebar-list/paired-server-rows'
import { describePairedServerHosts } from '../../../../../../shared/remote-runtime/host-catalog/paired-server-hosts'
import { getHostDisplayLabelOverrides } from '../../../../../../shared/host-setting-overrides'
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
import type { Worktree } from '../../../../../../shared/worktree/types'
import { lineageStoreKeyOfRow } from '../../../../../../shared/worktree/cross-store-lineage-resolution'
import { validCrossStoreLineage } from '../../../../../../shared/worktree/cross-store-lineage-records'
import { worktreeWorkspaceKey } from '../../../../../../shared/workspace-scope'
import { folderLineageEdgeOf } from '../../../../../../shared/worktree/folder-lineage-parents'
/** The paired-server rows the window fetched itself, keyed by host-qualified id, for these hosts. */
export function readWindowPairedServerRows(
@@ -6,18 +6,18 @@ import type { AppState } from '@/store/types'
import { getIndexedAllWorktrees } from '@/store/slices/worktrees/listing/worktree-catalog-index'
import { getIndexedRepoMap } from '@/store/repos/repository-catalog-index'
import { getLiveAgentStatusByWorktreeId } from '@/lib/workspace/activity/worktree-activity-state'
import { tabHasLivePty } from '../../../../shared/tab-has-live-pty'
import { tabHasLivePty } from '../../../../../../shared/tab-has-live-pty'
import { getWorktreeIdsWithStructuredChat } from '@/components/sidebar/worktree-list/listing/visible-worktree-activity-inputs'
import {
getRepoExecutionHostId,
parseExecutionHostId,
type ExecutionHostId
} from '../../../../shared/execution-host'
import { folderWorkspaceKey } from '../../../../shared/workspace-scope'
} from '../../../../../../shared/execution-host'
import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope'
import {
isIdleWorkspaceActivity,
type WorkspaceActivityFacts
} from '../../../../shared/sidebar-list/workspace-activity-facts'
} from '../../../../../../shared/sidebar-list/workspace-activity-facts'
/** The window's own activity facts, from the same store slices the sidebar filter reads. */
export function readWindowWorkspaceActivityFacts(
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest'
import { useAppStore } from '@/store'
import { useAppStore } from '@/store/index'
import { makeWorktree } from '@/components/worktree-jump/worktree-jump-palette-test-fixtures'
import { toLocallyOwnedRows } from './workspace-activity-shadow'
import { toLocallyOwnedRows } from './sidebar-workspace-activity.test-fixture'
describe('toLocallyOwnedRows', () => {
it('leaves out an id a paired server also lists, since bare-id activity names no one host', () => {
@@ -1,7 +1,7 @@
import { useEffect } from 'react'
import type { ExecutionHostId } from '../../../../shared/execution-host'
import { useAppStore } from '@/store'
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval'
import { findWorktreeReviewOwner } from '@/store/github/refresh/worktree-refresh'
/** Re-reads the worktree's current linked issue in this window's store; fresh-gated by fetchIssue. */
@@ -6,7 +6,7 @@ import type { ClientHostedBrowserRow } from '../../../../shared/client-hosted-br
import {
selectClientHostedBrowserRow,
useActiveClientHostedBrowserRowId
} from '@/lib/pane-manager/client-hosted-browser-row-state'
} from '@/runtime/browser/client-hosting/client-hosted-browser-row-state'
import { closeClientHostedBrowserRow } from '../../runtime/browser/closing/client-hosted-browser-row-close'
import ClientHostedBrowserTab from './ClientHostedBrowserTab'
@@ -9,7 +9,7 @@ import { usePluginNewFileMenuOptions } from './use-plugin-new-file-menu-options'
import { useTabBarItemProjection } from './use-tab-bar-item-projection'
import { renderTabBarSurface } from './tab-bar-surface'
import { useTabBarItemActions } from './use-tab-bar-item-actions'
import { useActiveClientHostedBrowserRowId } from '@/lib/pane-manager/client-hosted-browser-row-state'
import { useActiveClientHostedBrowserRowId } from '@/runtime/browser/client-hosting/client-hosted-browser-row-state'
import { useEditorGroupFileDropOwner } from '../editor/use-editor-group-file-drop-owner'
import { useTranslate } from '@/i18n/use-translate'
@@ -1,271 +0,0 @@
// @vitest-environment happy-dom
import { act, startTransition, Suspense, use } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { clearClientHostedBrowserRowSelection } from '@/lib/pane-manager/client-hosted-browser-row-state'
import type { TabBarItem } from './tab-bar-item-model'
import type { WorkspaceVisibleTabType } from '../../../../shared/tab-types'
import type { AgentType } from '../../../../shared/agent-status/contracts/agent-status-types'
import {
renderTabBarItems,
type TabBarItemSurfaceProps,
type TabBarItemSurfaceRuntime
} from './tab-bar-item-surface'
import { useTabBarItemActions } from './use-tab-bar-item-actions'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
type TabProps = {
tab?: { id: string; title: string }
agent?: string | null
nativeChat?: { sessionId: string; agent: string | undefined }
isActive: boolean
isPinned: boolean
onActivate: (id: string) => void
onDuplicate?: () => void
gitStatus?: string | null
}
const tabRenders: { id: string; props: TabProps }[] = []
vi.mock('./SortableTab', () => ({
default: (props: TabProps) => {
tabRenders.push({ id: props.tab!.id, props })
return null
}
}))
vi.mock('./BrowserTab', () => ({
default: (props: TabProps) => {
tabRenders.push({ id: props.tab!.id, props })
return null
},
getBrowserTabLabel: () => ''
}))
vi.mock('./EditorFileTab', () => ({
default: (props: TabProps & { file: { id: string } }) => {
tabRenders.push({ id: props.file.id, props })
return null
}
}))
/** Rebuilt on every call, like the strip's projections: equal content, never the same objects. */
function buildItems({
terminalPinned = false,
browserTitle = 'Example',
sessionLabel = 'Session',
sessionAgent
}: {
terminalPinned?: boolean
browserTitle?: string
sessionLabel?: string
sessionAgent?: AgentType
} = {}): TabBarItem[] {
return [
{
type: 'terminal',
id: 'terminal-1',
unifiedTabId: 'unified-terminal-1',
isPinned: terminalPinned,
data: {
id: 'terminal-1',
ptyId: null,
worktreeId: 'wt-1',
title: 'zsh',
generatedTitle: 'Fix the login bug',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 0
}
},
{
type: 'browser',
id: 'browser-1',
unifiedTabId: 'unified-browser-1',
isPinned: false,
data: {
id: 'browser-1',
worktreeId: 'wt-1',
url: 'https://example.test',
title: browserTitle,
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 0
}
},
{
type: 'editor',
id: 'file-1',
unifiedTabId: 'unified-file-1',
isPinned: false,
data: {
id: 'file-1',
filePath: '/repo/notes.md',
relativePath: 'notes.md',
worktreeId: 'wt-1',
language: 'markdown',
isPreview: false,
isDirty: false,
mode: 'edit'
}
},
{
type: 'agent-session',
id: 'session-1',
unifiedTabId: 'session-1',
isPinned: false,
data: {
id: 'session-1',
entityId: 'session-1',
groupId: 'group-1',
worktreeId: 'wt-1',
contentType: 'agent-session',
...(sessionAgent ? { agentSessionAgent: sessionAgent } : {}),
label: sessionLabel,
customLabel: null,
color: null,
sortOrder: 3,
createdAt: 0
}
}
]
}
type StripInputs = {
onActivate?: (id: string) => void
generatedTabTitlesEnabled?: boolean
managedBrowserCreationEnabled?: boolean
terminalPinned?: boolean
browserTitle?: string
sessionLabel?: string
sessionAgent?: AgentType
activeTabType?: WorkspaceVisibleTabType
activeClientHostedBrowserRowId?: string | null
statusByRelativePath?: TabBarItemSurfaceRuntime['statusByRelativePath']
}
function Strip({
onActivate = NOOP,
generatedTabTitlesEnabled = false,
managedBrowserCreationEnabled = false,
terminalPinned,
browserTitle,
sessionLabel,
sessionAgent,
activeTabType = 'terminal',
activeClientHostedBrowserRowId = null,
statusByRelativePath = STATUS_BY_RELATIVE_PATH
}: StripInputs): React.JSX.Element {
const props: TabBarItemSurfaceProps = {
worktreeId: 'wt-1',
activeTabId: 'terminal-1',
activeFileId: 'file-1',
activeBrowserTabId: 'browser-1',
activeSimulatorTabId: null,
activeTabType,
expandedPaneByTabId: {}
}
const runtime: TabBarItemSurfaceRuntime = {
resolvedGroupId: 'group-1',
generatedTabTitlesEnabled,
unifiedTabByVisibleId: new Map(),
tabAgentTypesByTabId: {},
nativeChatTabWideFallbackUnsafeTabsById: {},
nativeChatTranscriptIsLocalReadable: false,
managedBrowserCreationEnabled,
statusByRelativePath
}
const actions = useTabBarItemActions({
props: {
worktreeId: 'wt-1',
onActivate,
onActivateFile: onActivate,
onActivateBrowserTab: onActivate,
onActivateAgentSession: onActivate,
onClose: NOOP,
onCloseOthers: NOOP,
onCloseToRight: NOOP,
onCloseToLeft: NOOP,
onSetCustomTitle: NOOP,
onSetTabColor: NOOP,
onTogglePaneExpand: NOOP
},
togglePinned: NOOP,
toggleTabViewMode: NOOP
})
return (
<>
{renderTabBarItems({
items: buildItems({ terminalPinned, browserTitle, sessionLabel, sessionAgent }),
props,
runtime,
actions,
dropIndicatorByVisibleId: new Map(),
includeTopTabBorder: true,
activeClientHostedBrowserRowId
})}
</>
)
}
const NOOP = (): void => {}
const STATUS_BY_RELATIVE_PATH: TabBarItemSurfaceRuntime['statusByRelativePath'] = new Map()
let root: Root | null = null
const NEVER_RESOLVES = new Promise<never>(() => {})
function Suspended(): null {
use(NEVER_RESOLVES)
return null
}
function stripTree(inputs: StripInputs, suspended = false): React.JSX.Element {
return (
<Suspense fallback={null}>
<Strip {...inputs} />
{suspended ? <Suspended /> : null}
</Suspense>
)
}
function renderStrip(inputs: StripInputs = {}): void {
if (!root) {
root = createRoot(document.createElement('div'))
}
act(() => root!.render(stripTree(inputs)))
}
function lastRender(tabId: string): TabProps {
return tabRenders.findLast((render) => render.id === tabId)!.props
}
afterEach(() => {
act(() => root?.unmount())
root = null
tabRenders.length = 0
clearClientHostedBrowserRowSelection()
})
describe('tab strip rows', () => {
it('keeps the committed handler when React abandons a render', async () => {
const committed = vi.fn()
const abandoned = vi.fn()
renderStrip({ onActivate: committed })
await act(async () =>
startTransition(() => root!.render(stripTree({ onActivate: abandoned }, true)))
)
lastRender('terminal-1').onActivate('terminal-1')
expect(committed).toHaveBeenCalledWith('terminal-1')
expect(abandoned).not.toHaveBeenCalled()
})
})
/** Client-hosted rows overlay panes without changing activeTabId; suppress real-tab underlines while they are selected. */
@@ -1,5 +1,5 @@
import { useLayoutEffect, useMemo, useRef } from 'react'
import { clearClientHostedBrowserRowSelection } from '@/lib/pane-manager/client-hosted-browser-row-state'
import { clearClientHostedBrowserRowSelection } from '@/runtime/browser/client-hosting/client-hosted-browser-row-state'
import { noteUserWorkspaceSwitch } from '@/lib/workspace/activation/workspace-switch-user-act'
import { useAppStore } from '@/store'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
@@ -1,118 +0,0 @@
// @vitest-environment happy-dom
import { useEffect, useRef } from 'react'
import { act, cleanup, render, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => {
const state = {
activeWorktreeId: 'wt-active',
rightSidebarOpen: true,
sidebarOpen: true,
groupsByWorktree: {}
}
const useAppStore = (selector: (current: typeof state) => unknown): unknown => selector(state)
useAppStore.getState = () => state
return { capture: vi.fn(), deliver: vi.fn(), monacoSawDrop: vi.fn(), useAppStore }
})
vi.mock('@/store', () => ({ useAppStore: mocks.useAppStore }))
vi.mock('../../store', () => ({ useAppStore: mocks.useAppStore }))
vi.mock('../editor/editor-dropped-file-open', () => ({
captureEditorFileDropOpen: mocks.capture,
editorGroupStillExists: () => true
}))
vi.mock('../tab-bar/TabBar', () => ({ default: () => null }))
vi.mock('../tab-bar/TabBarQuickCommandsButton', () => ({ TabBarQuickCommandsButton: () => null }))
vi.mock('@/lib/pane-manager/client-hosted-browser-row-state', () => ({
useClientHostedBrowserRows: () => []
}))
vi.mock('./useTabGroupWorkspaceModel', () => ({
useTabGroupWorkspaceModel: () => ({
activeTab: { id: 'tab-1', entityId: 'file-1', contentType: 'editor' },
agentSessionItems: [],
browserItems: [],
commands: { focusGroup: () => undefined },
editorItems: [],
tabBarOrder: [],
terminalTabs: [],
groupTabs: [],
expandedPaneByTabId: {}
})
}))
// Stands in for Monaco, which listens for drops on its own DOM node.
vi.mock('../editor/EditorPanel', () => ({
default: function FakeMonaco() {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
const node = ref.current
node?.addEventListener('drop', mocks.monacoSawDrop)
node?.addEventListener('dragover', mocks.monacoSawDrop)
return () => {
node?.removeEventListener('drop', mocks.monacoSawDrop)
node?.removeEventListener('dragover', mocks.monacoSawDrop)
}
}, [])
return (
<div ref={ref} data-testid="monaco">
<textarea data-testid="monaco-input" />
</div>
)
}
}))
import { TooltipProvider } from '@/components/ui/tooltip'
import TabGroupPanel from './TabGroupPanel'
function drag(target: Element, type: 'dragover' | 'drop'): Event {
const transfer = { types: ['Files'], files: [new File(['x'], 'dropped.md')], dropEffect: 'move' }
const event = new Event(type, { bubbles: true, cancelable: true, composed: true })
Object.defineProperty(event, 'dataTransfer', { value: transfer })
Object.defineProperty(event, 'isTrusted', { value: true })
act(() => {
target.dispatchEvent(event)
})
return event
}
beforeEach(() => {
mocks.capture.mockImplementation(() => mocks.deliver)
vi.stubGlobal('api', {
fs: {
getPathForFile: (file: File) => `/Users/me/${file.name}`,
prepareDroppedPaths: async ({ paths }: { paths: string[] }) => ({ paths, failures: [] })
}
})
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
vi.clearAllMocks()
})
describe('TabGroupPanel editor area OS file drops', () => {
it("opens a file dropped on the editor in this group's worktree, and Monaco never sees it", async () => {
const view = render(
<TooltipProvider>
<TabGroupPanel
groupId="group-b"
worktreeId="wt-b"
isVisible
isFocused={false}
hasSplitGroups
touchesLeftEdge={false}
touchesRightEdge={false}
reserveClosedExplorerToggleSpace={false}
reserveCollapsedSidebarHeaderSpace={false}
/>
</TooltipProvider>
)
const input = await view.findByTestId('monaco-input')
drag(input, 'dragover')
const drop = drag(input, 'drop')
expect(drop.defaultPrevented).toBe(true)
expect(mocks.monacoSawDrop).not.toHaveBeenCalled()
expect(mocks.capture).toHaveBeenCalledWith({ worktreeId: 'wt-b', groupId: 'group-b' })
await waitFor(() => expect(mocks.deliver).toHaveBeenCalledWith(['/Users/me/dropped.md']))
})
})
@@ -1,86 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => {
const state = {
activeWorktreeId: 'wt-a',
rightSidebarOpen: true,
sidebarOpen: true,
groupsByWorktree: {}
}
const useAppStore = (selector: (current: typeof state) => unknown): unknown => selector(state)
useAppStore.getState = () => state
return { useAppStore }
})
vi.mock('@/store', () => ({ useAppStore: mocks.useAppStore }))
vi.mock('../../store', () => ({ useAppStore: mocks.useAppStore }))
vi.mock('../tab-bar/TabBar', () => ({ default: () => null }))
vi.mock('../tab-bar/TabBarQuickCommandsButton', () => ({
TabBarQuickCommandsButton: () => null
}))
vi.mock('@/lib/pane-manager/client-hosted-browser-row-state', () => ({
useClientHostedBrowserRows: () => []
}))
vi.mock('./useTabGroupWorkspaceModel', () => ({
useTabGroupWorkspaceModel: () => ({
activeTab: { id: 'tab-1', entityId: 'term-1', contentType: 'terminal' },
agentSessionItems: [],
browserItems: [],
commands: { focusGroup: () => undefined, closeGroup: () => undefined },
editorItems: [],
tabBarOrder: [],
terminalTabs: [],
groupTabs: [],
expandedPaneByTabId: {}
})
}))
import { TooltipProvider } from '@/components/ui/tooltip'
import TabGroupPanel from './TabGroupPanel'
function panel(isFocused: boolean): React.JSX.Element {
return (
<TooltipProvider>
<TabGroupPanel
groupId="group-a"
worktreeId="wt-a"
isVisible
isFocused={isFocused}
hasSplitGroups
touchesLeftEdge={false}
touchesRightEdge={false}
reserveClosedExplorerToggleSpace={false}
reserveCollapsedSidebarHeaderSpace={false}
/>
</TooltipProvider>
)
}
afterEach(cleanup)
describe('TabGroupPanel Pane Actions menu', () => {
it('closes without restoring focus to the old group', async () => {
const view = render(panel(true))
const trigger = view.getByRole('button', { name: 'Pane Actions' })
act(() => {
fireEvent.pointerDown(trigger, {
button: 0,
ctrlKey: false,
pointerType: 'mouse'
})
})
expect(view.queryByRole('menuitem', { name: 'Close split pane' })).not.toBeNull()
await act(async () => {
view.rerender(panel(false))
// Radix restores trigger focus on the next task after its focus scope unmounts.
await new Promise((resolve) => setTimeout(resolve, 0))
})
expect(view.queryByRole('menuitem', { name: 'Close split pane' })).toBeNull()
expect(document.activeElement).not.toBe(trigger)
view.rerender(panel(true))
expect(view.queryByRole('menuitem', { name: 'Close split pane' })).toBeNull()
})
})
@@ -17,7 +17,7 @@ import { useTranslate } from '@/i18n/use-translate'
import type { TabGroup } from '../../../../shared/tab-types'
import { isStructuredTab } from '../../../../shared/agent-session/view/structured-agent-session-tab'
import type { ClientHostedBrowserRow } from '../../../../shared/client-hosted-browser-rows'
import { useClientHostedBrowserRows } from '@/lib/pane-manager/client-hosted-browser-row-state'
import { useClientHostedBrowserRows } from '@/runtime/browser/client-hosting/client-hosted-browser-row-state'
import { resolveClientHostedBrowserRowStripGroupId } from '../tab-bar/client-hosted-browser-row-strip-placement'
import { useEditorGroupFileDropOwner } from '../editor/use-editor-group-file-drop-owner'
import { cn } from '@/lib/class-names'
@@ -99,62 +99,6 @@ describe('remote runtime PTY reattach on a healthy link', () => {
return transport
}
it('reattaches a handle the host still reports ready within seconds of a stream end', async () => {
const transport = await attachHostMirror()
runtimeCall.mockImplementation(async (args: { method: string }) =>
args.method === 'session.tabs.list' || args.method === 'session.tabs.activate'
? readyHostSessionInventoryResponse('terminal-1')
: { ok: true, result: {} }
)
endLatestStream()
await vi.advanceTimersByTimeAsync(2_000)
expect(subscribedTerminalHandles()).toEqual(['terminal-1', 'terminal-1'])
emitSnapshot(latestSubscribePayload().streamId, 'reattached')
expect(transport.isConnected()).toBe(true)
expect(transport.getRecoveryState?.().phase).toBe('connected')
transport.destroy?.()
})
it('keeps reattaching a still-ready handle that ends repeatedly instead of parking', async () => {
const transport = await attachHostMirror()
runtimeCall.mockImplementation(async (args: { method: string }) =>
args.method === 'session.tabs.list' || args.method === 'session.tabs.activate'
? readyHostSessionInventoryResponse('terminal-1')
: { ok: true, result: {} }
)
for (let cycle = 0; cycle < 5; cycle += 1) {
endLatestStream()
await vi.advanceTimersByTimeAsync(10_000)
expect(subscribedTerminalHandles()).toHaveLength(cycle + 2)
emitSnapshot(latestSubscribePayload().streamId, `cycle ${cycle}`)
expect(transport.isConnected()).toBe(true)
expect(transport.getRecoveryState?.().phase).toBe('connected')
}
transport.destroy?.()
})
it('retries a resubscribe whose host answered without a ready handle', async () => {
const transport = await attachHostMirror()
let hostReady = false
runtimeCall.mockImplementation(async (args: { method: string }) =>
args.method === 'session.tabs.list' || args.method === 'session.tabs.activate'
? hostSnapshot(hostReady ? 'ready' : 'pending-handle')
: { ok: true, result: {} }
)
endLatestStream()
await vi.advanceTimersByTimeAsync(16_000)
expect(subscribedTerminalHandles()).toHaveLength(1)
hostReady = true
await vi.advanceTimersByTimeAsync(5_000)
expect(subscribedTerminalHandles()).toEqual(['terminal-1', 'terminal-1'])
transport.destroy?.()
})
it('retries an attach whose host surface stayed pending past the bounded wait', async () => {
let hostReady = false
runtimeCall.mockImplementation(async (args: { method: string }) =>
@@ -175,34 +175,4 @@ describe('remote runtime pty transport against a relaunched host that has not pu
vi.useRealTimers()
}
})
it('still retires the pane when a published graph lacks its surface', async () => {
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
const onPtyExit = vi.fn()
const transport = createRemoteRuntimePtyTransport('env-1', {
worktreeId: 'wt-1',
tabId: 'web-terminal-host-tab-1',
leafId: 'pane:1',
onPtyExit
})
await transport.connect({ url: '', callbacks: {} })
await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled())
runtimeCall.mockImplementation(async (request: { method: string }) =>
request.method === 'session.tabs.list'
? {
ok: true,
result: {
...UNPUBLISHED_HOST_GRAPH.result,
publicationEpoch: 'epoch-2:client-navigation',
snapshotVersion: 3
}
}
: { ok: false, error: { code: 'runtime_error', message: 'tab_not_found' } }
)
subscriptionCallbacks?.onClose?.()
await vi.waitFor(() => expect(onPtyExit).toHaveBeenCalledWith('remote:env-1@@terminal-1', -1))
expect(transport.getPtyId()).toBeNull()
})
})
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo } from 'react'
import { useAppStore } from '../store'
import { hasFeatureInteraction } from '../../../shared/feature-interactions'
import { setForegroundTerminalTabIds } from '@/components/terminal-pane/parking/retention/foreground-terminal-tabs'
import { useClientHostedBrowserRows } from '@/lib/pane-manager/client-hosted-browser-row-state'
import { useClientHostedBrowserRows } from '@/runtime/browser/client-hosting/client-hosted-browser-row-state'
import { useTerminalProviderSnapshotCapability } from './terminal/use-terminal-provider-snapshot-capability'
import { getEffectiveLayoutForWorktree as getEffectiveLayout } from './terminal/split-group-mount'
import { useContextualTour } from './contextual-tours/use-contextual-tour'
@@ -1,6 +1,7 @@
/** Keep live DOM/store census reads outside the typing probe’s sampling loop: focused pane/screen, mounted rows and listener counts. */
import { useAppStore } from '@/store'
import { listProbePanes, paneRootElement, type ProbePane } from './echo-instrumentation'
import { useAppStore } from '@/store/index'
import './echo-instrumentation'
import { listProbePanes, paneRootElement, type ProbePane } from './pane-target'
import type { FocusedPaneCensus } from './diagnostic-summary'
type ProbeStoreState = {
@@ -61,4 +62,4 @@ export function countMountedAgentRows(): number | null {
}
}
export { readStoreListenerCount } from '@/store/diagnostics/store-listener-census'
import '@/store/diagnostics/store-listener-census'
@@ -1,9 +1,5 @@
import {
countMountedAgentRows,
readFocusedPaneCensus,
readProbeStoreState,
readStoreListenerCount
} from './census-probe'
import { countMountedAgentRows, readFocusedPaneCensus, readProbeStoreState } from './census-probe'
import { readStoreListenerCount } from '../../store/diagnostics/store-listener-census'
import {
summarizeLatencySamples,
summarizeTypingScaleCensus,
@@ -11,7 +7,9 @@ import {
type LatencyPercentiles,
type TypingScaleCensus
} from './diagnostic-summary'
import { listProbePanes, type InstrumentedPane } from './echo-instrumentation'
import './echo-instrumentation'
import type { InstrumentedPane } from './echo-instrumentation'
import { listProbePanes } from './pane-target'
import {
emptyInputSourceBreakdown,
type InputSourceBreakdown,
@@ -2,16 +2,14 @@
import {
detachPaneEcho,
discardUndispatchedKeystroke,
drainTimedOutEchoCandidates,
findPaneOwningFocus,
findPaneOwningNode,
instrumentPaneEcho,
listProbePanes,
noteEchoOutputArrival,
recordKeystroke,
type EchoObservation,
type InstrumentedPane
} from './echo-instrumentation'
import { drainTimedOutEchoCandidates } from './echo-candidate-timeout'
import { findPaneOwningFocus, findPaneOwningNode, listProbePanes } from './pane-target'
import type { EchoObservation } from './echo-observation'
import { setTerminalOutputArrivalObserver } from '@/lib/pane-manager/terminal-output-arrival-observer'
import { observeRendererLongTasks } from './renderer-long-tasks'
import {
@@ -28,8 +26,6 @@ import {
TYPING_LATENCY_SAMPLE_LIMIT
} from './sample-window'
export type { TypingLatencyReport } from './diagnostic-report'
let active: ProbeState | null = null
let lastState: ProbeState | null = null
let cachedAppVersion: string | null = null
@@ -0,0 +1,204 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { instrumentPaneEcho, recordKeystroke, type InstrumentedPane } from './echo-instrumentation'
import type { EchoObservation } from './echo-observation'
type FakeTerminal = {
write: (data: string | Uint8Array, callback?: () => void) => void
onData: (listener: (data: string) => void) => { dispose: () => void }
onWriteParsed: (listener: () => void) => { dispose: () => void }
onRender: (listener: () => void) => { dispose: () => void }
}
function fakeTerminal(): {
terminal: FakeTerminal
emitData: (data?: string) => void
emitParsed: () => void
emitRender: () => void
writtenPayloads: (string | Uint8Array)[]
} {
const dataListeners = new Set<(data: string) => void>()
const parsedListeners = new Set<() => void>()
const renderListeners = new Set<() => void>()
const writtenPayloads: (string | Uint8Array)[] = []
const listen = <T>(listeners: Set<T>, listener: T): { dispose: () => void } => {
listeners.add(listener)
return {
dispose: () => {
listeners.delete(listener)
}
}
}
return {
terminal: {
write: (data) => writtenPayloads.push(data),
onData: (listener) => listen(dataListeners, listener),
onWriteParsed: (listener) => listen(parsedListeners, listener),
onRender: (listener) => listen(renderListeners, listener)
},
emitData: (data = 'x') => dataListeners.forEach((listener) => listener(data)),
emitParsed: () => parsedListeners.forEach((listener) => listener()),
emitRender: () => renderListeners.forEach((listener) => listener()),
writtenPayloads
}
}
function recordAndDispatch(
entry: InstrumentedPane,
fake: ReturnType<typeof fakeTerminal>,
source: 'direct' | 'ime' = 'direct',
recordedAt: number = performance.now()
): void {
recordKeystroke(entry, recordedAt, source)
fake.emitData()
}
afterEach(() => {
vi.restoreAllMocks()
})
describe('instrumentPaneEcho', () => {
it('does not credit output that arrived before the input dispatched', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordKeystroke(entry, performance.now(), 'direct')
fake.terminal.write('unrelated')
fake.emitParsed()
fake.emitRender()
expect(observations).toEqual([])
fake.emitData()
fake.terminal.write('echo')
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
})
it('emits one ambiguous burst when overlapping inputs receive separate outputs', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake, 'direct')
recordAndDispatch(entry, fake, 'direct')
fake.terminal.write('A')
fake.emitParsed()
fake.emitRender()
fake.terminal.write('B')
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
expect(observations[0]).toMatchObject({
attribution: 'ambiguous-burst',
reason: 'overlapping-inputs',
inputCount: 2,
sourceCounts: { direct: 2, ime: 0 },
outputBatchBytes: 1,
outputBatchWrites: 1
})
})
it('keeps a batch ambiguous when another input arrives before parsing finishes', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake)
fake.terminal.write('x'.repeat(90))
recordAndDispatch(entry, fake)
fake.terminal.write('x'.repeat(30))
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
expect(observations[0]).toMatchObject({
attribution: 'ambiguous-burst',
inputCount: 2,
outputBatchBytes: 120,
outputBatchWrites: 2
})
})
it('keeps parsed batches separate when two parses precede one render', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake)
fake.terminal.write('a')
fake.emitParsed()
recordAndDispatch(entry, fake)
fake.terminal.write('b')
fake.emitParsed()
fake.emitRender()
expect(observations.map((value) => value.attribution)).toEqual(['single-input', 'single-input'])
})
it('marks the first late output after a timeout as ambiguous, then restores confidence', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
const now = vi.spyOn(performance, 'now')
recordKeystroke(entry, 0, 'direct')
now.mockReturnValueOnce(1)
fake.emitData('A')
expect(recordKeystroke(entry, 5_000, 'direct').unmatched).toBe(1)
now.mockReturnValueOnce(5_001)
fake.emitData('B')
fake.terminal.write('late A')
now.mockReturnValueOnce(5_010)
fake.emitParsed()
now.mockReturnValueOnce(5_015)
fake.emitRender()
recordKeystroke(entry, 5_020, 'ime')
now.mockReturnValueOnce(5_021)
fake.emitData('한')
fake.terminal.write('한')
now.mockReturnValueOnce(5_030)
fake.emitParsed()
now.mockReturnValueOnce(5_035)
fake.emitRender()
expect(observations[0]).toMatchObject({
attribution: 'ambiguous-burst',
reason: 'attribution-gap',
inputCount: 1
})
expect(observations[1]).toMatchObject({
attribution: 'single-input',
source: 'ime'
})
})
it('holds an unparsed input across a render instead of discarding it', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake)
fake.terminal.write('echo')
fake.emitRender()
expect(observations).toHaveLength(0)
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
})
})
@@ -14,44 +14,26 @@ import {
createEchoObservation,
type EchoBatch,
type EchoCandidate,
type EchoObservation as EchoObservationValue,
type EchoObservation,
type RecordedKeystroke
} from './echo-observation'
import type { TypingInputSource } from './input-events'
import type { ProbePane } from './pane-target'
export type {
AmbiguousEchoBurst,
EchoObservation,
EchoSourceCounts,
ExactEchoSample,
RecordedKeystroke
} from './echo-observation'
export {
findPaneOwningFocus,
findPaneOwningNode,
listProbePanes,
paneRootElement
} from './pane-target'
export type { ProbePane } from './pane-target'
export { drainTimedOutEchoCandidates }
import './pane-target'
type Disposable = { dispose: () => void }
export type KeystrokeSource = TypingInputSource
export type PreventedKeystrokeDiscard = 'pending' | 'counted-unmatched' | null
type PendingKeystroke = EchoCandidate
export type InstrumentedPane = {
pane: ProbePane | null
undispatched: PendingKeystroke[]
nextDispatch: PendingKeystroke | null
deferredNextDispatch: PendingKeystroke | null
ignoredDispatches: PendingKeystroke[]
undispatched: EchoCandidate[]
nextDispatch: EchoCandidate | null
deferredNextDispatch: EchoCandidate | null
ignoredDispatches: EchoCandidate[]
ignoredDispatchOverflowedAt: number | null
awaitingEcho: PendingKeystroke[]
awaitingEcho: EchoCandidate[]
attributionGap: boolean
parsingBatch: EchoBatch | null
parsedBatches: EchoBatch[]
@@ -64,7 +46,7 @@ export type InstrumentedPane = {
export function recordKeystroke(
entry: InstrumentedPane,
now: number,
source: KeystrokeSource,
source: TypingInputSource,
eventAt: number | null = null
): RecordedKeystroke {
const dropped = drainTimedOutEchoCandidates(entry, now)
@@ -82,7 +64,7 @@ export function recordKeystroke(
/** Removes a prevented routed commit only if it never reached terminal.onData. */
export function discardUndispatchedKeystroke(
entry: InstrumentedPane,
candidate: PendingKeystroke
candidate: EchoCandidate
): PreventedKeystrokeDiscard {
if (candidate.status === 'unmatched-undispatched') {
const index = entry.ignoredDispatches.lastIndexOf(candidate)
@@ -143,7 +125,7 @@ function updateEchoBatch(entry: InstrumentedPane): EchoBatch | null {
export function instrumentPaneEcho(
pane: ProbePane,
onObservation: (observation: EchoObservationValue) => void
onObservation: (observation: EchoObservation) => void
): InstrumentedPane {
const entry: InstrumentedPane = {
pane,
@@ -1,5 +1,6 @@
import { summarizeLatencySamples, type LatencyPercentiles } from './diagnostic-summary'
import type { EchoObservation, KeystrokeSource } from './echo-instrumentation'
import type { EchoObservation } from './echo-observation'
import type { TypingInputSource } from './input-events'
import {
appendExactLatencySample,
appendTypingLatencySample,
@@ -26,12 +27,12 @@ export type InputSourceLatency = {
outputWritesPerInput: LatencyPercentiles
}
export type InputSourceBreakdown = Record<KeystrokeSource, InputSourceLatency> & {
export type InputSourceBreakdown = Record<TypingInputSource, InputSourceLatency> & {
imeCommitChars: LatencyPercentiles
}
export type InputSourceTally = {
recordInput: (source: KeystrokeSource, text: string) => void
recordInput: (source: TypingInputSource, text: string) => void
addObservation: (observation: EchoObservation) => void
breakdown: () => InputSourceBreakdown
}
@@ -60,7 +61,7 @@ function summarizeSource(tally: SourceTally): InputSourceLatency {
}
export function createInputSourceTally(): InputSourceTally {
const bySource: Record<KeystrokeSource, SourceTally> = {
const bySource: Record<TypingInputSource, SourceTally> = {
direct: emptySourceTally(),
ime: emptySourceTally()
}
@@ -1,7 +1,7 @@
import {
hydrateBrowserRemoteViewerPages,
setRemoteViewersForBrowserPage
} from '../../lib/pane-manager/browser-remote-viewer-store'
} from '../../runtime/browser/ownership/browser-remote-viewer-store'
/** Local guests also render remote workspaces, so their viewer state follows this desktop's IPC. */
export function registerBrowserRemoteViewerIpcBridge(): () => void {
@@ -1,12 +1,12 @@
import {
hydrateBrowserDrivers,
setDriverForBrowserPage
} from '@/lib/pane-manager/browser-mobile-driver-state'
} from '@/runtime/browser/ownership/browser-mobile-driver-state'
import { registerBrowserRemoteViewerIpcBridge } from './browser-remote-viewer-ipc-bridge'
import {
applyClientHostedBrowserRows,
hydrateClientHostedBrowserRows
} from '@/lib/pane-manager/client-hosted-browser-row-state'
} from '@/runtime/browser/client-hosting/client-hosted-browser-row-state'
import type { ClientHostedBrowserRowsEvent } from '../../../../shared/client-hosted-browser-rows'
import { setDriverForPty, hydrateDrivers } from '@/lib/pane-manager/mobile-driver-state'
import { setFitOverride, hydrateOverrides } from '@/lib/pane-manager/mobile-fit-overrides'
@@ -236,7 +236,7 @@ export function registerRuntimeClientIpcBridge(
const runtimeClientEventsSync = createRuntimeClientEventsSync({
getDesiredEnvironmentIds: () => getRuntimeClientEventEnvironmentIds(useAppStore.getState()),
getSubscriptionKey: (environmentId) => buildRuntimeClientEventEnvironmentKey([environmentId]),
subscribe: (environmentId, onEvent, onError, isCurrent) => {
subscribe: (environmentId, onEvent, onError, isCurrent, onClose) => {
const sshGeneration = getEnvironmentSshStateGeneration(environmentId)
const runtimeGeneration = getRuntimeEnvironmentConnectionGeneration(environmentId)
const runtimeRevision = getRuntimeEnvironmentRevision(environmentId)
@@ -271,10 +271,10 @@ export function registerRuntimeClientIpcBridge(
useAppStore.getState().markEnvironmentSshStateStale(environmentId),
hydrateEnvironmentSshState: () =>
hydrateRuntimeEnvironmentSshState(environmentId, { force: true }),
sync: runtimeClientEventsSync.sync
sync: () => runtimeClientEventsSync.sync([environmentId])
})
},
{ hostsBrowserPages: hostsBrowserPagesFor(environmentId) }
{ hostsBrowserPages: hostsBrowserPagesFor(environmentId), onClose }
)
return subscription
},
@@ -111,7 +111,7 @@ type RuntimeEnvironmentStoreSyncSubscriberDeps = {
getReachableEnvironmentIds: (state: RuntimeEnvironmentStoreSyncState) => string[]
requestProjectRefresh: (environmentId: string) => void
markEnvironmentSshStateStale: (environmentId: string) => void
sync: () => void
sync: (recoveryEnvironmentIds?: readonly string[]) => void
}
export type RuntimeEnvironmentStoreSyncSubscriber = (
@@ -170,7 +170,7 @@ export function createRuntimeEnvironmentStoreSyncSubscriber(
}
desiredEnvironmentKey = nextDesiredEnvironmentKey
reachableEnvironmentKey = nextReachableEnvironmentKey
deps.sync()
deps.sync(refreshEnvironmentIds)
} finally {
handlingStoreWrite = false
}
@@ -92,39 +92,6 @@ function focus(surface: 'main' | 'floating'): void {
document.getElementById(surface)?.focus()
}
it('waits for an asynchronously revealed floating panel', async () => {
const { store, fileId, position } = await setup(false)
position(fileId, { line: 300, column: 7 }, true)
flushFrames()
expect(store.getState().pendingEditorReveal).toBeNull()
store.setState({ floatingWorkspacePanelOpen: true })
flushFrames()
expect(store.getState().pendingEditorReveal).toMatchObject({ fileId, line: 300, column: 7 })
})
it('keeps a background floating position deferred until the panel owns keyboard input', async () => {
const { store, fileId, position } = await setup()
focus('main')
position(fileId, { line: 17 }, false)
flushFrames()
expect(store.getState().pendingEditorReveal).toBeNull()
focus('floating')
flushFrames()
expect(store.getState().pendingEditorReveal).toMatchObject({ fileId, line: 17 })
})
it('does not publish after keyboard input moves from the panel to the main surface', async () => {
const { store, fileId, position } = await setup()
focus('floating')
position(fileId, { line: 17 }, true)
focus('main')
flushFrames()
expect(store.getState().pendingEditorReveal).toBeNull()
focus('floating')
flushFrames()
expect(store.getState().pendingEditorReveal).toMatchObject({ fileId, line: 17 })
})
it('cancels a published reveal after an outside click even if DOM focus does not change', async () => {
const { store, fileId, position } = await setup()
focus('main')
@@ -146,35 +113,6 @@ it('does not reclaim input when an asynchronously revealed panel opens after an
expect(store.getState().pendingEditorReveal).toBeNull()
})
it('invalidates a published floating reveal when the panel closes or is disabled', async () => {
const { store, fileId, position } = await setup()
position(fileId, { line: 17 }, true)
flushFrames()
const reveal = store.getState().pendingEditorReveal
expect(reveal?.canApply?.()).toBe(true)
store.setState({ floatingWorkspacePanelOpen: false })
expect(reveal?.canApply?.()).toBe(false)
store.setState({ floatingWorkspacePanelOpen: true })
const settings = store.getState().settings
if (!settings) {
throw new Error('Settings missing')
}
store.setState({ settings: { ...settings, floatingTerminalEnabled: false } })
expect(reveal?.canApply?.()).toBe(false)
})
it('keeps floating input ownership independent of an unrelated main workspace selection', async () => {
const { store, fileId, position } = await setup()
focus('floating')
position(fileId, { line: 300, column: 7 }, true)
flushFrames()
const reveal = store.getState().pendingEditorReveal
expect(reveal?.canApply?.()).toBe(true)
store.setState({ activeWorktreeId: 'other-main-workspace' })
expect(document.activeElement?.id).toBe('floating')
expect(reveal?.canApply?.()).toBe(true)
})
it('scopes the floating reveal to its selected split pane', async () => {
const { store, fileId, position } = await setup()
const tab = store.getState().getActiveTab(FLOATING)
@@ -199,15 +137,3 @@ it('scopes the floating reveal to its selected split pane', async () => {
store.getState().focusGroup(FLOATING, siblingGroupId)
expect(reveal?.canApply?.()).toBe(false)
})
it('disposes floating DOM listeners and invalidates an already published reveal', async () => {
const { store, fileId, position } = await setup()
position(fileId, { line: 17 }, true)
flushFrames()
const reveal = store.getState().pendingEditorReveal
unsubs.forEach((unsubscribe) => unsubscribe())
expect(reveal?.canApply?.()).toBe(false)
focus('floating')
flushFrames()
expect(store.getState().pendingEditorReveal).toBe(reveal)
})
@@ -211,6 +211,73 @@ describe('createRuntimeClientEventsSync', () => {
}
})
it('resubscribes on its own when the stream closes, backing off until a stream stays up', async () => {
vi.useFakeTimers()
try {
const closes: (() => void)[] = []
const unsubscribes: ReturnType<typeof vi.fn>[] = []
const subscribe = vi.fn(
(
_environmentId: string,
_onEvent: unknown,
_onError: unknown,
_isCurrent: unknown,
onClose?: () => void
): Promise<RuntimeClientEventSubscriptionHandle> => {
const unsubscribe = vi.fn()
unsubscribes.push(unsubscribe)
closes.push(() => onClose?.())
// The first stream closes before its setup settles.
if (closes.length === 1) {
onClose?.()
}
return Promise.resolve({ unsubscribe })
}
)
const sync = createRuntimeClientEventsSync({
getDesiredEnvironmentIds: () => ['A'],
getSubscriptionKey: () => 'A:1',
subscribe,
onEvent: vi.fn(),
retryDelayMs: 10,
retryMaxDelayMs: 40,
random: () => 1
})
sync.sync()
await vi.advanceTimersByTimeAsync(0)
expect(unsubscribes[0]).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(10)
expect(subscribe).toHaveBeenCalledTimes(2)
// Streams that close right after setup back off 20, 40, then stay capped at 40.
for (const [attempt, delay] of [
[2, 20],
[3, 40],
[4, 40]
]) {
closes[attempt - 1]()
await vi.advanceTimersByTimeAsync(delay - 1)
expect(subscribe).toHaveBeenCalledTimes(attempt)
await vi.advanceTimersByTimeAsync(1)
expect(subscribe).toHaveBeenCalledTimes(attempt + 1)
}
// A late close from a replaced stream must not drop the live one.
closes[1]()
await vi.advanceTimersByTimeAsync(40)
expect(subscribe).toHaveBeenCalledTimes(5)
// A stream that stayed up 30s ends the streak: the next retry uses the base delay.
await vi.advanceTimersByTimeAsync(30_000)
closes[4]()
await vi.advanceTimersByTimeAsync(10)
expect(subscribe).toHaveBeenCalledTimes(6)
} finally {
vi.useRealTimers()
}
})
it('backs off exponentially with a cap while an environment keeps failing', async () => {
vi.useFakeTimers()
try {
@@ -282,7 +349,7 @@ describe('createRuntimeClientEventsSync', () => {
}
})
it('an external sync retries a waiting environment immediately (recovery path)', async () => {
it('an explicit recovery wake retries a waiting environment immediately', async () => {
vi.useFakeTimers()
try {
const subscribe = vi.fn((): Promise<RuntimeClientEventSubscriptionHandle> =>
@@ -302,7 +369,7 @@ describe('createRuntimeClientEventsSync', () => {
expect(subscribe).toHaveBeenCalledTimes(1)
// Reachability changes retry immediately instead of waiting on backoff.
sync.sync()
sync.sync(['A'])
await vi.advanceTimersByTimeAsync(0)
expect(subscribe).toHaveBeenCalledTimes(2)
} finally {
@@ -310,6 +377,104 @@ describe('createRuntimeClientEventsSync', () => {
}
})
it.each([10, 100])('keeps retries local to due hosts in a fleet of %i', async (hostCount) => {
vi.useFakeTimers()
try {
const desired = Array.from({ length: hostCount }, (_, i) => `host-${i}`)
const getDesiredEnvironmentIds = vi.fn(() => desired)
const getSubscriptionKey = vi.fn((id: string) => id)
const closes = new Map<string, () => void>()
const subscribe = vi.fn(
(id: string, _event: unknown, _error: unknown, _current: unknown, close: () => void) => {
closes.set(id, close)
return Promise.resolve({ unsubscribe: vi.fn() })
}
)
const sync = createRuntimeClientEventsSync({
getDesiredEnvironmentIds,
getSubscriptionKey,
subscribe,
onEvent: vi.fn(),
random: () => 1
})
sync.sync()
await vi.advanceTimersByTimeAsync(0)
getDesiredEnvironmentIds.mockClear()
getSubscriptionKey.mockClear()
subscribe.mockClear()
closes.get('host-0')!()
await vi.advanceTimersByTimeAsync(1_000)
expect(subscribe.mock.calls.map(([id]) => id)).toEqual(['host-0'])
expect(getDesiredEnvironmentIds).not.toHaveBeenCalled()
expect(getSubscriptionKey).not.toHaveBeenCalled()
subscribe.mockClear()
for (const close of closes.values()) {
close()
}
// Every host is due once within 2s; only host-0 has a prior failure.
await vi.advanceTimersByTimeAsync(2_000)
expect(subscribe).toHaveBeenCalledTimes(hostCount)
expect(new Set(subscribe.mock.calls.map(([id]) => id)).size).toBe(hostCount)
expect(getDesiredEnvironmentIds).not.toHaveBeenCalled()
expect(getSubscriptionKey).not.toHaveBeenCalled()
sync.stop()
} finally {
vi.useRealTimers()
}
})
it('preserves sibling deadlines across retries, reconciliation, and scoped recovery', async () => {
vi.useFakeTimers()
try {
const closes = new Map<string, () => void>()
const attempts: { id: string; at: number }[] = []
const sync = createRuntimeClientEventsSync({
getDesiredEnvironmentIds: () => ['A', 'B'],
subscribe: (id, _event, _error, _current, close) => {
attempts.push({ id, at: Date.now() })
closes.set(id, close)
return Promise.resolve({ unsubscribe: vi.fn() })
},
onEvent: vi.fn(),
random: () => 1
})
vi.setSystemTime(0)
sync.sync()
await vi.advanceTimersByTimeAsync(0)
for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) {
closes.get('A')!()
await vi.advanceTimersByTimeAsync(delay)
}
// A is due at 61s. B's first close at 31s must not reset A's deadline.
closes.get('A')!()
closes.get('B')!()
sync.sync()
await vi.advanceTimersByTimeAsync(1_000)
expect(attempts.filter(({ id }) => id === 'A').map(({ at }) => at)).toEqual([
0, 1_000, 3_000, 7_000, 15_000, 31_000
])
expect(attempts.filter(({ id }) => id === 'B').map(({ at }) => at)).toEqual([0, 32_000])
closes.get('B')!()
sync.sync(['B'])
await vi.advanceTimersByTimeAsync(0)
expect(attempts.filter(({ id }) => id === 'B').map(({ at }) => at)).toEqual([
0, 32_000, 32_000
])
await vi.advanceTimersByTimeAsync(28_999)
expect(attempts.filter(({ id }) => id === 'A')).toHaveLength(6)
await vi.advanceTimersByTimeAsync(1)
expect(attempts.filter(({ id }) => id === 'A').map(({ at }) => at)).toEqual([
0, 1_000, 3_000, 7_000, 15_000, 31_000, 61_000
])
sync.stop()
} finally {
vi.useRealTimers()
}
})
it('does not carry a stale failure count when a rejection lands after the env left the set', async () => {
vi.useFakeTimers()
try {
@@ -5,8 +5,8 @@ export type RuntimeClientEventSubscriptionHandle = {
}
export type RuntimeClientEventsSyncDeps = {
/** Current set of runtime environment ids that should have a live client-event
* subscription. Re-read on every sync and at subscribe-resolution time. */
/** Current desired hosts. Membership and key changes must synchronously call sync;
* retries and settlements use the ownership that reconciliation established. */
getDesiredEnvironmentIds: () => string[]
/** Changes when an environment's transport generation requires a fresh subscription. */
getSubscriptionKey?: (environmentId: string) => string
@@ -15,7 +15,9 @@ export type RuntimeClientEventsSyncDeps = {
onEvent: (event: RuntimeClientEvent) => void,
onError: (error: unknown) => void,
/** Use for subscription-side recovery that runs before event delivery. */
isCurrent: () => boolean
isCurrent: () => boolean,
/** The stream ended (e.g. its host connection was replaced); the owner resubscribes. */
onClose: () => void
) => Promise<RuntimeClientEventSubscriptionHandle>
onEvent: (environmentId: string, event: RuntimeClientEvent) => void
/** Base retry delay; doubles per consecutive failure up to retryMaxDelayMs. */
@@ -26,221 +28,160 @@ export type RuntimeClientEventsSyncDeps = {
}
export type RuntimeClientEventsSync = {
/** Reconciles live subscriptions to the desired environment set. */
sync: () => void
/** Tears down all subscriptions and bumps the generation so in-flight
* subscribes resolve into a no-op. */
/** Reconciles desired hosts; recovery ids explicitly wake those hosts before their retry deadline. */
sync: (recoveryEnvironmentIds?: readonly string[]) => void
/** Retires all ownership so in-flight subscriptions are released on settlement. */
stop: () => void
}
/** Reconcile one subscription per desired environment; remove/re-add can race two in-flight subscribes without a generation change. Keep the first winner and unsubscribe duplicates rather than overwriting and leaking its handle. */
const STABLE_STREAM_MS = 30_000
type SubscriptionAttempt = {
closed: boolean
unsubscribe?: () => void
installedAt?: number
}
type EnvironmentSubscription = {
key: string
attempt?: SubscriptionAttempt
failures: number
retryTimer?: ReturnType<typeof setTimeout>
}
export function createRuntimeClientEventsSync(
deps: RuntimeClientEventsSyncDeps
): RuntimeClientEventsSync {
type SubscriptionToken = { key: string; generation: number }
const subscriptions = new Map<
string,
{ key: string; token: SubscriptionToken; unsubscribe: () => void }
>()
const pending = new Map<string, SubscriptionToken>()
const retryTimers = new Map<string, ReturnType<typeof setTimeout>>()
const consecutiveFailures = new Map<string, { key: string; count: number }>()
const environments = new Map<string, EnvironmentSubscription>()
const retryDelayMs = deps.retryDelayMs ?? 1_000
const retryMaxDelayMs = deps.retryMaxDelayMs ?? 30_000
const random = deps.random ?? Math.random
const getSubscriptionKey = deps.getSubscriptionKey ?? ((environmentId: string) => environmentId)
let generation = 0
let syncInvocation = 0
const clearRetryTimer = (environmentId: string): void => {
const retryTimer = retryTimers.get(environmentId)
if (!retryTimer) {
return
const clearRetry = (entry: EnvironmentSubscription): void => {
if (entry.retryTimer !== undefined) {
clearTimeout(entry.retryTimer)
entry.retryTimer = undefined
}
clearTimeout(retryTimer)
retryTimers.delete(environmentId)
}
const nextRetryDelayMs = (environmentId: string, subscriptionKey: string): number => {
// Exponential capped jitter paces dead hosts without synchronized retries; external reachability/desired transitions still retry immediately.
const failure = consecutiveFailures.get(environmentId)
const failures = failure?.key === subscriptionKey ? failure.count : 0
const capped = Math.min(retryDelayMs * 2 ** Math.max(0, failures - 1), retryMaxDelayMs)
return capped * (0.5 + random() * 0.5)
const retire = (entry: EnvironmentSubscription): void => {
clearRetry(entry)
const attempt = entry.attempt
entry.attempt = undefined
attempt?.unsubscribe?.()
}
const scheduleRetry = (
environmentId: string,
subscriptionKey: string,
subscribeGeneration: number
): void => {
if (retryTimers.has(environmentId)) {
const scheduleRetry = (environmentId: string, entry: EnvironmentSubscription): void => {
if (environments.get(environmentId) !== entry || entry.retryTimer !== undefined) {
return
}
// Store writes no longer drive retries; keep a bounded timer while failed environments remain desired.
const retryTimer = setTimeout(
const capped = Math.min(retryDelayMs * 2 ** Math.max(0, entry.failures - 1), retryMaxDelayMs)
entry.retryTimer = setTimeout(
() => {
retryTimers.delete(environmentId)
if (
subscribeGeneration !== generation ||
!deps.getDesiredEnvironmentIds().includes(environmentId) ||
getSubscriptionKey(environmentId) !== subscriptionKey
) {
entry.retryTimer = undefined
if (environments.get(environmentId) === entry) {
startAttempt(environmentId, entry)
}
},
capped * (0.5 + random() * 0.5)
)
}
const startAttempt = (environmentId: string, entry: EnvironmentSubscription): void => {
if (environments.get(environmentId) !== entry || entry.attempt) {
return
}
clearRetry(entry)
const attempt: SubscriptionAttempt = { closed: false }
entry.attempt = attempt
const ownsAttempt = (): boolean =>
environments.get(environmentId) === entry && entry.attempt === attempt
const isCurrent = (): boolean => ownsAttempt() && !attempt.closed
void deps
.subscribe(
environmentId,
(event) => {
if (isCurrent()) {
deps.onEvent(environmentId, event)
}
},
(error) => console.warn('[runtime-client-events] subscription error:', error),
isCurrent,
() => {
attempt.closed = true
if (!ownsAttempt() || attempt.installedAt === undefined) {
return
}
entry.attempt = undefined
if (Date.now() - attempt.installedAt >= STABLE_STREAM_MS) {
entry.failures = 0
}
entry.failures += 1
scheduleRetry(environmentId, entry)
}
)
.then((subscription) => {
if (!ownsAttempt()) {
subscription.unsubscribe()
return
}
sync()
},
nextRetryDelayMs(environmentId, subscriptionKey)
)
retryTimers.set(environmentId, retryTimer)
if (attempt.closed) {
entry.attempt = undefined
subscription.unsubscribe()
entry.failures += 1
scheduleRetry(environmentId, entry)
return
}
attempt.unsubscribe = subscription.unsubscribe
attempt.installedAt = Date.now()
})
.catch((error) => {
if (ownsAttempt()) {
entry.attempt = undefined
console.warn('[runtime-client-events] failed to subscribe:', error)
entry.failures += 1
scheduleRetry(environmentId, entry)
}
})
}
const sync = (recoveryEnvironmentIds: readonly string[] = []): void => {
const invocation = ++syncInvocation
const desiredIds = new Set(deps.getDesiredEnvironmentIds())
for (const [environmentId, entry] of environments) {
if (invocation !== syncInvocation) {
return
}
if (desiredIds.has(environmentId) && entry.key === getSubscriptionKey(environmentId)) {
continue
}
environments.delete(environmentId)
retire(entry)
}
const recoveryIds = new Set(recoveryEnvironmentIds)
for (const environmentId of desiredIds) {
if (invocation !== syncInvocation) {
return
}
let entry = environments.get(environmentId)
if (!entry) {
entry = { key: getSubscriptionKey(environmentId), failures: 0 }
environments.set(environmentId, entry)
}
if (entry.retryTimer === undefined || recoveryIds.has(environmentId)) {
startAttempt(environmentId, entry)
}
}
}
const stop = (): void => {
generation += 1
const stoppedSubscriptions = [...subscriptions.values()]
subscriptions.clear()
pending.clear()
for (const retryTimer of retryTimers.values()) {
clearTimeout(retryTimer)
}
retryTimers.clear()
consecutiveFailures.clear()
for (const subscription of stoppedSubscriptions) {
subscription.unsubscribe()
}
}
const sync = (): void => {
const syncGeneration = generation
const currentSyncInvocation = ++syncInvocation
const desiredIds = new Set(deps.getDesiredEnvironmentIds())
for (const environmentId of retryTimers.keys()) {
if (desiredIds.has(environmentId)) {
continue
}
clearRetryTimer(environmentId)
}
for (const environmentId of consecutiveFailures.keys()) {
if (!desiredIds.has(environmentId)) {
consecutiveFailures.delete(environmentId)
}
}
for (const [environmentId, subscription] of subscriptions) {
if (syncGeneration !== generation || currentSyncInvocation !== syncInvocation) {
return
}
if (desiredIds.has(environmentId) && subscription.key === getSubscriptionKey(environmentId)) {
continue
}
subscriptions.delete(environmentId)
subscription.unsubscribe()
}
for (const environmentId of desiredIds) {
if (syncGeneration !== generation || currentSyncInvocation !== syncInvocation) {
return
}
const subscriptionKey = getSubscriptionKey(environmentId)
const pendingSubscription = pending.get(environmentId)
if (pendingSubscription && pendingSubscription.key !== subscriptionKey) {
pending.delete(environmentId)
}
if (
subscriptions.get(environmentId)?.key === subscriptionKey ||
pending.get(environmentId)?.key === subscriptionKey
) {
continue
}
clearRetryTimer(environmentId)
const subscribeGeneration = generation
const pendingSubscriptionToken = { key: subscriptionKey, generation: subscribeGeneration }
pending.set(environmentId, pendingSubscriptionToken)
const isCurrent = (): boolean =>
subscribeGeneration === generation &&
(pending.get(environmentId) === pendingSubscriptionToken ||
subscriptions.get(environmentId)?.token === pendingSubscriptionToken)
void deps
.subscribe(
environmentId,
(event) => {
// Initial frames arrive before setup settles; only the owning attempt may deliver.
if (isCurrent()) {
deps.onEvent(environmentId, event)
}
},
(error) => {
console.warn('[runtime-client-events] subscription error:', error)
},
isCurrent
)
.then((subscription) => {
const isCurrentPending = pending.get(environmentId) === pendingSubscriptionToken
if (isCurrentPending) {
pending.delete(environmentId)
}
if (
!isCurrentPending ||
subscribeGeneration !== generation ||
!deps.getDesiredEnvironmentIds().includes(environmentId) ||
getSubscriptionKey(environmentId) !== subscriptionKey
) {
subscription.unsubscribe()
return
}
// Another subscribe already won; unsubscribe this duplicate instead of overwriting and leaking the winner’s handle.
if (subscriptions.get(environmentId)?.key === subscriptionKey) {
subscription.unsubscribe()
return
}
consecutiveFailures.delete(environmentId)
subscriptions.set(environmentId, {
key: subscriptionKey,
token: pendingSubscriptionToken,
unsubscribe: subscription.unsubscribe
})
})
.catch((error) => {
const isCurrentPending = pending.get(environmentId) === pendingSubscriptionToken
if (isCurrentPending) {
pending.delete(environmentId)
}
if (
isCurrentPending &&
subscribeGeneration === generation &&
getSubscriptionKey(environmentId) === subscriptionKey
) {
console.warn('[runtime-client-events] failed to subscribe:', error)
// Count failures only while retrying this desired environment; late rejection after removal must not penalize re-entry.
if (deps.getDesiredEnvironmentIds().includes(environmentId)) {
const failure = consecutiveFailures.get(environmentId)
consecutiveFailures.set(environmentId, {
key: subscriptionKey,
count: failure?.key === subscriptionKey ? failure.count + 1 : 1
})
scheduleRetry(environmentId, subscriptionKey, subscribeGeneration)
} else {
consecutiveFailures.delete(environmentId)
}
}
})
}
if (syncGeneration !== generation || currentSyncInvocation !== syncInvocation) {
return
}
for (const [environmentId, pendingSubscription] of pending) {
if (
desiredIds.has(environmentId) &&
pendingSubscription.key === getSubscriptionKey(environmentId)
) {
continue
}
pending.delete(environmentId)
}
if (desiredIds.size === 0 && subscriptions.size === 0) {
generation += 1
syncInvocation += 1
const stopped = [...environments.values()]
environments.clear()
for (const entry of stopped) {
retire(entry)
}
}
@@ -122,53 +122,6 @@ describe('useEditorExternalWatch subscriptions', () => {
;(window as unknown as { api?: unknown }).api = previousApi
})
it('unsubscribes an SSH watch and the shared event listener exactly once on unmount', async () => {
subscriptionState.snapshot = {
targets: [
{
worktreeId: 'wt-ssh',
worktreePath: '/remote/repo',
connectionId: 'ssh-1',
runtimeEnvironmentId: null
}
],
targetsKey: 'ssh-watch'
}
await act(async () => root.render(createElement(WatchProbe)))
expect(watchWorktree).toHaveBeenCalledWith({
worktreePath: '/remote/repo',
connectionId: 'ssh-1'
})
await act(async () => root.unmount())
expect(unwatchWorktree).toHaveBeenCalledTimes(1)
expect(unwatchWorktree).toHaveBeenCalledWith({
worktreePath: '/remote/repo',
connectionId: 'ssh-1'
})
expect(unsubscribeFsEvents).toHaveBeenCalledTimes(1)
expect(subscriptionState.disposeEventHandler).toHaveBeenCalledTimes(1)
})
it('disposes a runtime subscription that resolves after unmount', async () => {
const pending = deferredRuntimeSubscription()
const unsubscribeRuntime = vi.fn()
subscriptionState.subscribeRuntimeFileChanges.mockReturnValueOnce(pending.promise)
subscriptionState.snapshot = {
targets: [runtimeTarget()],
targetsKey: 'runtime-watch'
}
await act(async () => root.render(createElement(WatchProbe)))
await act(async () => root.unmount())
pending.resolve(unsubscribeRuntime)
await act(async () => pending.promise)
expect(unsubscribeRuntime).toHaveBeenCalledTimes(1)
expect(unwatchWorktree).not.toHaveBeenCalled()
})
it('cannot let an old runtime subscribe resolution replace a re-added watch', async () => {
const stalePending = deferredRuntimeSubscription()
const currentPending = deferredRuntimeSubscription()
@@ -1,354 +0,0 @@
import type * as ReactModule from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createTestStore } from '../store/testing/app-store-test-fixture'
import { makeTab } from '../store/terminals/terminal-tab.test-fixture'
import { makeUnifiedTab } from '../store/slices/tabs/tab-group.test-fixture'
import { makeWorktree } from '../store/slices/worktrees/worktree.test-fixture'
import { TEST_REPO } from '../store/repos/repo.test-fixture'
import { layoutApplyTestDouble } from '@/runtime/workspace-layout/testing/layout-apply-test-double'
import type { AppState } from '../store/types'
import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id'
import {
buildStoreState,
expectWorktreeRouting,
FUTURE_LEAF_ID,
FUTURE_PANE_KEY,
type AgentStatusSetData,
type StoreLike,
type StoreSubscribeListener,
type MobileFitListener,
type MobileDriverListener,
type MobileBrowserDriverListener
} from './ipc-events-agent-status-store-test-fixtures'
import {
buildWindowApi,
stubReactSyncEffect,
stubAuxiliaryModules
} from './ipc-events-agent-status-window-test-fixtures'
describe('useIpcEvents agent status snapshot integration', () => {
beforeEach(() => {
vi.resetModules()
vi.unstubAllGlobals()
})
it('clears pending mobile state events and ignores late hydration after cleanup', async () => {
const setFitOverride = vi.fn()
const hydrateOverrides = vi.fn()
const setDriverForPty = vi.fn()
const hydrateDrivers = vi.fn()
const setDriverForBrowserPage = vi.fn()
const hydrateBrowserDrivers = vi.fn()
const unsubscribeFit = vi.fn()
const unsubscribeDriver = vi.fn()
const unsubscribeBrowserDriver = vi.fn()
const refs: {
cleanup?: () => void
fit?: MobileFitListener
driver?: MobileDriverListener
browserDriver?: MobileBrowserDriverListener
} = {}
let resolveFitOverrides: (value: []) => void = () => {}
let resolveDrivers: (value: []) => void = () => {}
let resolveBrowserDrivers: (value: []) => void = () => {}
vi.doMock('@/lib/pane-manager/mobile-fit-overrides', () => ({
setFitOverride,
hydrateOverrides
}))
vi.doMock('@/lib/pane-manager/mobile-driver-state', () => ({
setDriverForPty,
hydrateDrivers
}))
vi.doMock('@/lib/pane-manager/browser-mobile-driver-state', () => ({
setDriverForBrowserPage,
hydrateBrowserDrivers
}))
vi.doMock('react', async () => {
const actual = await vi.importActual<typeof ReactModule>('react')
return {
...actual,
useEffect: (effect: () => void | (() => void)) => {
const result = effect()
if (typeof result === 'function') {
refs.cleanup = result
}
}
}
})
stubAuxiliaryModules()
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn(() => () => {}),
getState: () => buildStoreState({})
}
}))
vi.stubGlobal(
'window',
buildWindowApi({
onSet: () => () => {},
runtime: {
getTerminalFitOverrides: () =>
new Promise<[]>((resolve) => {
resolveFitOverrides = resolve
}),
getTerminalDrivers: () =>
new Promise<[]>((resolve) => {
resolveDrivers = resolve
}),
getBrowserDrivers: () =>
new Promise<[]>((resolve) => {
resolveBrowserDrivers = resolve
}),
onTerminalFitOverrideChanged: (listener: MobileFitListener) => {
refs.fit = listener
return unsubscribeFit
},
onTerminalDriverChanged: (listener: MobileDriverListener) => {
refs.driver = listener
return unsubscribeDriver
},
onBrowserDriverChanged: (listener: MobileBrowserDriverListener) => {
refs.browserDriver = listener
return unsubscribeBrowserDriver
},
onClientHostedBrowserRowsChanged: () => () => {},
getClientHostedBrowserRows: async () => []
}
})
)
const { useIpcEvents } = await import('./useIpcEvents')
useIpcEvents()
if (!refs.fit || !refs.driver || !refs.browserDriver || !refs.cleanup) {
throw new Error('Expected mobile listeners and cleanup to be registered')
}
refs.fit({
ptyId: 'pty-1',
mode: 'mobile-fit',
cols: 80,
rows: 24
})
refs.driver({
ptyId: 'pty-1',
driver: { kind: 'mobile', clientId: 'phone' }
})
refs.browserDriver({
browserPageId: 'page-1',
driver: { kind: 'mobile', clientId: 'phone' }
})
refs.cleanup()
resolveFitOverrides([])
resolveDrivers([])
resolveBrowserDrivers([])
await Promise.resolve()
await Promise.resolve()
expect(unsubscribeFit).toHaveBeenCalledTimes(1)
expect(unsubscribeDriver).toHaveBeenCalledTimes(1)
expect(unsubscribeBrowserDriver).toHaveBeenCalledTimes(1)
expect(hydrateOverrides).not.toHaveBeenCalled()
expect(hydrateDrivers).not.toHaveBeenCalled()
expect(hydrateBrowserDrivers).not.toHaveBeenCalled()
expect(setFitOverride).not.toHaveBeenCalled()
expect(setDriverForPty).not.toHaveBeenCalled()
expect(setDriverForBrowserPage).not.toHaveBeenCalled()
})
it('ignores early push events but applies the main-process snapshot after readiness', async () => {
const setAgentStatus = vi.fn()
const getSnapshot = vi.fn(() =>
Promise.resolve([
{
paneKey: FUTURE_PANE_KEY,
state: 'working' as const,
workingMode: 'monitoring' as const,
prompt: 'p',
agentType: 'claude',
receivedAt: 1_700_000_000_000,
stateStartedAt: 1_699_999_999_000
}
])
)
const onSetListenerRef: { current: ((data: AgentStatusSetData) => void) | null } = {
current: null
}
const subscribeListenerRef: { current: StoreSubscribeListener | null } = { current: null }
const storeState: StoreLike = buildStoreState({
setAgentStatus,
tabsByWorktree: {},
workspaceSessionReady: false
})
const setAgentStatuses = vi.mocked(storeState.setAgentStatuses as AppState['setAgentStatuses'])
stubReactSyncEffect()
vi.doMock('../store', () => ({
useAppStore: {
subscribe: vi.fn((listener: StoreSubscribeListener) => {
subscribeListenerRef.current = listener
return () => {
subscribeListenerRef.current = null
}
}),
getState: () => storeState
}
}))
stubAuxiliaryModules()
vi.stubGlobal(
'window',
buildWindowApi({
getSnapshot,
onSet: (cb) => {
onSetListenerRef.current = cb
return () => {}
}
})
)
const { useIpcEvents } = await import('./useIpcEvents')
useIpcEvents()
await Promise.resolve()
if (typeof onSetListenerRef.current !== 'function') {
throw new Error('Expected agentStatus.onSet listener to be registered')
}
onSetListenerRef.current({
paneKey: FUTURE_PANE_KEY,
state: 'working',
prompt: 'p',
agentType: 'claude',
receivedAt: 1_700_000_000_100,
stateStartedAt: 1_699_999_999_100
})
expect(setAgentStatus).not.toHaveBeenCalled()
expect(getSnapshot).not.toHaveBeenCalled()
const previousStoreState = { ...storeState }
storeState.workspaceSessionReady = true
storeState.tabsByWorktree = {
'wt-1': [{ id: 'tab-future', ptyId: 'pty-1', worktreeId: 'wt-1', title: 'Future Tab' }]
}
storeState.terminalLayoutsByTabId = {
'tab-future': {
root: { type: 'leaf', leafId: FUTURE_LEAF_ID },
activeLeafId: FUTURE_LEAF_ID,
expandedLeafId: null
}
}
if (typeof subscribeListenerRef.current !== 'function') {
throw new Error('Expected useAppStore.subscribe listener to be registered')
}
subscribeListenerRef.current(storeState, previousStoreState)
await Promise.resolve()
expect(setAgentStatus).toHaveBeenCalledTimes(1)
expect(setAgentStatuses).toHaveBeenCalledTimes(1)
expect(setAgentStatuses.mock.calls[0]?.[0]).toHaveLength(1)
expect(setAgentStatus).toHaveBeenCalledWith(
FUTURE_PANE_KEY,
expect.objectContaining({
state: 'working',
workingMode: 'monitoring',
prompt: 'p',
agentType: 'claude'
}),
'Future Tab',
{ updatedAt: 1_700_000_000_000, stateStartedAt: 1_699_999_999_000 },
expectWorktreeRouting('wt-1'),
undefined
)
})
it('applies a status snapshot to terminal panes after session readiness', async () => {
const paneCount = 2
const snapshot: AgentStatusSetData[] = []
const worktrees: AppState['worktreesByRepo'][string] = []
const tabsByWorktree: AppState['tabsByWorktree'] = {}
const unifiedTabsByWorktree: AppState['unifiedTabsByWorktree'] = {}
const terminalLayoutsByTabId: AppState['terminalLayoutsByTabId'] = {}
for (let index = 0; index < paneCount; index += 1) {
const worktreeId = `wt-snapshot-${index}`
const tabId = `tab-snapshot-${index}`
const leafId = `00000000-0000-4000-8000-${String(index).padStart(12, '0')}`
const paneKey = makePaneKey(tabId, leafId)
worktrees.push(makeWorktree({ id: worktreeId, repoId: TEST_REPO.id }))
tabsByWorktree[worktreeId] = [
makeTab({ id: tabId, worktreeId, title: 'Hermes', ptyId: `pty-${index}` })
]
unifiedTabsByWorktree[worktreeId] = [makeUnifiedTab({ id: tabId, worktreeId, groupId: 'g' })]
terminalLayoutsByTabId[tabId] = {
root: { type: 'leaf', leafId },
activeLeafId: leafId,
expandedLeafId: null
}
snapshot.push({
paneKey,
worktreeId,
state: 'waiting',
prompt: `remote prompt ${index}`,
agentType: 'hermes',
receivedAt: 1_700_000_000_000 + index,
stateStartedAt: 1_700_000_000_000 + index
})
}
let resolveSnapshot: ((entries: AgentStatusSetData[]) => void) | undefined
const getSnapshot = vi.fn(
() =>
new Promise<AgentStatusSetData[]>((resolve) => {
resolveSnapshot = resolve
})
)
const store = createTestStore()
store.setState({
workspaceSessionReady: true,
repos: [TEST_REPO],
worktreesByRepo: { [TEST_REPO.id]: worktrees },
tabsByWorktree,
terminalLayoutsByTabId,
activeWorktreeId: worktrees[0]?.id ?? null,
settings: {
...store.getState().settings,
tabAutoGenerateTitle: true,
terminalFontSize: 13
}
} as Partial<AppState>)
store.setState({ unifiedTabsByWorktree })
stubReactSyncEffect()
vi.doMock('../store', () => ({
useAppStore: {
subscribe: store.subscribe,
getState: store.getState,
setState: store.setState
}
}))
stubAuxiliaryModules()
const main = layoutApplyTestDouble()
vi.stubGlobal(
'window',
buildWindowApi({
getSnapshot,
onSet: () => () => {},
runtime: { call: main.call }
})
)
const { useIpcEvents } = await import('./useIpcEvents')
useIpcEvents()
await Promise.resolve()
resolveSnapshot?.(snapshot)
await vi.waitFor(() => {
expect(
store.getState().agentStatusByPaneKey['tab-snapshot-1:00000000-0000-4000-8000-000000000001']
?.state
).toBe('waiting')
})
})
})
@@ -1,72 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { ClientHostedBrowserRowsEvent } from '../../../shared/client-hosted-browser-rows'
import {
loadIpcEventsHarness,
type IpcEventsHarness,
type IpcEventsHarnessOptions
} from './ipc-events-test-harness'
import { createHarnessStoreState } from './ipc-events-harness-store-state'
const WT = 'wt-1'
function pushEvent(): ClientHostedBrowserRowsEvent {
return {
worktreeId: WT,
rows: [
{
browserPageId: 'page-a',
worktreeId: WT,
url: 'https://client-hosted.test/docs',
title: 'Docs',
loading: false,
browserHostClientId: 'host-a',
hostDeviceName: 'Studio',
hostAbsent: false
}
]
}
}
/** Import after harness module reset so hook and assertions share the same real row store. */
async function mountHook(options: IpcEventsHarnessOptions = {}): Promise<{
harness: IpcEventsHarness
readRows: (worktreeId: string) => readonly { browserPageId: string }[]
}> {
const harness = await loadIpcEventsHarness(
createHarnessStoreState({ tabsByWorktree: {} }),
options
)
const { getClientHostedBrowserRows } =
await import('@/lib/pane-manager/client-hosted-browser-row-state')
harness.useIpcEvents()
return { harness, readRows: getClientHostedBrowserRows }
}
describe('useIpcEvents client-hosted browser rows', () => {
// Subscribe before hydration so older snapshots cannot erase pages pushed during the round trip.
it('keeps a push that raced the hydration snapshot', async () => {
const { harness, readRows } = await mountHook({
clientHostedBrowserRowsSnapshot: [{ worktreeId: WT, rows: [] }]
})
harness.clientHostedBrowserRowsChanged(pushEvent())
await harness.settleClientHostedBrowserRowsSnapshot()
expect(readRows(WT).map((row) => row.browserPageId)).toEqual(['page-a'])
})
// Failed hydration must settle and drain buffered pushes or the host strip stays empty forever.
it('applies pushes after the hydration round trip fails', async () => {
const { harness, readRows } = await mountHook({
clientHostedBrowserRowsSnapshotError: new Error('runtime unreachable')
})
harness.clientHostedBrowserRowsChanged(pushEvent())
expect(readRows(WT)).toEqual([])
await harness.settleClientHostedBrowserRowsSnapshot()
expect(readRows(WT).map((row) => row.browserPageId)).toEqual(['page-a'])
harness.clientHostedBrowserRowsChanged({ worktreeId: WT, rows: [] })
expect(readRows(WT)).toEqual([])
})
})
@@ -10,6 +10,8 @@ import type {
RuntimeEnvironmentStoreSyncSubscriber
} from './ipc-events/runtime-environment-subscription-selection'
import { createRuntimeClientEventsSync } from './runtime-client-events-sync'
type RuntimeEnvironmentStoreSubscriber = RuntimeEnvironmentStoreSyncSubscriber
type RuntimeEnvironmentStoreState = RuntimeEnvironmentStoreSyncState
@@ -32,6 +34,78 @@ function makeRuntimeEnvironmentStoreState(args: {
}
describe('createRuntimeEnvironmentStoreSyncSubscriber', () => {
it('retires removed registry members despite retained status and follows active host changes', async () => {
const environments = [
{ id: 'A', createdAt: 1 },
{ id: 'B', createdAt: 2 }
]
const statuses = new Map([
['A', { status: { runtimeId: 'peer-a' }, checkedAt: 1 }],
['B', { status: { runtimeId: 'peer-b' }, checkedAt: 1 }]
])
let state = makeRuntimeEnvironmentStoreState({ environments, statuses })
const subscriptions: string[] = []
const retirements: string[] = []
const wakes: (readonly string[] | undefined)[] = []
const manager = createRuntimeClientEventsSync({
getDesiredEnvironmentIds: () => getRuntimeClientEventEnvironmentIds(state),
subscribe: (id) => {
subscriptions.push(id)
return Promise.resolve({
unsubscribe: () => {
retirements.push(id)
}
})
},
onEvent: vi.fn()
})
const subscriber = createRuntimeEnvironmentStoreSyncSubscriber({
initialDesiredEnvironmentIds: getRuntimeClientEventEnvironmentIds(state),
initialReachableEnvironmentIds: getReachableRuntimeEnvironmentIds(state),
getDesiredEnvironmentIds: getRuntimeClientEventEnvironmentIds,
getReachableEnvironmentIds: getReachableRuntimeEnvironmentIds,
buildEnvironmentKey: (ids) => [...ids].sort().join(':'),
requestProjectRefresh: vi.fn(),
markEnvironmentSshStateStale: vi.fn(),
sync: (ids) => {
wakes.push(ids)
manager.sync(ids)
}
})
const publish = (next: RuntimeEnvironmentStoreState): void => {
const previous = state
state = next
subscriber(state, previous)
}
manager.sync()
await Promise.resolve()
publish(makeRuntimeEnvironmentStoreState({ environments: [environments[1]], statuses }))
expect(retirements).toEqual(['A'])
expect(wakes).toEqual([[]])
publish(
makeRuntimeEnvironmentStoreState({
environments: [environments[1]],
statuses,
activeEnvironmentId: 'C'
})
)
await Promise.resolve()
expect(subscriptions).toEqual(['A', 'B', 'C'])
expect(wakes).toEqual([[], ['C']])
publish(
makeRuntimeEnvironmentStoreState({
environments: [environments[1]],
statuses,
activeEnvironmentId: 'D'
})
)
await Promise.resolve()
expect(retirements).toEqual(['A', 'C'])
expect(subscriptions).toEqual(['A', 'B', 'C', 'D'])
expect(wakes).toEqual([[], ['C'], ['D']])
manager.stop()
})
it('syncs each connect, disconnect, re-pair, runtime generation, and nested SSH generation once', () => {
let environments = [
{ id: 'runtime-a', createdAt: 1, pairingRevision: 1 },
+1
View File
@@ -868,6 +868,7 @@
"defaultSurfaceSetAllChat": "Alle auf Chat setzen",
"defaultSurfaceSetAllTerminal": "Alle auf Terminal setzen",
"sameAsChoice": "Wie {{agent}} · {{choice}}",
"modelListFallback": "Integrierte Liste. Orca konnte von diesem Host keine Modellliste abrufen.",
"chatUnavailableOnWindows": "{{value0}} Chat ist unter Windows noch nicht verfügbar, daher öffnet sich {{value0}} auf diesem Host in einem Terminal. Chats auf einem macOS- oder Linux-Host funktionieren weiterhin.",
"undetectedCommandHint": "Wenn die {{agent}}-CLI außerhalb von PATH installiert ist, gib den vollständigen Pfad zu ihrer ausführbaren Datei auf diesem Host ein."
},
+1
View File
@@ -1052,6 +1052,7 @@
"defaultSurfaceSetAllChat": "Set all to Chat",
"defaultSurfaceSetAllTerminal": "Set all to Terminal",
"sameAsChoice": "Same as {{agent}} · {{choice}}",
"modelListFallback": "Built-in list. Orca could not get a model list from this host.",
"chatUnavailableOnWindows": "{{value0}} Chat isn't available on Windows yet, so {{value0}} opens in a terminal on this host. Chats on a macOS or Linux host still work.",
"undetectedCommandHint": "If the {{agent}} CLI is installed outside PATH, enter the full path to its executable on this host."
},
+1
View File
@@ -414,6 +414,7 @@
"defaultSurfaceSetAllChat": "Poner todos en Chat",
"defaultSurfaceSetAllTerminal": "Poner todos en Terminal",
"sameAsChoice": "Igual que {{agent}} · {{choice}}",
"modelListFallback": "Lista integrada. Orca no pudo obtener una lista de modelos de este host.",
"chatUnavailableOnWindows": "{{value0}} Chat aún no está disponible en Windows, así que {{value0}} se abre en una terminal en este host. Los chats en un host macOS o Linux siguen funcionando.",
"undetectedCommandHint": "Si la CLI de {{agent}} está instalada fuera de PATH, introduce la ruta completa a su ejecutable en este host."
},
+1
View File
@@ -653,6 +653,7 @@
"defaultSurfaceSetAllChat": "Tout mettre en Chat",
"defaultSurfaceSetAllTerminal": "Tout mettre en Terminal",
"sameAsChoice": "Identique à {{agent}} · {{choice}}",
"modelListFallback": "Liste intégrée. Orca n’a pas pu obtenir de liste de modèles depuis cet hôte.",
"chatUnavailableOnWindows": "{{value0}} Chat n’est pas encore disponible sous Windows : {{value0}} s’ouvre donc dans un terminal sur cet hôte. Les chats sur un hôte macOS ou Linux fonctionnent toujours.",
"undetectedCommandHint": "Si la CLI {{agent}} est installée hors de PATH, saisissez le chemin complet de son exécutable sur cet hôte."
},
+1
View File
@@ -409,6 +409,7 @@
"defaultSurfaceSetAllChat": "すべてチャットにする",
"defaultSurfaceSetAllTerminal": "すべてターミナルにする",
"sameAsChoice": "{{agent}} と同じ · {{choice}}",
"modelListFallback": "組み込みのリストです。Orca はこのホストからモデル一覧を取得できませんでした。",
"chatUnavailableOnWindows": "{{value0}} Chat はまだ Windows では利用できないため、このホストでは {{value0}} がターミナルで開きます。macOS または Linux ホストでのチャットは引き続き利用できます。",
"undetectedCommandHint": "{{agent}} CLI が PATH 以外にインストールされている場合、このホスト上の実行ファイルのフルパスを入力してください。"
},
+1
View File
@@ -409,6 +409,7 @@
"defaultSurfaceSetAllChat": "모두 채팅으로 설정",
"defaultSurfaceSetAllTerminal": "모두 터미널로 설정",
"sameAsChoice": "{{agent}}와 동일 · {{choice}}",
"modelListFallback": "기본 제공 목록입니다. Orca가 이 호스트에서 모델 목록을 가져오지 못했습니다.",
"chatUnavailableOnWindows": "{{value0}} Chat은 아직 Windows에서 사용할 수 없으므로 이 호스트에서는 {{value0}}이(가) 터미널에서 열립니다. macOS 또는 Linux 호스트의 채팅은 계속 사용할 수 있습니다.",
"undetectedCommandHint": "{{agent}} CLI가 PATH 외부에 설치되어 있다면 이 호스트의 실행 파일 전체 경로를 입력하세요."
},
+1
View File
@@ -1628,6 +1628,7 @@
"defaultSurfaceSetAllChat": "Definir todos como Chat",
"defaultSurfaceSetAllTerminal": "Definir todos como Terminal",
"sameAsChoice": "Igual a {{agent}} · {{choice}}",
"modelListFallback": "Lista integrada. O Orca não conseguiu obter uma lista de modelos deste host.",
"chatUnavailableOnWindows": "O {{value0}} Chat ainda não está disponível no Windows, então o {{value0}} abre em um terminal neste host. Chats em um host macOS ou Linux continuam funcionando.",
"undetectedCommandHint": "Se a CLI do {{agent}} estiver instalada fora do PATH, informe o caminho completo do executável neste host."
},
+1
View File
@@ -924,6 +924,7 @@
"defaultSurfaceSetAllChat": "Перевести все в чат",
"defaultSurfaceSetAllTerminal": "Перевести все в терминал",
"sameAsChoice": "Как у {{agent}} · {{choice}}",
"modelListFallback": "Встроенный список. Orca не удалось получить список моделей с этого хоста.",
"chatUnavailableOnWindows": "{{value0}} Chat пока недоступен в Windows, поэтому {{value0}} открывается в терминале на этом хосте. Чаты на хосте macOS или Linux по-прежнему работают.",
"undetectedCommandHint": "Если CLI {{agent}} установлен вне PATH, укажите полный путь к исполняемому файлу на этом хосте."
},
+1
View File
@@ -860,6 +860,7 @@
"defaultSurfaceSetAllChat": "Tümünü Sohbet yap",
"defaultSurfaceSetAllTerminal": "Tümünü Terminal yap",
"sameAsChoice": "{{agent}} ile aynı · {{choice}}",
"modelListFallback": "Yerleşik liste. Orca bu ana makineden model listesi alamadı.",
"chatUnavailableOnWindows": "{{value0}} Chat henüz Windows'ta kullanılamıyor, bu nedenle {{value0}} bu ana makinede bir terminalde açılır. macOS veya Linux ana makinesindeki sohbetler çalışmaya devam eder.",
"undetectedCommandHint": "{{agent}} CLI, PATH dışında kuruluysa bu ana makinedeki yürütülebilir dosyanın tam yolunu girin."
},
@@ -833,6 +833,7 @@
"defaultSurfaceSetAllChat": "全部設為聊天",
"defaultSurfaceSetAllTerminal": "全部設為終端機",
"sameAsChoice": "與 {{agent}} 相同 · {{choice}}",
"modelListFallback": "內建清單。Orca 無法從此主機取得模型清單。",
"chatUnavailableOnWindows": "{{value0}} Chat 尚不支援 Windows,因此 {{value0}} 會在此主機的終端機中開啟。macOS 或 Linux 主機上的聊天仍可正常使用。",
"undetectedCommandHint": "如果 {{agent}} CLI 安裝在 PATH 之外,請輸入其在此主機上的可執行檔完整路徑。"
},
+1
View File
@@ -409,6 +409,7 @@
"defaultSurfaceSetAllChat": "全部设为聊天",
"defaultSurfaceSetAllTerminal": "全部设为终端",
"sameAsChoice": "与 {{agent}} 相同 · {{choice}}",
"modelListFallback": "内置列表。Orca 无法从此主机获取模型列表。",
"chatUnavailableOnWindows": "{{value0}} Chat 暂不支持 Windows,因此 {{value0}} 会在此主机的终端中打开。macOS 或 Linux 主机上的聊天仍可正常使用。",
"undetectedCommandHint": "如果 {{agent}} CLI 安装在 PATH 之外,请输入其在此主机上的可执行文件完整路径。"
},
@@ -2,7 +2,7 @@ import { retireStructuredAgentSessionReadOwner } from '@/components/native-chat/
import { structuredAgentSessionTargetForHost } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner'
import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../../shared/execution-host'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch'
import { markStructuredAgentLaunchCancellation } from '../../launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation'
import { markStructuredAgentLaunchCancellation } from './structured-agent-session-launch-cancellation'
import { cancelStructuredAgentLaunchOnLocalHost } from './structured-agent-session-local-launch-cancel'
import { forgetStructuredSessionSelection } from '../options/structured-agent-session-selection-controller'
import { hasStructuredAgentLaunchCancellationTombstonePersisted } from './structured-agent-session-launch-persistence'
@@ -1,12 +1,12 @@
// Hide/close late publication of canceled creates for paired hosts; they may not fence close-before-create. Local window-owned builds retain tombstones until layout-owner phase F.
import type { ExecutionHostId } from '../../../../shared/execution-host'
import type { ExecutionHostId } from '../../../../../shared/execution-host'
import {
hasStructuredAgentLaunchCancellationTombstonePersisted,
markStructuredAgentLaunchCancelledPersisted,
readStructuredAgentLaunchCancellationTombstoneSessionIds,
retireAbsentStructuredAgentLaunchCancellationTombstonesPersisted,
retireStructuredAgentLaunchCancellationTombstonePersisted
} from '../agent-session/launch/structured-agent-session-launch-persistence'
} from './structured-agent-session-launch-persistence'
type CancellationRetirement = {
retireAfterInventory: number | null
@@ -13,7 +13,7 @@ import {
resetStructuredAgentLaunchCancellationForTests,
retireAbsentStructuredAgentLaunchCancellations,
retireStructuredAgentLaunchCancellation
} from '../../launch-cancel-tombstones-compat/structured-agent-session-launch-cancellation'
} from './structured-agent-session-launch-cancellation'
import { resetStructuredAgentLocalLaunchCancelsForTests } from './structured-agent-session-local-launch-cancel'
import {
clearStructuredLaunchStateStoreForTests,
@@ -1,396 +0,0 @@
// @vitest-environment happy-dom
import { markStructuredAgentSessionLaunchCancelled } from '../agent-session/launch/structured-agent-session-launch-cancel'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { StructuredLaunchSlotOwner } from '@/lib/agent-session/launch/structured-agent-session-launch-slot'
import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types'
import { suppressCancelledStructuredSessionTabs } from '@/runtime/native-chat/tab-retirement/structured-agent-session-tab-retirement'
import type { StructuredLaunchState } from '../agent-session/launch/structured-agent-session-launch-registry'
import {
hasStructuredAgentSessionLaunchCancellationTombstone,
retireAbsentStructuredAgentSessionLaunchCancellationTombstones,
resetStructuredAgentLaunchRegistryForTests,
setStructuredLaunchState
} from '../agent-session/launch/structured-agent-session-launch-registry'
import { beginStructuredAgentSessionAuthoritativeInventory } from './structured-agent-session-launch-cancellation'
import { resetStructuredAgentLaunchPersistenceForTests } from '../agent-session/launch/structured-agent-session-launch-persistence'
import { refreshLocalStructuredSessionTabs } from '@/runtime/local-structured-session-tabs-sync/inventory-refresh'
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
import type { ExecutionHostId } from '../../../../shared/execution-host'
import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target'
import { useAppStore } from '@/store'
import { layoutApplyTestTransport } from '@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture'
import {
drawTabsFromMain,
type TabsDrawnFromMain
} from '@/store/slices/tabs/tabs-drawn-from-main.test-fixture'
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await importOriginal())
)
vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await importOriginal())
)
const layoutOwner: StructuredLaunchSlotOwner = {
unifiedTabsByWorktree: {},
groupsByWorktree: {},
reorderUnifiedTabs: vi.fn()
}
const WORKTREE_ID = 'repo-1::worktree-1'
const SESSION_ID = 'session-close-race'
// Paired hosts always need window tombstones; layout-owner local builds use main’s cancel fence instead.
const SERVER_HOST = 'runtime:server-1'
const SERVER = { kind: 'environment', environmentId: 'server-1' } as const
function latePublication(): RuntimeMobileSessionTabsResult {
return {
worktree: WORKTREE_ID,
publicationEpoch: 'epoch-late',
snapshotVersion: 1,
activeGroupId: 'group-1',
activeTabId: `agent-session:${SESSION_ID}`,
activeTabType: 'agent-session',
tabs: [
{
type: 'agent-session',
id: `agent-session:${SESSION_ID}`,
title: 'Codex Chat',
sessionId: SESSION_ID,
agent: 'codex',
isActive: true
}
]
}
}
function setLaunch(
executionHostId: ExecutionHostId,
target: RuntimeClientTarget,
promise: Promise<{ sessionId: string; fence: number }>,
operation = 'close-race'
): void {
setStructuredLaunchState({
identity: `codex:${WORKTREE_ID}`,
intent: {
worktreeId: WORKTREE_ID,
executionHostId,
target,
sessionId: SESSION_ID,
agent: 'codex',
params: {
envelope: {
sessionId: SESSION_ID,
clientOperationId: `operation-${operation}`,
expectedRuntimeFence: null,
payloadFingerprint: `fingerprint-${operation}`
},
worktree: `id:${WORKTREE_ID}`,
agent: 'codex'
}
},
promptDelivery: 'auto-submit',
callers: {
outcome: 'pending',
attempt: { kind: 'first', requestId: 'plus-pick', stagedPrompt: null },
entries: new Set(),
promptDeliveryResults: new Set(),
onSettled: () => undefined
},
promise,
visibilityUnknown: false,
cancelled: false,
selection: {}
} satisfies StructuredLaunchState)
}
/** The cancelled launch's late publication stays hidden until the launch settles, on `host`. */
async function expectLatePublicationSuppressed(
host: ExecutionHostId,
target: RuntimeClientTarget
): Promise<void> {
let resolveLaunch!: (receipt: { sessionId: string; fence: number }) => void
setLaunch(
host,
target,
new Promise((resolve) => {
resolveLaunch = resolve
})
)
const beforeCancel = beginStructuredAgentSessionAuthoritativeInventory()
expect(
retireAbsentStructuredAgentSessionLaunchCancellationTombstones(new Set(), beforeCancel, host)
).toBe(false)
markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, host, layoutOwner)
const afterCancel = beginStructuredAgentSessionAuthoritativeInventory()
expect(
retireAbsentStructuredAgentSessionLaunchCancellationTombstones(new Set(), afterCancel, host)
).toBe(false)
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(true)
resolveLaunch({ sessionId: SESSION_ID, fence: 1 })
await Promise.resolve()
expect(suppressCancelledStructuredSessionTabs(latePublication(), target).tabs).toEqual([])
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(true)
expect(
retireAbsentStructuredAgentSessionLaunchCancellationTombstones(new Set(), beforeCancel, host)
).toBe(false)
const afterSettlement = beginStructuredAgentSessionAuthoritativeInventory()
expect(
retireAbsentStructuredAgentSessionLaunchCancellationTombstones(new Set(), afterSettlement, host)
).toBe(true)
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(false)
}
const TERMINAL = 'terminal-1'
let main: TabsDrawnFromMain | null = null
async function drawWorktreeFromMain(): Promise<void> {
useAppStore.setState({
worktreesByRepo: { 'repo-1': [makeWorktree({ id: WORKTREE_ID, repoId: 'repo-1' })] },
tabsByWorktree: {
[WORKTREE_ID]: [
{
id: TERMINAL,
ptyId: null,
worktreeId: WORKTREE_ID,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
unifiedTabsByWorktree: {
[WORKTREE_ID]: [
{
id: TERMINAL,
entityId: TERMINAL,
groupId: 'group-1',
worktreeId: WORKTREE_ID,
contentType: 'terminal',
label: 'Terminal 1',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
groupsByWorktree: {
[WORKTREE_ID]: [
{ id: 'group-1', worktreeId: WORKTREE_ID, activeTabId: TERMINAL, tabOrder: [TERMINAL] }
]
},
activeGroupIdByWorktree: { [WORKTREE_ID]: 'group-1' },
layoutByWorktree: { [WORKTREE_ID]: { type: 'leaf', groupId: 'group-1' } }
})
main = await drawTabsFromMain(useAppStore)
}
async function shownChat(): Promise<{ drawn: boolean; inMain: boolean; opened: boolean }> {
await main?.settle()
return {
drawn: (useAppStore.getState().unifiedTabsByWorktree[WORKTREE_ID] ?? []).some(
(tab) => tab.entityId === SESSION_ID
),
inMain: (layoutApplyTestTransport.mainModel?.workspaces[WORKTREE_ID]?.tabs ?? []).some(
(tab) => tab.entityId === SESSION_ID
),
opened: layoutApplyTestTransport
.sentOfType('openAgentSessionTab')
.some((command) => command.sessionId === SESSION_ID)
}
}
const NOT_SHOWN = { drawn: false, inMain: false, opened: false }
afterEach(() => {
main?.close()
main = null
})
describe('structured launch cancellation retirement', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.clear()
resetStructuredAgentLaunchPersistenceForTests()
resetStructuredAgentLaunchRegistryForTests()
Object.defineProperty(window, 'api', {
configurable: true,
value: {
runtime: {
call: vi.fn().mockResolvedValue({ ok: true, result: {} })
}
}
})
})
it('keeps a paired server’s late publication suppressed until the cancelled launch settles', async () => {
await expectLatePublicationSuppressed(SERVER_HOST, SERVER)
})
// A runtime refused its chats answers with no chat rows; that absence is not the host's answer.
// Switch on, this machine keeps no tombstone: main's fence is in its close-before-create test.
it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)(
'keeps a tombstone through an inventory that cannot list chats',
async () => {
setStructuredLaunchState({
identity: `codex:${WORKTREE_ID}`,
intent: {
worktreeId: WORKTREE_ID,
executionHostId: 'local',
target: { kind: 'local' },
sessionId: SESSION_ID,
agent: 'codex',
params: {
envelope: {
sessionId: SESSION_ID,
clientOperationId: 'operation-unverifiable',
expectedRuntimeFence: null,
payloadFingerprint: 'fingerprint-unverifiable'
},
worktree: `id:${WORKTREE_ID}`,
agent: 'codex'
}
},
promptDelivery: 'auto-submit',
callers: {
outcome: 'pending',
attempt: { kind: 'first', requestId: 'plus-pick', stagedPrompt: null },
entries: new Set(),
promptDeliveryResults: new Set(),
onSettled: () => undefined
},
promise: Promise.resolve({ sessionId: SESSION_ID, fence: 1 }),
visibilityUnknown: false,
cancelled: false,
selection: {}
} satisfies StructuredLaunchState)
markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, 'local', layoutOwner)
await new Promise((resolve) => setTimeout(resolve, 0))
const frame = (unverifiable: boolean): RuntimeMobileSessionTabsResult => ({
...latePublication(),
activeTabId: null,
activeTabType: null,
tabs: [],
...(unverifiable ? { agentSessionsUnverifiable: true as const } : {})
})
const call = vi.fn()
Object.defineProperty(window, 'api', { configurable: true, value: { runtime: { call } } })
call.mockResolvedValue({
ok: true,
result: { snapshots: [frame(true)], authoritative: true }
})
await refreshLocalStructuredSessionTabs()
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(
true
)
call.mockResolvedValue({
ok: true,
result: { snapshots: [frame(false)], authoritative: true }
})
await refreshLocalStructuredSessionTabs()
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(
false
)
}
)
it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)(
'drains a restored cancellation before a newer inventory retires it',
async () => {
markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, 'local', layoutOwner)
resetStructuredAgentLaunchRegistryForTests()
resetStructuredAgentLaunchPersistenceForTests()
const close = Promise.withResolvers<void>()
const call = vi.fn(({ method }: { method: string }) => {
if (method === 'agentSession.close') {
return close.promise.then(() => ({ ok: true, result: { ok: true } }))
}
return Promise.resolve({ ok: true, result: { snapshots: [], authoritative: true } })
})
Object.defineProperty(window, 'api', {
configurable: true,
value: { runtime: { call } }
})
await refreshLocalStructuredSessionTabs(undefined, { authoritative: true })
expect(call.mock.calls.map(([request]) => request.method)).toEqual([
'agentSession.close',
'session.tabs.listAll'
])
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(
true
)
// The close shares the host's session lane with create, so settlement drains a late attach.
close.resolve()
await close.promise
await new Promise((resolve) => setTimeout(resolve, 0))
await refreshLocalStructuredSessionTabs()
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(
false
)
expect(
call.mock.calls.filter(([request]) => request.method === 'agentSession.close')
).toHaveLength(1)
}
)
// An older switch-off build saved the tombstone; this build drains it on its first inventory.
it.runIf(ORCA_LAYOUT_OWNER_IS_MAIN)(
'drains a tombstone an older build saved: one close, and main shows no chat',
async () => {
localStorage.setItem(
'orca:structuredAgentLaunchCancelledSessions:v1',
JSON.stringify([SESSION_ID])
)
resetStructuredAgentLaunchPersistenceForTests()
await drawWorktreeFromMain()
const close = Promise.withResolvers<void>()
const call = vi.fn(({ method }: { method: string }) => {
if (method === 'agentSession.close') {
return close.promise.then(() => ({ ok: true, result: { ok: true } }))
}
return Promise.resolve({ ok: true, result: { snapshots: [], authoritative: true } })
})
Object.defineProperty(window, 'api', { configurable: true, value: { runtime: { call } } })
await refreshLocalStructuredSessionTabs(undefined, { authoritative: true })
expect(call.mock.calls.map(([request]) => request.method)).toEqual([
'agentSession.close',
'session.tabs.listAll'
])
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(
true
)
close.resolve()
await close.promise
await new Promise((resolve) => setTimeout(resolve, 0))
await refreshLocalStructuredSessionTabs()
expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE_ID, SESSION_ID)).toBe(
false
)
expect(
call.mock.calls.filter(([request]) => request.method === 'agentSession.close')
).toHaveLength(1)
expect(await shownChat()).toEqual(NOT_SHOWN)
}
)
})
@@ -1,319 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { type CoalescedPollRunner, createCoalescedPollRunner } from './coalesced-poll-runner'
function deferred(): {
promise: Promise<void>
resolve: () => void
reject: (error: Error) => void
} {
let resolve: () => void = () => {}
let reject: (error: Error) => void = () => {}
const promise = new Promise<void>((r, j) => {
resolve = r
reject = j
})
return { promise, resolve, reject }
}
async function flushMicrotasks(): Promise<void> {
await Promise.resolve()
await Promise.resolve()
}
describe('createCoalescedPollRunner', () => {
it('keeps one task in flight and runs one trailing task after skipped triggers', async () => {
const calls: ReturnType<typeof deferred>[] = []
const task = vi.fn(() => {
const call = deferred()
calls.push(call)
return call.promise
})
const runner = createCoalescedPollRunner(task)
runner.run()
runner.run()
runner.run()
await flushMicrotasks()
expect(task).toHaveBeenCalledTimes(1)
calls[0]?.resolve()
await flushMicrotasks()
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
expect(task).toHaveBeenCalledTimes(2)
})
it('drops queued trailing work after disposal', async () => {
const call = deferred()
const task = vi.fn(() => call.promise)
const runner = createCoalescedPollRunner(task)
runner.run()
runner.run()
runner.dispose()
call.resolve()
await flushMicrotasks()
expect(task).toHaveBeenCalledTimes(1)
})
it('enforces minIntervalMs delay between consecutive runs', async () => {
vi.useFakeTimers()
const calls: ReturnType<typeof deferred>[] = []
const task = vi.fn(() => {
const call = deferred()
calls.push(call)
return call.promise
})
const runner = createCoalescedPollRunner(task, { minIntervalMs: 1000 })
runner.run()
expect(task).toHaveBeenCalledTimes(1)
runner.run()
expect(task).toHaveBeenCalledTimes(1)
calls[0]?.resolve()
await flushMicrotasks()
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(500)
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(500)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
vi.useRealTimers()
})
describe('slowTaskBackoff', () => {
const BACKOFF = { idleMultiplier: 5, changeSignalMultiplier: 1, maxIntervalMs: 300_000 }
function makeSlowRunner(): {
runner: CoalescedPollRunner
task: ReturnType<typeof vi.fn>
calls: ReturnType<typeof deferred>[]
} {
const calls: ReturnType<typeof deferred>[] = []
const task = vi.fn(() => {
const call = deferred()
calls.push(call)
return call.promise
})
const runner = createCoalescedPollRunner(task, {
minIntervalMs: 3000,
slowTaskBackoff: BACKOFF
})
return { runner, task, calls }
}
async function completeRunOfDuration(
runner: CoalescedPollRunner,
calls: ReturnType<typeof deferred>[],
durationMs: number
): Promise<void> {
runner.run()
await vi.advanceTimersByTimeAsync(durationMs)
calls.at(-1)?.resolve()
await flushMicrotasks()
}
it('scales the tick idle gap with the previous run duration', async () => {
vi.useFakeTimers()
const { runner, task, calls } = makeSlowRunner()
// A 35s run (large-monorepo git status) with poll ticks arriving during it.
runner.run()
runner.run()
await vi.advanceTimersByTimeAsync(35_000)
calls[0]?.resolve()
await flushMicrotasks()
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(3000)
runner.run()
await vi.advanceTimersByTimeAsync(171_998)
runner.run()
expect(task).toHaveBeenCalledTimes(1)
// 5x the 35s duration → next tick-driven run only after 175s idle.
await vi.advanceTimersByTimeAsync(2)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
vi.useRealTimers()
})
it('caps the backoff at maxIntervalMs', async () => {
vi.useFakeTimers()
const { runner, task, calls } = makeSlowRunner()
await completeRunOfDuration(runner, calls, 120_000)
expect(task).toHaveBeenCalledTimes(1)
// 5 x 120s = 600s uncapped; the cap holds the gap to 300s.
runner.run()
await vi.advanceTimersByTimeAsync(299_999)
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
vi.useRealTimers()
})
it('paces a GitCommandTimeoutError from its full timeout duration', async () => {
vi.useFakeTimers()
const { runner, task, calls } = makeSlowRunner()
runner.run()
runner.run()
await vi.advanceTimersByTimeAsync(120_000)
const timeoutError = new Error('git timed out.')
timeoutError.name = 'GitCommandTimeoutError'
calls[0]?.reject(timeoutError)
await flushMicrotasks()
await vi.advanceTimersByTimeAsync(299_999)
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
vi.useRealTimers()
})
it('keeps minIntervalMs as the gap for fast tasks', async () => {
vi.useFakeTimers()
const { runner, task, calls } = makeSlowRunner()
await completeRunOfDuration(runner, calls, 100)
expect(task).toHaveBeenCalledTimes(1)
// max(3000, 5 x 100ms) = 3000 → normal-repo cadence is unchanged.
runner.run()
await vi.advanceTimersByTimeAsync(2999)
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
vi.useRealTimers()
})
it('lets change signals run after the short backoff instead of the tick backoff', async () => {
vi.useFakeTimers()
const { runner, task, calls } = makeSlowRunner()
await completeRunOfDuration(runner, calls, 35_000)
expect(task).toHaveBeenCalledTimes(1)
// A change signal waits 1 x 35s, not 5 x 35s.
runner.run({ changeSignal: true })
await vi.advanceTimersByTimeAsync(34_999)
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
vi.useRealTimers()
})
it('pulls an already-scheduled tick run earlier when a change signal arrives', async () => {
vi.useFakeTimers()
const { runner, task, calls } = makeSlowRunner()
await completeRunOfDuration(runner, calls, 35_000)
runner.run() // tick scheduled for +175s
await vi.advanceTimersByTimeAsync(10_000)
runner.run({ changeSignal: true }) // reschedules for end + 35s
await vi.advanceTimersByTimeAsync(24_999)
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
await vi.advanceTimersByTimeAsync(600_000)
expect(task).toHaveBeenCalledTimes(2)
vi.useRealTimers()
})
it('does not let a later tick delay a scheduled change-signal run', async () => {
vi.useFakeTimers()
const { runner, task, calls } = makeSlowRunner()
await completeRunOfDuration(runner, calls, 35_000)
runner.run({ changeSignal: true }) // scheduled for +35s
await vi.advanceTimersByTimeAsync(10_000)
runner.run() // tick must not push the schedule to +175s
await vi.advanceTimersByTimeAsync(24_999)
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
vi.useRealTimers()
})
it('keeps change-signal pacing for a signal that arrived mid-run', async () => {
vi.useFakeTimers()
const { runner, task, calls } = makeSlowRunner()
runner.run()
await vi.advanceTimersByTimeAsync(20_000)
runner.run({ changeSignal: true }) // during flight
await vi.advanceTimersByTimeAsync(15_000)
runner.run() // a later tick must not downgrade the pending signal
calls[0]?.resolve()
await flushMicrotasks()
expect(task).toHaveBeenCalledTimes(1)
// Trailing rerun waits 1 x 35s (signal), not 5 x 35s (tick).
await vi.advanceTimersByTimeAsync(34_999)
expect(task).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(task).toHaveBeenCalledTimes(2)
calls[1]?.resolve()
await flushMicrotasks()
vi.useRealTimers()
})
})
it('cancels scheduled deferred run on dispose', async () => {
vi.useFakeTimers()
const calls: ReturnType<typeof deferred>[] = []
const task = vi.fn(() => {
const call = deferred()
calls.push(call)
return call.promise
})
const runner = createCoalescedPollRunner(task, { minIntervalMs: 1000 })
runner.run()
runner.run()
calls[0]?.resolve()
await flushMicrotasks()
runner.dispose()
await vi.advanceTimersByTimeAsync(1000)
expect(task).toHaveBeenCalledTimes(1)
vi.useRealTimers()
})
})
@@ -1,534 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Terminal } from '@xterm/xterm'
import {
detachPaneEcho,
discardUndispatchedKeystroke,
drainTimedOutEchoCandidates,
instrumentPaneEcho,
recordKeystroke,
type EchoObservation,
type InstrumentedPane
} from './echo-instrumentation'
function emptyEntry(): InstrumentedPane {
return {
pane: {},
undispatched: [],
nextDispatch: null,
deferredNextDispatch: null,
ignoredDispatches: [],
ignoredDispatchOverflowedAt: null,
awaitingEcho: [],
attributionGap: false,
parsingBatch: null,
parsedBatches: [],
pendingCount: 0,
disposables: [],
restoreWrite: null
}
}
type FakeTerminal = {
write: (data: string | Uint8Array, callback?: () => void) => void
onData: (listener: (data: string) => void) => { dispose: () => void }
onWriteParsed: (listener: () => void) => { dispose: () => void }
onRender: (listener: () => void) => { dispose: () => void }
}
type CoreServiceAccess = {
_core: {
coreService: {
triggerDataEvent: (data: string, wasUserInput?: boolean) => void
}
}
}
function fakeTerminal(): {
terminal: FakeTerminal
emitData: (data?: string) => void
emitParsed: () => void
emitRender: () => void
writtenPayloads: (string | Uint8Array)[]
disposeCount: () => number
} {
const dataListeners = new Set<(data: string) => void>()
const parsedListeners = new Set<() => void>()
const renderListeners = new Set<() => void>()
const writtenPayloads: (string | Uint8Array)[] = []
let disposed = 0
const listen = <T>(listeners: Set<T>, listener: T): { dispose: () => void } => {
listeners.add(listener)
return {
dispose: () => {
if (listeners.delete(listener)) {
disposed += 1
}
}
}
}
return {
terminal: {
write: (data) => writtenPayloads.push(data),
onData: (listener) => listen(dataListeners, listener),
onWriteParsed: (listener) => listen(parsedListeners, listener),
onRender: (listener) => listen(renderListeners, listener)
},
emitData: (data = 'x') => dataListeners.forEach((listener) => listener(data)),
emitParsed: () => parsedListeners.forEach((listener) => listener()),
emitRender: () => renderListeners.forEach((listener) => listener()),
writtenPayloads,
disposeCount: () => disposed
}
}
function recordAndDispatch(
entry: InstrumentedPane,
fake: ReturnType<typeof fakeTerminal>,
source: 'direct' | 'ime' = 'direct',
recordedAt: number = performance.now()
): void {
recordKeystroke(entry, recordedAt, source)
fake.emitData()
}
afterEach(() => {
vi.restoreAllMocks()
})
describe('recordKeystroke', () => {
it('drains a final timed-out input without waiting for another keystroke', () => {
const entry = emptyEntry()
const recorded = recordKeystroke(entry, 0, 'direct')
expect(drainTimedOutEchoCandidates(entry, 2_001)).toBe(1)
expect(drainTimedOutEchoCandidates(entry, 2_002)).toBe(0)
expect(recorded.candidate.status).toBe('unmatched-undispatched')
expect(entry.pendingCount).toBe(0)
})
it('reverses timeout accounting when an undispatched IME commit settles prevented', () => {
const entry = emptyEntry()
const recorded = recordKeystroke(entry, 0, 'ime')
expect(drainTimedOutEchoCandidates(entry, 2_001)).toBe(1)
expect(discardUndispatchedKeystroke(entry, recorded.candidate)).toBe('counted-unmatched')
expect(discardUndispatchedKeystroke(entry, recorded.candidate)).toBeNull()
expect(entry).toMatchObject({ pendingCount: 0, ignoredDispatches: [] })
})
it('keeps timeout accounting when the IME commit reached terminal input', () => {
const fake = fakeTerminal()
const entry = instrumentPaneEcho({ terminal: fake.terminal }, () => undefined)
const recorded = recordKeystroke(entry, 0, 'ime')
fake.emitData('한')
expect(drainTimedOutEchoCandidates(entry, 2_001)).toBe(1)
expect(recorded.candidate.status).toBe('unmatched-dispatched')
expect(discardUndispatchedKeystroke(entry, recorded.candidate)).toBeNull()
expect(entry.pendingCount).toBe(0)
})
it('drops a prevented commit only when it never dispatched', () => {
const fake = fakeTerminal()
const entry = instrumentPaneEcho({ terminal: fake.terminal }, () => undefined)
const prevented = recordKeystroke(entry, 10, 'ime')
expect(discardUndispatchedKeystroke(entry, prevented.candidate)).toBe('pending')
const dispatched = recordKeystroke(entry, 20, 'ime')
fake.emitData('글')
expect(discardUndispatchedKeystroke(entry, dispatched.candidate)).toBeNull()
expect(entry.awaitingEcho).toHaveLength(1)
})
it('dispatches a nested IME finalizer before its outer direct key', () => {
const fake = fakeTerminal()
const entry = instrumentPaneEcho({ terminal: fake.terminal }, () => undefined)
recordKeystroke(entry, 10, 'direct')
recordKeystroke(entry, 11, 'ime')
fake.emitData('한')
fake.emitData('\r')
expect(entry.awaitingEcho.map((pending) => pending.source)).toEqual(['ime', 'direct'])
})
it('uses a cap-rejection sentinel instead of consuming a retained input', () => {
const fake = fakeTerminal()
const entry = instrumentPaneEcho({ terminal: fake.terminal }, () => undefined)
for (let index = 0; index < 64; index += 1) {
recordKeystroke(entry, index, 'direct')
}
expect(recordKeystroke(entry, 64, 'direct').unmatched).toBe(1)
fake.emitData('rejected')
expect(entry.undispatched).toHaveLength(64)
expect(entry.awaitingEcho).toEqual([])
expect(entry.pendingCount).toBe(64)
expect(entry.attributionGap).toBe(true)
})
it('fences overflow dispatches without consuming retained inputs', () => {
const fake = fakeTerminal()
const entry = instrumentPaneEcho({ terminal: fake.terminal }, () => undefined)
for (let index = 0; index < 64; index += 1) {
recordKeystroke(entry, index, 'direct')
}
for (let index = 64; index < 129; index += 1) {
recordKeystroke(entry, index, 'direct')
}
expect(entry.ignoredDispatches).toHaveLength(64)
expect(entry.ignoredDispatchOverflowedAt).toBe(128)
for (let index = 0; index < 65; index += 1) {
fake.emitData('rejected')
}
expect(entry.undispatched).toHaveLength(64)
expect(entry).toMatchObject({
awaitingEcho: [],
pendingCount: 64,
ignoredDispatches: [],
ignoredDispatchOverflowedAt: 128
})
expect(drainTimedOutEchoCandidates(entry, 2_129)).toBe(64)
expect(entry).toMatchObject({
undispatched: [],
pendingCount: 0,
ignoredDispatchOverflowedAt: null
})
const recovered = recordKeystroke(entry, 2_130, 'direct')
fake.emitData('recovered')
expect(entry.awaitingEcho).toEqual([recovered.candidate])
})
it('settles a prevented cap-rejected commit without touching retained inputs', () => {
const entry = emptyEntry()
for (let index = 0; index < 64; index += 1) {
recordKeystroke(entry, index, 'direct')
}
const rejected = recordKeystroke(entry, 64, 'ime')
expect(rejected.unmatched).toBe(1)
expect(discardUndispatchedKeystroke(entry, rejected.candidate)).toBe('counted-unmatched')
expect(entry.undispatched).toHaveLength(64)
expect(entry.ignoredDispatches).toEqual([])
expect(entry.attributionGap).toBe(false)
})
it('settles overlapping cap-rejected commits by identity', () => {
const entry = emptyEntry()
for (let index = 0; index < 64; index += 1) {
recordKeystroke(entry, index, 'direct')
}
const first = recordKeystroke(entry, 64, 'ime')
const second = recordKeystroke(entry, 65, 'ime')
expect(first.unmatched).toBe(1)
expect(second.unmatched).toBe(1)
expect(discardUndispatchedKeystroke(entry, first.candidate)).toBe('counted-unmatched')
expect(discardUndispatchedKeystroke(entry, second.candidate)).toBe('counted-unmatched')
expect(entry.undispatched).toHaveLength(64)
expect(entry.ignoredDispatches).toEqual([])
expect(entry.attributionGap).toBe(false)
})
it('settles same-timestamp cap rejections independently', () => {
const entry = emptyEntry()
for (let index = 0; index < 64; index += 1) {
recordKeystroke(entry, index, 'direct')
}
const first = recordKeystroke(entry, 64, 'ime')
const second = recordKeystroke(entry, 64, 'ime')
expect(discardUndispatchedKeystroke(entry, first.candidate)).toBe('counted-unmatched')
expect(discardUndispatchedKeystroke(entry, second.candidate)).toBe('counted-unmatched')
expect(entry.ignoredDispatches).toEqual([])
})
})
describe('instrumentPaneEcho', () => {
it('does not attribute parser replies as user dispatches', () => {
const terminal = new Terminal({ allowProposedApi: true })
const entry = instrumentPaneEcho({ terminal }, () => undefined)
const coreService = (terminal as unknown as CoreServiceAccess)._core.coreService
recordKeystroke(entry, 10, 'direct')
coreService.triggerDataEvent('\x1b[?1;2c', false)
expect(entry.undispatched).toHaveLength(1)
expect(entry.awaitingEcho).toEqual([])
coreService.triggerDataEvent('a', true)
expect(entry.undispatched).toEqual([])
expect(entry.awaitingEcho).toHaveLength(1)
detachPaneEcho(entry)
terminal.dispose()
})
it('does not credit output that arrived before the input dispatched', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordKeystroke(entry, performance.now(), 'direct')
fake.terminal.write('unrelated')
fake.emitParsed()
fake.emitRender()
expect(observations).toEqual([])
fake.emitData()
fake.terminal.write('echo')
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
})
it('emits one ambiguous burst when overlapping inputs receive separate outputs', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake, 'direct')
recordAndDispatch(entry, fake, 'direct')
fake.terminal.write('A')
fake.emitParsed()
fake.emitRender()
fake.terminal.write('B')
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
expect(observations[0]).toMatchObject({
attribution: 'ambiguous-burst',
reason: 'overlapping-inputs',
inputCount: 2,
sourceCounts: { direct: 2, ime: 0 },
outputBatchBytes: 1,
outputBatchWrites: 1
})
})
it('keeps a batch ambiguous when another input arrives before parsing finishes', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake)
fake.terminal.write('x'.repeat(90))
recordAndDispatch(entry, fake)
fake.terminal.write('x'.repeat(30))
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
expect(observations[0]).toMatchObject({
attribution: 'ambiguous-burst',
inputCount: 2,
outputBatchBytes: 120,
outputBatchWrites: 2
})
})
it('aggregates thousands of writes in constant-size batch accounting', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake)
for (let index = 0; index < 1_000; index += 1) {
fake.terminal.write('x')
}
expect(entry.parsingBatch).toMatchObject({ outputBytes: 1_000, outputWrites: 1_000 })
expect(entry.parsingBatch?.candidates).toHaveLength(1)
fake.emitParsed()
fake.emitRender()
expect(observations[0]).toMatchObject({ outputBytes: 1_000, outputWrites: 1_000 })
})
it('keeps parsed batches separate when two parses precede one render', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake)
fake.terminal.write('a')
fake.emitParsed()
recordAndDispatch(entry, fake)
fake.terminal.write('b')
fake.emitParsed()
fake.emitRender()
expect(observations.map((value) => value.attribution)).toEqual(['single-input', 'single-input'])
})
it('marks the first late output after a timeout as ambiguous, then restores confidence', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
const now = vi.spyOn(performance, 'now')
recordKeystroke(entry, 0, 'direct')
now.mockReturnValueOnce(1)
fake.emitData('A')
expect(recordKeystroke(entry, 5_000, 'direct').unmatched).toBe(1)
now.mockReturnValueOnce(5_001)
fake.emitData('B')
fake.terminal.write('late A')
now.mockReturnValueOnce(5_010)
fake.emitParsed()
now.mockReturnValueOnce(5_015)
fake.emitRender()
recordKeystroke(entry, 5_020, 'ime')
now.mockReturnValueOnce(5_021)
fake.emitData('한')
fake.terminal.write('한')
now.mockReturnValueOnce(5_030)
fake.emitParsed()
now.mockReturnValueOnce(5_035)
fake.emitRender()
expect(observations[0]).toMatchObject({
attribution: 'ambiguous-burst',
reason: 'attribution-gap',
inputCount: 1
})
expect(observations[1]).toMatchObject({
attribution: 'single-input',
source: 'ime'
})
})
it('clears a gap-only output boundary without retaining an empty parsed batch', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
const now = vi.spyOn(performance, 'now')
recordKeystroke(entry, 0, 'direct')
now.mockReturnValueOnce(1)
fake.emitData('A')
expect(recordKeystroke(entry, 5_000, 'direct').unmatched).toBe(1)
fake.terminal.write('late A')
now.mockReturnValueOnce(5_001)
fake.emitParsed()
expect(entry.parsedBatches).toEqual([])
now.mockReturnValueOnce(5_002)
fake.emitData('B')
fake.terminal.write('B')
now.mockReturnValueOnce(5_010)
fake.emitParsed()
now.mockReturnValueOnce(5_015)
fake.emitRender()
expect(observations).toHaveLength(1)
expect(observations[0]).toMatchObject({ attribution: 'single-input', startedAt: 5_000 })
})
it('holds an unparsed input across a render instead of discarding it', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake)
fake.terminal.write('echo')
fake.emitRender()
expect(observations).toHaveLength(0)
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
})
it('drains parsed output that never paints exactly once', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake, 'direct', 0)
fake.terminal.write('A')
fake.emitParsed()
expect(drainTimedOutEchoCandidates(entry, 2_001)).toBe(1)
expect(drainTimedOutEchoCandidates(entry, 2_002)).toBe(0)
expect(entry).toMatchObject({ parsedBatches: [], pendingCount: 0 })
recordAndDispatch(entry, fake, 'direct', 2_003)
fake.terminal.write('B')
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
expect(observations[0]).toMatchObject({ attribution: 'single-input', startedAt: 2_003 })
expect(entry.pendingCount).toBe(0)
})
it('keeps a shared unparsed batch ambiguous after draining its stale input', () => {
const fake = fakeTerminal()
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake, 'direct', 0)
fake.terminal.write('late A')
expect(drainTimedOutEchoCandidates(entry, 2_001)).toBe(1)
recordAndDispatch(entry, fake, 'direct', 2_002)
fake.terminal.write('B')
fake.emitParsed()
fake.emitRender()
expect(observations).toHaveLength(1)
expect(observations[0]).toMatchObject({
attribution: 'ambiguous-burst',
reason: 'attribution-gap',
inputCount: 1
})
expect(entry.pendingCount).toBe(0)
})
it('returns trailing unmatched inputs and releases pane and listener closures', () => {
const fake = fakeTerminal()
const originalWrite = fake.terminal.write
const observations: EchoObservation[] = []
const entry = instrumentPaneEcho({ terminal: fake.terminal }, (value) =>
observations.push(value)
)
recordAndDispatch(entry, fake)
fake.terminal.write('parsed but not painted')
fake.emitParsed()
recordKeystroke(entry, performance.now(), 'direct')
expect(detachPaneEcho(entry)).toBe(2)
expect(fake.terminal.write).toBe(originalWrite)
expect(fake.disposeCount()).toBe(3)
expect(entry).toMatchObject({ pane: null, pendingCount: 0, restoreWrite: null })
fake.emitRender()
fake.emitData()
expect(observations).toEqual([])
})
})
@@ -1,90 +0,0 @@
import { describe, expect, it } from 'vitest'
import { appendExactLatencySample, createExactLatencySampleWindow } from './sample-window'
import type { ExactEchoSample } from './echo-observation'
import { summarizeLatencySamples } from './diagnostic-summary'
function exactSample(value: number): ExactEchoSample {
return {
attribution: 'single-input',
source: 'direct',
inputToDispatchMs: value,
dispatchToParseMs: value + 10000,
parseToPaintMs: value + 20000,
inputToPaintMs: 3 * value + 30000,
eventToHandlerMs: null,
eventToPaintMs: null,
dispatchToArrivalMs: null,
arrivalToWriteMs: null,
writeToParseMs: null,
startedAt: value,
paintedAt: 3 * value + 30000,
outputBytes: value + 40000,
outputWrites: value + 5000
}
}
describe('typing latency sample window', () => {
it('expires optional phases with their inputs across mixed direct and IME captures', () => {
const samples = createExactLatencySampleWindow()
const optionalFields = [
'eventToHandlerMs',
'eventToPaintMs',
'dispatchToArrivalMs',
'arrivalToWriteMs',
'writeToParseMs'
] as const
appendExactLatencySample(samples, {
...exactSample(0),
eventToHandlerMs: 999,
eventToPaintMs: 999,
dispatchToArrivalMs: 999,
arrivalToWriteMs: 999,
writeToParseMs: 999
})
for (let value = 1; value < 2000; value += 1) {
appendExactLatencySample(samples, { ...exactSample(value), source: 'ime' })
}
for (const field of optionalFields) {
expect(summarizeLatencySamples(samples[field])).toEqual({
count: 1,
p50: 999,
p95: 999,
max: 999
})
}
appendExactLatencySample(samples, {
...exactSample(2000),
eventToHandlerMs: 0,
dispatchToArrivalMs: 3,
writeToParseMs: 5
})
for (const [field, value] of [
['eventToHandlerMs', 0],
['eventToPaintMs', null],
['dispatchToArrivalMs', 3],
['arrivalToWriteMs', null],
['writeToParseMs', 5]
] as const) {
expect(samples[field]).toHaveLength(2000)
expect(summarizeLatencySamples(samples[field])).toEqual({
count: value === null ? 0 : 1,
p50: value,
p95: value,
max: value
})
}
for (let value = 2001; value <= 4000; value += 1) {
appendExactLatencySample(samples, { ...exactSample(value), source: 'ime' })
}
for (const field of optionalFields) {
expect(summarizeLatencySamples(samples[field])).toEqual({
count: 0,
p50: null,
p95: null,
max: null
})
}
})
})
@@ -16,7 +16,7 @@ import { activateWorkspaceTabPaletteResult } from './workspace-tab-palette-activ
import {
getClientHostedBrowserRowSelection,
selectClientHostedBrowserRow
} from '../../../pane-manager/client-hosted-browser-row-state'
} from '../../../../runtime/browser/client-hosting/client-hosted-browser-row-state'
const initialState = useAppStore.getInitialState()
afterEach(() => useAppStore.setState(initialState, true))

Some files were not shown because too many files have changed in this diff Show More