Merge remote-tracking branch 'origin/main' into brennanb2025/claude-parent-env-scrub

This commit is contained in:
Brennan Benson
2026-11-09 14:31:56 -08:00
105 changed files with 3207 additions and 3098 deletions
@@ -33,7 +33,6 @@ on:
- 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts'
- 'src/main/claude-usage/scanner-incremental-append.test.ts'
- 'src/main/claude-usage/store-checkpoint-persistence.test.ts'
- 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx'
permissions:
contents: read
File diff suppressed because one or more lines are too long
@@ -5199,9 +5199,7 @@
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.host-outage.test.tsx": 3552,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx": 2911,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx": 3014,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.retained-draft.test.tsx": 3736,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx": 4459,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.wsl-host-stopped.test.tsx": 3657,
"src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx": 583,
"src/renderer/src/components/native-chat/tools/lines/NativeChatToolLine.test.tsx": 3544,
"src/renderer/src/components/native-chat/tools/lines/NativeChatToolOutput.test.tsx": 410,
@@ -5275,7 +5273,6 @@
"src/renderer/src/components/native-chat/pane/routing/native-chat-split-flow.test.ts": 1916,
"src/renderer/src/components/native-chat/composer/submit/native-chat-structured-send-composition-clear.test.tsx": 2098,
"src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff-copy-budget.test.ts": 362,
"src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-work-runs.test.ts": 278,
"src/renderer/src/components/native-chat/pane/routing/native-chat-tab-directory.test.ts": 304,
"src/renderer/src/components/native-chat/native-chat-task-list-state.test.ts": 62,
"src/renderer/src/components/native-chat/native-chat-thread-goal-rows.test.ts": 50,
+1 -2
View File
@@ -22,8 +22,7 @@ const contracts = [
'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs',
'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs',
'src/main/claude-usage/scanner-incremental-append.test.ts',
'src/main/claude-usage/store-checkpoint-persistence.test.ts',
'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx'
'src/main/claude-usage/store-checkpoint-persistence.test.ts'
]
for (const contract of contracts) {
if (!existsSync(resolve(contract))) {
+1 -1
View File
@@ -27,4 +27,4 @@ The chat root (`.native-chat-appearance`) redefines these steps as ratios of the
- **Focus rings:** full-width transcript rows use the inset ring (`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring`) so it isn't clipped by the scroll container; standalone controls use `focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`. Inside the chat `--ring` is `--chat-focus-ring`, which clears 3:1 on the canvas; don't lower its opacity.
- **Theme overrides:** plugin themes can set `--chat-bold-foreground`, `--chat-muted-foreground`, `--chat-inline-code`, `--chat-inline-code-foreground`, `--chat-code-block`, `--chat-selection` and `--chat-selection-foreground`. They feed `text-chat-foreground-faint`, `bg-chat-inline-code-surface`, `bg-chat-code-surface` and the chat root's `::selection`, so use those rather than reading the theme tokens directly.
- **Selection** inside the chat is the link hue mixed into the canvas (close to the system highlight), with selected text in the full foreground so every role stays 4.5:1. Don't add per-component `selection:` colors in transcript text.
- **State colours:** warnings use `text-chat-warning`; diff lines use `text-chat-diff-added` / `text-chat-diff-removed`. They are mixed toward the foreground so they pass text contrast in light and dark. Don't use raw palette colours (`text-yellow-500`) or the git decoration tokens for text on a tinted row.
- **State colours:** warnings use `text-chat-warning`; diff lines use `text-chat-diff-added` / `text-chat-diff-removed`; what the reader has not seen yet uses `text-chat-unread`. They are mixed toward the foreground so they pass text contrast in light and dark. Don't use raw palette colours (`text-yellow-500`) or the git decoration tokens for text on a tinted row.
@@ -5,3 +5,7 @@ Handle a whole `check` batch before the next `check`.
Groups (`@all`, `@idle`, `@codex`, ...) reach the live workers of your Run;
`@worktree:<id>` also reaches coordinators in that workspace. Use groups only
for deliberate fan-out.
To reach an agent on a paired server, use `send --on <server>`; a reply to mail
from another server needs no flag. See
[Placement and remote execution](placement-and-remote.md).
@@ -35,3 +35,24 @@ workspace, and the start output names the workspace it created.
After start, address a remote worker only by Dispatch ID, never by a terminal
handle.
## Agents on another server
To message an agent that already runs on a paired server, send with `--on`,
using the same server names as `worker-start --on`:
```bash
ORCA orchestration send --on <server> --to <term_…|orca_session_id:…> --subject "<text>" --body "<text>"
```
Your own Orca carries the mail and keeps the conversation. Replies come back to
your own `check`, and they wake you like local mail. The other agent answers
with a plain `reply --id <msg_id> --body <text>`; no flag is needed on either
side. Mail from another server names its sender as `<sender> on <server name>`.
`--environment <server>` runs one command on that server and delivers nothing back
to you, so an agent never mails with it. Your mailbox stays on your own Orca:
`check` takes no `--environment`. Read-only commands such as `inbox` or
`worker-list` with `--environment` show that server's records. A server whose Orca
is too old answers `server_mail_unsupported` and nothing is sent. Pair servers
with `orca pair` or in Settings.
+25
View File
@@ -4101,6 +4101,10 @@ const ORCHESTRATION_MESSAGING_AND_GATES_REFERENCE_MARKDOWN = [
"`@worktree:<id>` also reaches coordinators in that workspace. Use groups only",
"for deliberate fan-out.",
"",
"To reach an agent on a paired server, use `send --on <server>`; a reply to mail",
"from another server needs no flag. See",
"[Placement and remote execution](placement-and-remote.md).",
"",
].join('\n')
// oxfmt-ignore
@@ -4143,6 +4147,27 @@ const ORCHESTRATION_PLACEMENT_AND_REMOTE_REFERENCE_MARKDOWN = [
"After start, address a remote worker only by Dispatch ID, never by a terminal",
"handle.",
"",
"## Agents on another server",
"",
"To message an agent that already runs on a paired server, send with `--on`,",
"using the same server names as `worker-start --on`:",
"",
"```bash",
"ORCA orchestration send --on <server> --to <term_…|orca_session_id:…> --subject \"<text>\" --body \"<text>\"",
"```",
"",
"Your own Orca carries the mail and keeps the conversation. Replies come back to",
"your own `check`, and they wake you like local mail. The other agent answers",
"with a plain `reply --id <msg_id> --body <text>`; no flag is needed on either",
"side. Mail from another server names its sender as `<sender> on <server name>`.",
"",
"`--environment <server>` runs one command on that server and delivers nothing back",
"to you, so an agent never mails with it. Your mailbox stays on your own Orca:",
"`check` takes no `--environment`. Read-only commands such as `inbox` or",
"`worker-list` with `--environment` show that server's records. A server whose Orca",
"is too old answers `server_mail_unsupported` and nothing is sent. Pair servers",
"with `orca pair` or in Settings.",
"",
].join('\n')
// oxfmt-ignore
@@ -0,0 +1,105 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as RuntimeClientModule from '../../runtime-client'
import { refuseAgentServerRoute, requirePeerMailCarrier } from './agent-server-route'
const { callerShow } = vi.hoisted(() => ({ callerShow: vi.fn() }))
vi.mock('../../runtime-client', async (importOriginal) => {
const actual = await importOriginal<typeof RuntimeClientModule>()
return {
...actual,
RuntimeClient: class {
call = callerShow
}
}
})
function ctx(command: string[], flags: [string, string | boolean][]) {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a handler context with only the fields this function reads.
return {
flags: new Map(flags),
client: { isRemote: true },
cwd: '/',
json: false,
rawArgs: [...command, ...flags.flatMap(([name, value]) => [`--${name}`, String(value)])]
} as unknown as Parameters<typeof refuseAgentServerRoute>[1]
}
describe('an agent pointing mail at another server', () => {
beforeEach(() => {
vi.stubEnv('ORCA_AGENT_LAUNCH_TOKEN', 'launch-token')
vi.stubEnv('ORCA_AGENT_SESSION_ID', '')
vi.stubEnv('ORCA_CLI_COMMAND', 'orca')
callerShow.mockResolvedValue({ result: { caller: null, terminal: true } })
})
afterEach(() => {
vi.unstubAllEnvs()
callerShow.mockReset()
})
it('is refused with the --on command to run instead', async () => {
await expect(
refuseAgentServerRoute(
'send',
ctx(
['orchestration', 'send'],
[
['environment', 'devB'],
['to', 'term_b'],
['subject', 'hi']
]
)
)
).rejects.toMatchObject({
code: 'agent_server_route_refused',
message:
'send with --environment devB runs on devB and nothing comes back to you. To message an agent on devB, use: orca orchestration send --on devB --to term_b --subject hi'
})
})
it('refuses a check against another server: the mailbox is local', async () => {
await expect(
refuseAgentServerRoute('check', ctx(['orchestration', 'check'], [['environment', 'devB']]))
).rejects.toMatchObject({
code: 'mailbox_is_local',
message:
'Your mailbox is on this Orca; replies from devB arrive here. Drop --environment devB.'
})
})
it('leaves a person in a shell running the command on that server', async () => {
vi.stubEnv('ORCA_AGENT_LAUNCH_TOKEN', '')
await expect(
refuseAgentServerRoute('send', ctx(['orchestration', 'send'], [['environment', 'devB']]))
).resolves.toBeUndefined()
expect(callerShow).not.toHaveBeenCalled()
})
it('leaves a launch its own Orca does not verify running on that server', async () => {
callerShow.mockResolvedValue({ result: { caller: null, terminal: false } })
await expect(
refuseAgentServerRoute('send', ctx(['orchestration', 'send'], [['environment', 'devB']]))
).resolves.toBeUndefined()
})
})
describe('send --on from an older Orca', () => {
it('is refused before anything is sent', async () => {
const call = vi
.fn()
.mockResolvedValue({ result: { capabilities: ['orchestration.contract.v1'] } })
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a handler context with only the fields this function reads.
const context = {
flags: new Map([['on', 'devB']]),
client: { call },
cwd: '/',
json: false
} as unknown as Parameters<typeof requirePeerMailCarrier>[0]
await expect(requirePeerMailCarrier(context)).rejects.toMatchObject({
code: 'server_mail_unsupported'
})
expect(call).toHaveBeenCalledTimes(1)
expect(call).toHaveBeenCalledWith('status.get')
})
})
@@ -0,0 +1,95 @@
import type { HandlerContext } from '../../dispatch'
import { RuntimeClient, RuntimeClientError } from '../../runtime-client'
import { readInjectedAgentSessionId } from '../../../shared/agent-session/lifecycle/agent-session-caller-env'
import type { OrchestrationCallerShowResult } from '../../../shared/orchestration/orchestration-caller-status'
import { renderOrchestrationArgv } from './agent-view'
import type { RuntimeStatus } from '../../../shared/runtime-types'
import { ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY } from '../../../shared/orchestration/orchestration-runtime-capabilities'
type AgentServerRoutedCommand = 'send' | 'worker-start' | 'check'
/** The server a remote client was pointed at, as the caller spelled it. */
function serverSelector(
flags: HandlerContext['flags']
): { name: string; route: string } | undefined {
const explicit = flags.get('environment')
if (typeof explicit === 'string') {
return { name: explicit, route: `--environment ${explicit}` }
}
const inherited = process.env.ORCA_ENVIRONMENT?.trim()
return inherited ? { name: inherited, route: `ORCA_ENVIRONMENT=${inherited}` } : undefined
}
/** Only an agent its own Orca verifies counts; a person's shell keeps --environment = run it there. */
async function isOrcaVerifiedAgent(): Promise<boolean> {
if (!readInjectedAgentSessionId() && !process.env.ORCA_AGENT_LAUNCH_TOKEN?.trim()) {
return false
}
try {
const local = new RuntimeClient(undefined, 10_000, null, null)
const { result } = await local.call<OrchestrationCallerShowResult>('orchestration.callerShow')
return result.caller !== null || result.terminal === true
} catch {
return false
}
}
/** The same command with the server moved from --environment to --on. */
function withOn(rawArgs: readonly string[] | undefined, server: string): string {
const args = rawArgs ?? []
const kept: string[] = []
for (let index = 0; index < args.length; index += 1) {
const arg = args[index]!
const [name] = arg.split('=', 1)
if (name === '--environment') {
if (!arg.includes('=')) {
index += 1
}
continue
}
kept.push(arg)
}
const at = kept.findIndex((arg) => arg === 'send' || arg === 'worker-start')
kept.splice(at + 1, 0, '--on', server)
return renderOrchestrationArgv(kept) ?? ''
}
/** An agent's mail and workers live on its own Orca; pointing them at another server reaches nobody. */
export async function refuseAgentServerRoute(
command: AgentServerRoutedCommand,
ctx: HandlerContext
): Promise<void> {
if (!ctx.client.isRemote || ctx.flags.has('on')) {
return
}
const server = serverSelector(ctx.flags)
if (!server || !(await isOrcaVerifiedAgent())) {
return
}
const { name, route } = server
if (command === 'check') {
throw new RuntimeClientError(
'mailbox_is_local',
`Your mailbox is on this Orca; replies from ${name} arrive here. Drop ${route}.`
)
}
const verb = command === 'send' ? 'message an agent' : 'start a worker'
throw new RuntimeClientError(
'agent_server_route_refused',
`${command} with ${route} runs on ${name} and nothing comes back to you. To ${verb} on ${name}, use: ${withOn(ctx.rawArgs, name)}`
)
}
/** An older Orca would drop --on and send the mail to an agent here, so it must carry mail between servers first. */
export async function requirePeerMailCarrier(ctx: HandlerContext): Promise<void> {
if (!ctx.flags.has('on')) {
return
}
const { result } = await ctx.client.call<RuntimeStatus>('status.get')
if (!result.capabilities?.includes(ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'server_mail_unsupported',
'The Orca running here is too old to carry mail to another server. Update or restart Orca here, then send again. Nothing was sent.'
)
}
}
@@ -1,4 +1,5 @@
import type { CommandHandler } from '../../dispatch'
import { refuseAgentServerRoute } from './agent-server-route'
import { printResult } from '../../format'
import { withReceiptNext } from './receipt-next-text'
import { printOrchestrationResult } from './agent-view'
@@ -32,7 +33,9 @@ type CheckResult = {
}
export const ORCHESTRATION_CHECK_HANDLER: Record<string, CommandHandler> = {
'orchestration check': async ({ flags, client, cwd, json }) => {
'orchestration check': async (ctx) => {
const { flags, client, cwd, json } = ctx
await refuseAgentServerRoute('check', ctx)
const wait = flags.has('wait')
const peek = flags.has('peek')
// Older runtimes ignore peek, making --unread --peek destructive.
@@ -11,13 +11,16 @@ import {
type OrchestrationMessageSummary as MessageSummary
} from '../../../shared/orchestration/mailbox/orchestration-check-output'
import { callOrchestrationMutation } from './mutation-request'
import { requirePeerMailCarrier } from './agent-server-route'
import { resolveOrchestrationTerminalHandle } from './terminal-identity'
import { withReceiptNext } from './receipt-next-text'
import { printOrchestrationResult } from './agent-view'
import { formatMessageViewText, toMessageView, type MessageView } from './message-agent-views'
export const ORCHESTRATION_INBOX_HANDLERS: Record<string, CommandHandler> = {
'orchestration reply': async ({ flags, client, cwd, json }) => {
'orchestration reply': async (ctx) => {
const { flags, client, cwd, json } = ctx
await requirePeerMailCarrier(ctx)
const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
const result = await callOrchestrationMutation<{
message: { id: string }
@@ -27,6 +30,7 @@ export const ORCHESTRATION_INBOX_HANDLERS: Record<string, CommandHandler> = {
id: getRequiredStringFlag(flags, 'id'),
body: getRequiredStringFlag(flags, 'body'),
run: getOptionalStringFlag(flags, 'run'),
on: getOptionalStringFlag(flags, 'on'),
from
})
if (!flags.has('full')) {
@@ -12,6 +12,7 @@ import { requireWorkerDoneSettlement } from '../orchestration-worker-settlement'
import { getOptionalStructuredMessagePayload } from './message-payload'
import { callOrchestrationMutation } from './mutation-request'
import { isDevCliInvocation } from './runtime-compatibility'
import { refuseAgentServerRoute, requirePeerMailCarrier } from './agent-server-route'
import {
resolveOrchestrationTerminalHandle,
throwNoActiveSenderTerminal
@@ -70,7 +71,10 @@ function rejectLifecycleGroupRecipient(type: string | undefined, to: string): vo
}
export const ORCHESTRATION_SEND_HANDLER: Record<string, CommandHandler> = {
'orchestration send': async ({ flags, client, cwd, json }) => {
'orchestration send': async (ctx) => {
const { flags, client, cwd, json } = ctx
await refuseAgentServerRoute('send', ctx)
await requirePeerMailCarrier(ctx)
const to = getOptionalStringFlag(flags, 'to')
const type = getOptionalStringFlag(flags, 'type')
if (to) {
@@ -99,6 +103,7 @@ export const ORCHESTRATION_SEND_HANDLER: Record<string, CommandHandler> = {
from,
to,
run: getOptionalStringFlag(flags, 'run'),
on: getOptionalStringFlag(flags, 'on'),
subject: getRequiredStringFlag(flags, 'subject'),
body: getOptionalStringFlag(flags, 'body'),
type,
@@ -19,9 +19,12 @@ import {
import { explainOlderRuntimeRunRequired } from './older-runtime-run-binding'
import { withResolvedNextCommands } from '../../orchestration-mutation-recovery'
import { readTextOrFileFlag } from '../../command-body-input'
import { refuseAgentServerRoute } from './agent-server-route'
export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record<string, CommandHandler> = {
'orchestration worker-start': async ({ flags, client, cwd, json }) => {
'orchestration worker-start': async (ctx) => {
const { flags, client, cwd, json } = ctx
await refuseAgentServerRoute('worker-start', ctx)
const terminal = getPresentStringFlag(flags, 'terminal')
const model = getOptionalStringFlag(flags, 'model')
const effort = getOptionalStringFlag(flags, 'effort')
+23
View File
@@ -103,6 +103,29 @@ describe('--environment local and workspace addresses', () => {
}
})
it('runs worker-start --on on this Orca despite an inherited ORCA_ENVIRONMENT', async () => {
const args = [
'orchestration',
'worker-start',
'--on',
'build-box',
'--spec',
'Go',
'--agent',
'claude'
]
vi.stubEnv('ORCA_ENVIRONMENT', 'srv-b')
runtimeClientConstructorMock.mockClear()
listEnvironmentsMock.mockReturnValue(SAVED)
callMock.mockRejectedValue(new RuntimeClientError('runtime_unavailable', 'stop here'))
await run([...args, '--json'])
expect(runtimeClientConstructorMock).toHaveBeenCalled()
expect(
runtimeClientConstructorMock.mock.calls.every(([, environment]) => environment === null)
).toBe(true)
vi.unstubAllEnvs()
})
it('refuses current against another environment with an inspection command', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const { exitCode, output } = await run([
+27 -1
View File
@@ -105,7 +105,20 @@ export async function main(
refuseConflictingSessionCallerFlags(commandSpec, parsed.flags)
await refuseLocalManagementSelector(parsed.commandPath, parsed.flags)
const RuntimeClientClass = await loadRuntimeClientClass()
const ignoreRemoteSelection = ignoresRemoteSelection(parsed.commandPath)
// `--on` runs on the caller's own Orca, which reaches that server; an inherited selection never reroutes it.
const onCallersOrca = runsOnCallersOrca(parsed.commandPath, parsed.flags)
if (
onCallersOrca &&
(parsed.flags.has('pairing-code') ||
(parsed.flags.has('environment') &&
!isLocalEnvironmentSelector(parsed.flags.get('environment'))))
) {
throw new RuntimeClientError(
'invalid_argument',
'--on already names the server; drop --environment. Your own Orca reaches it.'
)
}
const ignoreRemoteSelection = onCallersOrca || ignoresRemoteSelection(parsed.commandPath)
const pairingCode = ignoreRemoteSelection ? null : parsed.flags.get('pairing-code')
const environmentSelector = ignoreRemoteSelection ? null : parsed.flags.get('environment')
// An explicit local route suppresses ambient ORCA_ENVIRONMENT and pairing codes.
@@ -192,6 +205,19 @@ export async function main(
}
}
const ON_CALLERS_ORCA_COMMANDS: ReadonlySet<string> = new Set(['send', 'reply', 'worker-start'])
function runsOnCallersOrca(
commandPath: readonly string[],
flags: ReadonlyMap<string, string | boolean>
): boolean {
return (
commandPath[0] === 'orchestration' &&
ON_CALLERS_ORCA_COMMANDS.has(commandPath[1] ?? '') &&
flags.has('on')
)
}
async function runClaudeTeams(argv: string[], cwd: string): Promise<void> {
try {
// Forward Claude Code arguments verbatim so new flags work without Orca changes.
+7 -18
View File
@@ -38,10 +38,7 @@ import {
ORCHESTRATION_CONTRACT_VERSION
} from '../../shared/orchestration/orchestration-runtime-capabilities'
import { RemoteRuntimeCompatGate } from './remote-runtime-compat-gate'
import {
createAgentLaunchCallerEvidence,
createOrchestrationCompatibilityEnvelope
} from './orchestration-compatibility-envelope'
import { OrchestrationRequestEvidence } from './orchestration-compatibility-envelope'
import { getTimeoutMsParam, isWaitingCheck } from './runtime-request-timeout'
import {
isWorkerStartTimeoutWithinTimerLimit,
@@ -56,7 +53,6 @@ import {
const LONG_POLL_CLIENT_GRACE_MS = 10_000
// The host records the launched agent in the caller's chat; older hosts ignore the evidence.
const AGENT_LAUNCH_METHODS: ReadonlySet<string> = new Set(['agent.launch', 'agent.launchReplay'])
const loadWebSocketTransport = async () => await import('./websocket-transport.js')
@@ -68,10 +64,7 @@ export class RuntimeClient {
private readonly originalArgs: readonly string[] | undefined
private readonly remoteCompat: RemoteRuntimeCompatGate
private orchestrationContractCheck: Promise<void> | null = null
private readonly orchestrationCompatibility = createOrchestrationCompatibilityEnvelope(
process.env
)
private readonly agentLaunchCaller = createAgentLaunchCallerEvidence(process.env)
private readonly requestEvidence = new OrchestrationRequestEvidence(process.env)
private readonly runtimeSourceFence: RuntimeSourceFence
// Browser session cold starts can take 15–30 seconds; allow time for initialization.
@@ -139,15 +132,11 @@ export class RuntimeClient {
: error
}
}
const compatibilityEnvelope = method.startsWith('orchestration.')
? {
...this.orchestrationCompatibility,
compatibilityInvocationId:
orchestrationRequestId ?? this.orchestrationCompatibility.compatibilityInvocationId
}
: AGENT_LAUNCH_METHODS.has(method) && !this.remote && this.agentLaunchCaller
? { orchestrationCompatibilityEvidence: this.agentLaunchCaller }
: {}
const compatibilityEnvelope = this.requestEvidence.envelopeFor(method, {
remote: this.remote !== null,
mutation: orchestrationMutation,
requestId: orchestrationRequestId
})
const envelope = {
orchestrationCapability: options?.orchestrationCapability,
orchestrationContractVersion: method.startsWith('orchestration.')
@@ -26,3 +26,40 @@ export function createAgentLaunchCallerEvidence(
}
return { agentSessionId }
}
const AGENT_LAUNCH_METHODS: ReadonlySet<string> = new Set(['agent.launch', 'agent.launchReplay'])
/** The caller evidence one request carries, read from this process's environment once. */
export class OrchestrationRequestEvidence {
private readonly orchestration: RuntimeOrchestrationEnvelope
// A chat's session id means nothing on another server, so reads there go like a shell's.
private readonly remoteRead: RuntimeOrchestrationEnvelope
private readonly agentLaunchCaller: RuntimeOrchestrationEnvelope['orchestrationCompatibilityEvidence']
constructor(env: NodeJS.ProcessEnv) {
this.orchestration = createOrchestrationCompatibilityEnvelope(env)
const { agentSessionId: _session, ...shell } =
this.orchestration.orchestrationCompatibilityEvidence ?? {}
this.remoteRead = {
...this.orchestration,
orchestrationCompatibilityEvidence: Object.keys(shell).length > 0 ? shell : undefined
}
this.agentLaunchCaller = createAgentLaunchCallerEvidence(env)
}
envelopeFor(
method: string,
request: { remote: boolean; mutation: boolean; requestId: string | undefined }
): RuntimeOrchestrationEnvelope {
if (method.startsWith('orchestration.')) {
const base = request.remote && !request.mutation ? this.remoteRead : this.orchestration
return {
...base,
compatibilityInvocationId: request.requestId ?? base.compatibilityInvocationId
}
}
return AGENT_LAUNCH_METHODS.has(method) && !request.remote && this.agentLaunchCaller
? { orchestrationCompatibilityEvidence: this.agentLaunchCaller }
: {}
}
}
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest'
import { OrchestrationRequestEvidence } from './orchestration-compatibility-envelope'
const CHAT = { ORCA_AGENT_SESSION_ID: '11111111-1111-4111-8111-111111111111' }
describe('caller evidence on requests to another server', () => {
it('sends a chat read there like a shell, with no session id', () => {
const evidence = new OrchestrationRequestEvidence(CHAT)
expect(
evidence.envelopeFor('orchestration.inbox', {
remote: true,
mutation: false,
requestId: undefined
}).orchestrationCompatibilityEvidence
).toBeUndefined()
})
it('keeps the session id on writes there, so that server still refuses them', () => {
const evidence = new OrchestrationRequestEvidence(CHAT)
expect(
evidence.envelopeFor('orchestration.taskCreate', {
remote: true,
mutation: true,
requestId: 'request_1'
}).orchestrationCompatibilityEvidence
).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' })
})
})
+10 -4
View File
@@ -49,10 +49,11 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
path: ['orchestration', 'send'],
summary: 'Send an inter-agent message',
usage:
'orca orchestration send --subject <text> [--to <run:id|dispatch:id|legacy_handle>] [--run <run_id>] [--from <handle>] [--body <text>] [--type <type>] [--priority <level>] [--thread-id <id>] [--payload <json>] [--task-id <id>] [--dispatch-id <id>] [--outcome <succeeded|failed>] [--files-modified <csv>] [--report-path <path>] [--phase <text>] [--retry-request <id>] [--json]',
'orca orchestration send --subject <text> [--to <run:id|dispatch:id|legacy_handle>] [--on <server>] [--run <run_id>] [--from <handle>] [--body <text>] [--type <type>] [--priority <level>] [--thread-id <id>] [--payload <json>] [--task-id <id>] [--dispatch-id <id>] [--outcome <succeeded|failed>] [--files-modified <csv>] [--report-path <path>] [--phase <text>] [--retry-request <id>] [--json]',
allowedFlags: [
...GLOBAL_FLAGS,
'to',
'on',
'run',
'from',
'subject',
@@ -82,7 +83,8 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
'From a worker, an omitted recipient defaults to its coordinator, also after it finished; mail sent after finishing, worker_done included, leaves the finished task unchanged.',
'Use --to dispatch:<id> for attempt-specific coordinator guidance; Orca durably relays it to a connected worker server.',
'A worker_done with the active task/dispatch IDs completes that task only from the dispatched pane. When stable pane identity is unavailable, the sender handle must exactly match the dispatch assignee; injected preambles include the correct --from value.',
'Prefer --task-id/--dispatch-id/etc. over raw --payload JSON in worker commands; PowerShell strips JSON quotes easily.'
'Prefer --task-id/--dispatch-id/etc. over raw --payload JSON in worker commands; PowerShell strips JSON quotes easily.',
'--on <server> mails a terminal or chat agent on a paired server (--to term_… or orca_session_id:…). Your own Orca carries it, and replies come back to your own check. From an agent, --environment runs the command on that server and delivers no mail.'
]
},
{
@@ -126,8 +128,12 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
summary: 'Reply to a message',
usage:
'orca orchestration reply --id <msg_id> --body <text> [--run <run_id>] [--from <handle>] [--retry-request <id>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'id', 'body', 'run', 'from', 'retry-request'],
identityFlagRoles: { from: 'caller' }
// --on is accepted only to refuse it with the fix; a reply finds its server by itself.
allowedFlags: [...GLOBAL_FLAGS, 'id', 'body', 'run', 'from', 'on', 'retry-request'],
identityFlagRoles: { from: 'caller' },
notes: [
'A reply to mail from an agent on another server goes back to that server by itself; no flag is needed.'
]
},
{
path: ['orchestration', 'inbox'],
+1 -1
View File
@@ -88,7 +88,7 @@ export class AcpSubagents {
this.known.set(update.id, subagent)
if (update.restart && subagent.ended !== undefined) {
subagent.ended = undefined
subagent.reply = undefined
subagent.replyDigest = undefined
}
const ending = update.state !== undefined && acpSubagentOutcome(update.state) !== undefined
// Late live reports must not resurrect an ended run after the host retires its record.
+15
View File
@@ -61,6 +61,7 @@ import { HEADLESS_RUNTIME_WINDOW_ID } from '../../shared/runtime-session-contrac
import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides'
import type { OrchestrationDb } from './orchestration/db/orchestration-db'
import { continueRestoredWorkerMailSoon } from './rpc/methods/orchestration/messaging/settled-worker-follow-through'
import { PeerMailRelay } from './orchestration/federation/peer-mail/peer-mail-relay'
const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDEBAR_INPUTS_IS_MAIN
? OrcaRuntimeWithSidebarTemporal
@@ -68,6 +69,20 @@ const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDE
// oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- SAFETY: The existing Linear installer supplies the canonical prototype surface.
class OrcaRuntimeService extends OrcaRuntimeSidebarBase {
// Lazy: the database can open, and arm relays, while the runtime is still constructing.
declare private peerMailRelay: PeerMailRelay | undefined
override ensureOrchestrationFederationRelay(runId?: string): void {
super.ensureOrchestrationFederationRelay(runId)
this.peerMailRelay ??= new PeerMailRelay(this, () => this.orchestrationEnvironmentTransport)
this.peerMailRelay.ensure()
}
override stopOrchestrationFederationRelay(): void {
super.stopOrchestrationFederationRelay()
this.peerMailRelay?.stop()
}
/** Sidebar facts are absent unless ORCA_SIDEBAR_INPUTS=main. */
get sidebarFacts() {
return sidebarFactsRuntime(this)
@@ -18,6 +18,7 @@ import { attachRemoteDispatchAttachmentCreate } from './federation/remote-dispat
import { attachRemoteDispatchAttachmentRelease } from './federation/remote-dispatch-attachment-release'
import { attachRemoteDispatchAttachmentStop } from './federation/remote-dispatch-attachment-stop'
import { attachRemoteQuestionStore } from './federation/remote-question-store'
import { attachPeerMailStore } from './federation/peer-mail-store'
import { attachLegacyAskOperation } from './legacy/legacy-ask-operation'
import { attachLegacyCompatibilityCandidates } from './legacy/legacy-compatibility-candidates'
import { attachLegacyCompatibilityPrincipals } from './legacy/legacy-compatibility-principals'
@@ -122,6 +123,7 @@ export function attachOrchestrationDbMethods(ctor: { prototype: object }): void
attachFederationRelayAck(ctor)
attachFederationRelayImport(ctor)
attachRemoteQuestionStore(ctor)
attachPeerMailStore(ctor)
attachFederationRelayItem(ctor)
attachWorkerTerminalResourceStore(ctor)
attachWorkerTerminalTransfer(ctor)
@@ -0,0 +1,182 @@
import type { MessageRow } from '../orchestration-records'
import type { MessageInsert } from '../messages/message-insert'
import { OrchestrationError } from '../../orchestration-error'
import { generateId } from '../generated-id'
import type { OrchestrationDb } from '../orchestration-db'
export type PeerMailConversationRow = {
conversation_id: string
role: 'home' | 'peer'
environment_id: string | null
peer_fingerprint: string
local_party: string | null
local_pane_key: string | null
created_at: string
}
export type PeerMailMessageRow = {
message_id: string
conversation_id: string
sender_label: string
remote_party: string | null
}
/** The conversation this Orca opened for one local agent with one paired server's current pairing; reused for every send. */
export function openHomePeerMailConversation(
this: OrchestrationDb,
params: {
environmentId: string
peerFingerprint: string
localParty: string
localPaneKey: string | null
}
): PeerMailConversationRow {
this.db
.prepare(
`INSERT INTO peer_mail_conversations (
conversation_id, role, environment_id, peer_fingerprint, local_party, local_pane_key
) VALUES (?, 'home', ?, ?, ?, ?)
ON CONFLICT(environment_id, local_party, peer_fingerprint) WHERE role = 'home'
DO UPDATE SET local_pane_key = COALESCE(excluded.local_pane_key, local_pane_key)`
)
.run(
generateId('peerconv'),
params.environmentId,
params.peerFingerprint,
params.localParty,
params.localPaneKey
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly its row shape.
return this.db
.prepare(
`SELECT * FROM peer_mail_conversations
WHERE role = 'home' AND environment_id = ? AND local_party = ? AND peer_fingerprint = ?`
)
.get(params.environmentId, params.localParty, params.peerFingerprint) as PeerMailConversationRow
}
export function getPeerMailConversation(
this: OrchestrationDb,
conversationId: string
): PeerMailConversationRow | undefined {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly its row shape.
return this.db
.prepare('SELECT * FROM peer_mail_conversations WHERE conversation_id = ?')
.get(conversationId) as PeerMailConversationRow | undefined
}
export function listHomePeerMailEnvironments(this: OrchestrationDb): string[] {
const statement = this.db.prepare(
`SELECT DISTINCT environment_id FROM peer_mail_conversations
WHERE role = 'home' AND environment_id IS NOT NULL`
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns.
const rows = statement.all() as { environment_id: string }[]
return rows.map((row) => row.environment_id)
}
export function listPeerConversationIds(this: OrchestrationDb, peerFingerprint: string): string[] {
const statement = this.db.prepare(
`SELECT conversation_id FROM peer_mail_conversations
WHERE role = 'peer' AND peer_fingerprint = ?`
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns.
const rows = statement.all(peerFingerprint) as { conversation_id: string }[]
return rows.map((row) => row.conversation_id)
}
export function getPeerMailMessage(
this: OrchestrationDb,
messageId: string
): PeerMailMessageRow | undefined {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly its row shape.
return this.db.prepare('SELECT * FROM peer_mail_messages WHERE message_id = ?').get(messageId) as
| PeerMailMessageRow
| undefined
}
export function isPeerMailSenderLabel(this: OrchestrationDb, label: string): boolean {
return (
this.db
.prepare('SELECT 1 FROM peer_mail_messages WHERE sender_label = ? LIMIT 1')
.get(label) !== undefined
)
}
/** Stores mail that crossed from a paired Orca once; a replayed id is a duplicate, even after a reset removed its row. */
export function insertPeerMailMessage(
this: OrchestrationDb,
params: {
conversationId: string
/** Only a 'peer' conversation is created here, by the paired Orca that opened it. */
peerFingerprint?: string
remoteParty: string | null
message: MessageInsert & { id: string; from: string }
}
):
| { message: MessageRow; duplicate: false }
| { message: MessageRow | undefined; duplicate: true } {
this.db.exec('SAVEPOINT peer_mail_insert')
try {
if (params.peerFingerprint !== undefined) {
const conversation = this.getPeerMailConversation(params.conversationId)
if (
conversation &&
(conversation.role !== 'peer' || conversation.peer_fingerprint !== params.peerFingerprint)
) {
throw new OrchestrationError(
'request_mismatch',
`Conversation ${params.conversationId} belongs to another server. Nothing was delivered.`,
{ effectsApplied: false }
)
}
if (!conversation) {
this.db
.prepare(
`INSERT INTO peer_mail_conversations (conversation_id, role, peer_fingerprint)
VALUES (?, 'peer', ?)`
)
.run(params.conversationId, params.peerFingerprint)
}
}
if (this.getPeerMailMessage(params.message.id)) {
this.db.exec('RELEASE peer_mail_insert')
return { message: this.getMessageById(params.message.id), duplicate: true }
}
const message = this.insertMessage(params.message)
this.db
.prepare(
`INSERT INTO peer_mail_messages (message_id, conversation_id, sender_label, remote_party)
VALUES (?, ?, ?, ?)`
)
.run(message.id, params.conversationId, params.message.from, params.remoteParty)
this.db.exec('RELEASE peer_mail_insert')
return { message, duplicate: false }
} catch (error) {
this.db.exec('ROLLBACK TO peer_mail_insert')
this.db.exec('RELEASE peer_mail_insert')
throw error
}
}
export type PeerMailStoreMethods = {
openHomePeerMailConversation: typeof openHomePeerMailConversation
getPeerMailConversation: typeof getPeerMailConversation
listHomePeerMailEnvironments: typeof listHomePeerMailEnvironments
listPeerConversationIds: typeof listPeerConversationIds
getPeerMailMessage: typeof getPeerMailMessage
isPeerMailSenderLabel: typeof isPeerMailSenderLabel
insertPeerMailMessage: typeof insertPeerMailMessage
}
export function attachPeerMailStore(ctor: { prototype: object }): void {
Object.assign(ctor.prototype, {
openHomePeerMailConversation,
getPeerMailConversation,
listHomePeerMailEnvironments,
listPeerConversationIds,
getPeerMailMessage,
isPeerMailSenderLabel,
insertPeerMailMessage
})
}
@@ -17,6 +17,7 @@ import type { RemoteDispatchAttachmentCreateMethods } from './federation/remote-
import type { RemoteDispatchAttachmentReleaseMethods } from './federation/remote-dispatch-attachment-release'
import type { RemoteDispatchAttachmentStopMethods } from './federation/remote-dispatch-attachment-stop'
import type { RemoteQuestionStoreMethods } from './federation/remote-question-store'
import type { PeerMailStoreMethods } from './federation/peer-mail-store'
import type { LegacyAskOperationMethods } from './legacy/legacy-ask-operation'
import type { LegacyCompatibilityCandidatesMethods } from './legacy/legacy-compatibility-candidates'
import type { LegacyCompatibilityPrincipalsMethods } from './legacy/legacy-compatibility-principals'
@@ -119,6 +120,7 @@ export type OrchestrationDbMethods = AttemptObservationStoreMethods &
FederationRelayAckMethods &
FederationRelayImportMethods &
RemoteQuestionStoreMethods &
PeerMailStoreMethods &
FederationRelayItemMethods &
StructuredMailSendStoreMethods &
WorkerTerminalResourceStoreMethods &
@@ -58,7 +58,7 @@ export function resetAll(this: OrchestrationDb): void {
}
export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined {
// Messages survive; close threads so orphaned questions cannot masquerade as generic replies.
// Messages survive, and so do replies waiting for a paired Orca to pull them; close threads so orphaned questions cannot masquerade as generic replies.
const watermark = this.runResetTransaction(`
DELETE FROM coordinator_runs;
DELETE FROM decision_gates;
@@ -70,7 +70,7 @@ export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined
DELETE FROM legacy_operation_receipts;
DELETE FROM legacy_compatibility_principals;
DELETE FROM legacy_adoptions;
DELETE FROM federation_relay_items;
DELETE FROM federation_relay_items WHERE kind <> 'peer_mail';
DELETE FROM remote_dispatch_attachments;
DELETE FROM federated_dispatches;
DELETE FROM worker_terminal_archives;
@@ -115,6 +115,34 @@ CREATE TABLE IF NOT EXISTS remote_questions (
CREATE INDEX IF NOT EXISTS idx_remote_questions_dispatch_status
ON remote_questions(dispatch_id, status);
-- Agent mail between paired Orcas. 'home': this Orca opened it for local_party and pulls replies
-- from environment_id over the pairing credential peer_fingerprint, so a re-pair opens a new one. 'peer': the paired Orca peer_fingerprint opened it here; its replies wait in
-- federation_relay_items under dispatch_id = conversation_id until that Orca pulls them.
CREATE TABLE IF NOT EXISTS peer_mail_conversations (
conversation_id TEXT PRIMARY KEY,
role TEXT NOT NULL CHECK(role IN ('home', 'peer')),
environment_id TEXT,
peer_fingerprint TEXT NOT NULL,
local_party TEXT,
local_pane_key TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_peer_mail_home_pairing
ON peer_mail_conversations(environment_id, local_party, peer_fingerprint) WHERE role = 'home';
CREATE INDEX IF NOT EXISTS idx_peer_mail_peer_fingerprint
ON peer_mail_conversations(peer_fingerprint, role);
-- A message that crossed between paired Orcas: its reply goes back over its conversation, to remote_party.
CREATE TABLE IF NOT EXISTS peer_mail_messages (
message_id TEXT PRIMARY KEY,
conversation_id TEXT NOT NULL,
sender_label TEXT NOT NULL,
remote_party TEXT
);
CREATE INDEX IF NOT EXISTS idx_peer_mail_messages_sender ON peer_mail_messages(sender_label);
-- Deletes from tasks, dispatch_contexts and worker tables are recorded in removed_orchestration_work
-- (removed-orchestration-work-store.ts).
CREATE TABLE IF NOT EXISTS tasks (
@@ -0,0 +1,122 @@
import { createHash } from 'node:crypto'
import { ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY } from '../../../../../shared/orchestration/orchestration-runtime-capabilities'
import { z } from 'zod'
import type { OrcaRuntimeService } from '../../../orca-runtime'
import type { PeerMailConversationRow } from '../../db/federation/peer-mail-store'
import { generateId } from '../../db/generated-id'
import { OrchestrationError } from '../../orchestration-error'
import type { OrchestrationWorkerServer } from '../environment-transport'
export type PeerMailRuntime = Pick<
OrcaRuntimeService,
| 'getOrchestrationDb'
| 'resolveOrchestrationWorkerServer'
| 'callOrchestrationWorkerServer'
| 'notifyMessageArrived'
| 'readMachineName'
| 'getTerminalHandleForPaneKey'
>
const NOTHING_SENT = { effectsApplied: false } as const
const RuntimeStatusCapabilities = z.object({ capabilities: z.array(z.string()).optional() })
const DELIVER_TIMEOUT_MS = 15_000
/** "term_9f3c on Jinwoo's Mac": who sent it, and the Orca server it came from. */
export function peerMailSenderLabel(runtime: PeerMailRuntime, sender: string): string {
return `${sender} on ${runtime.readMachineName()}`
}
/** A retried mutation reuses its message id, so the server stores the mail once. */
export function peerMailMessageId(
mutation: { callerFingerprint: string; requestId: string } | undefined
): string {
if (!mutation) {
return generateId('msg')
}
const digest = createHash('sha256')
.update(`${mutation.callerFingerprint}\0${mutation.requestId}`)
.digest('hex')
return `msg_${digest.slice(0, 12)}`
}
/** Refuses before any effect when the server's Orca cannot receive mail or queue its replies. */
export async function requirePeerMailServer(
runtime: PeerMailRuntime,
selector: string
): Promise<OrchestrationWorkerServer> {
const server = runtime.resolveOrchestrationWorkerServer(selector)
const status = RuntimeStatusCapabilities.safeParse(
await runtime.callOrchestrationWorkerServer(
server.environmentId,
'status.get',
undefined,
DELIVER_TIMEOUT_MS,
undefined,
{ expectedEnvironmentPairingRevision: server.pairingRevision }
)
)
if (
!status.success ||
!status.data.capabilities?.includes(ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY)
) {
throw new OrchestrationError(
'server_mail_unsupported',
`Server ${server.name} runs an older Orca that cannot receive agent mail from another server. Update Orca on ${server.name}, then send again. Nothing was sent.`,
{ ...NOTHING_SENT, server: server.name }
)
}
return server
}
/** The pairing credential the server knows this Orca by; a re-pair starts new conversations under it. */
export function peerMailPairing(server: OrchestrationWorkerServer): string {
return server.homePeerFingerprint ?? server.peerFingerprint
}
/** Hands one message to the paired server; it stores it once and delivers it with its own mail code. */
export async function deliverPeerMail(
runtime: PeerMailRuntime,
server: OrchestrationWorkerServer,
conversation: PeerMailConversationRow,
message: {
id: string
to: string
senderLabel: string
subject: string
body?: string
type?: 'status' | 'handoff'
priority?: 'normal' | 'high' | 'urgent'
threadId?: string
}
): Promise<void> {
await runtime.callOrchestrationWorkerServer(
server.environmentId,
'orchestration.peerMailDeliver',
{
conversationId: conversation.conversation_id,
messageId: message.id,
to: message.to,
senderLabel: message.senderLabel,
subject: message.subject,
...(message.body !== undefined ? { body: message.body } : {}),
...(message.type ? { type: message.type } : {}),
...(message.priority ? { priority: message.priority } : {}),
...(message.threadId ? { threadId: message.threadId } : {})
},
DELIVER_TIMEOUT_MS,
undefined,
{ expectedEnvironmentPairingRevision: server.pairingRevision }
)
}
/** Where a pulled reply lands: the opener's current mailbox, following a terminal's remint by pane. */
export function peerMailLocalRecipient(
runtime: PeerMailRuntime,
conversation: PeerMailConversationRow
): string {
const party = conversation.local_party ?? ''
const reminted = conversation.local_pane_key
? runtime.getTerminalHandleForPaneKey(conversation.local_pane_key)
: null
return reminted ?? party
}
@@ -0,0 +1,183 @@
import { z } from 'zod'
import type { OrcaRuntimeService } from '../../../orca-runtime'
import { PeerMailRelayPayload } from '../../../../../shared/rpc-contract/orchestration-peer-mail-params'
import { resolveBareOrchestrationRecipient } from '../../../rpc/methods/orchestration/messaging/recipient-routing'
import type { OrchestrationDb } from '../../db/orchestration-db'
import type { MessageRow } from '../../db/orchestration-records'
import { federationRelayRetryDelayMs } from '../relay/federation-relay-scheduler'
import type { OrchestrationEnvironmentTransport } from '../environment-transport'
import { peerMailLocalRecipient } from './peer-mail-delivery'
// Under the relay edge's idle cutoff, so an idle pull ends by itself instead of being dropped.
const PULL_WAIT_MS = 20_000
const PULL_TIMEOUT_MS = PULL_WAIT_MS + 15_000
const PulledPeerMail = z.object({
items: z.array(
z.object({
conversationId: z.string(),
sequence: z.number().int().positive(),
messageId: z.string(),
payload: z.string()
})
)
})
type Loop = { db: OrchestrationDb; stopped: boolean }
/** One pull loop per paired server this Orca opened conversations with. The server never dials
* back: each pull waits there for a reply, stores it as local mail, then acknowledges it. */
export class PeerMailRelay {
private readonly loops = new Map<string, Loop>()
constructor(
private readonly runtime: OrcaRuntimeService,
private readonly transport: () => OrchestrationEnvironmentTransport | null
) {}
ensure(): void {
if (!this.transport()) {
return
}
const db = this.runtime.getOrchestrationDb()
for (const environmentId of db.listHomePeerMailEnvironments()) {
const current = this.loops.get(environmentId)
if (current && !current.stopped && current.db === db) {
continue
}
const loop: Loop = { db, stopped: false }
this.loops.set(environmentId, loop)
void this.run(environmentId, loop)
}
}
stop(): void {
for (const loop of this.loops.values()) {
loop.stopped = true
}
this.loops.clear()
}
private isCurrent(environmentId: string, loop: Loop): boolean {
return (
!loop.stopped &&
this.loops.get(environmentId) === loop &&
this.runtime.getOrchestrationDb() === loop.db
)
}
private async run(environmentId: string, loop: Loop): Promise<void> {
let failures = 0
while (this.isCurrent(environmentId, loop)) {
try {
await this.pullOnce(environmentId, loop)
failures = 0
} catch {
if (this.isEnvironmentRemoved(environmentId)) {
// A removed server cannot answer; the next ensure re-arms it if it is added back.
break
}
failures += 1
await new Promise<void>((resolve) => {
setTimeout(resolve, federationRelayRetryDelayMs(failures)).unref?.()
})
}
}
if (this.loops.get(environmentId) === loop) {
this.loops.delete(environmentId)
}
}
/** A store read error keeps the loop retrying rather than ending it. */
private isEnvironmentRemoved(environmentId: string): boolean {
try {
return this.transport()?.hasEnvironment?.(environmentId) === false
} catch {
return false
}
}
private async pullOnce(environmentId: string, loop: Loop): Promise<void> {
const response = await this.runtime.callOrchestrationWorkerServer(
environmentId,
'orchestration.peerMailPull',
{ waitMs: PULL_WAIT_MS },
PULL_TIMEOUT_MS
)
if (!this.isCurrent(environmentId, loop)) {
return
}
const { items } = PulledPeerMail.parse(response)
if (items.length === 0) {
return
}
const through = new Map<string, number>()
for (const item of items) {
const stored = this.importReply(loop.db, environmentId, item)
// Wake before the ack: a replay after a failed ack finds the row stored and stays quiet.
if (stored) {
this.runtime.notifyMessageArrived(stored.to_handle, stored.type)
}
through.set(
item.conversationId,
Math.max(through.get(item.conversationId) ?? 0, item.sequence)
)
}
await this.runtime.callOrchestrationWorkerServer(
environmentId,
'orchestration.peerMailAck',
{
acknowledgments: [...through].map(([conversationId, throughSequence]) => ({
conversationId,
throughSequence
}))
},
15_000
)
}
/** Stores a pulled reply once; a replay after a crash before the ack finds the stored row. */
private importReply(
db: OrchestrationDb,
environmentId: string,
item: z.infer<typeof PulledPeerMail>['items'][number]
): MessageRow | undefined {
const conversation = db.getPeerMailConversation(item.conversationId)
const payload = PeerMailRelayPayload.safeParse(safeJson(item.payload))
if (
conversation?.role !== 'home' ||
conversation.environment_id !== environmentId ||
!payload.success
) {
// Nothing here can read it; acknowledging keeps the server's queue moving.
console.warn(
`[orchestration] Dropped unreadable reply ${item.messageId} from ${environmentId}`
)
return undefined
}
const handle = peerMailLocalRecipient(this.runtime, conversation)
const recipient = resolveBareOrchestrationRecipient({ runtime: this.runtime, db, handle })
const stored = db.insertPeerMailMessage({
conversationId: conversation.conversation_id,
remoteParty: payload.data.fromAddress,
message: {
id: item.messageId,
from: payload.data.senderLabel,
to: recipient.ok ? recipient.to : handle,
subject: payload.data.subject,
body: payload.data.body,
threadId: payload.data.threadId ?? undefined,
runId: recipient.ok ? recipient.runId : undefined
}
})
return stored.duplicate ? undefined : stored.message
}
}
function safeJson(value: string): unknown {
try {
return JSON.parse(value)
} catch {
return null
}
}
@@ -0,0 +1,32 @@
import type { OrchestrationDb } from '../../db/orchestration-db'
const waiters = new WeakMap<OrchestrationDb, Set<() => void>>()
/** Wakes every pull waiting on this store; each re-reads its own conversations. */
export function notifyPeerMailQueued(db: OrchestrationDb): void {
for (const wake of waiters.get(db) ?? []) {
wake()
}
}
/** Resolves when a reply is queued, the wait ends, or the caller goes away. */
export function waitForPeerMail(
db: OrchestrationDb,
timeoutMs: number,
signal?: AbortSignal
): Promise<void> {
return new Promise((resolve) => {
const set = waiters.get(db) ?? new Set<() => void>()
waiters.set(db, set)
const done = (): void => {
clearTimeout(timer)
set.delete(done)
signal?.removeEventListener('abort', done)
resolve()
}
const timer = setTimeout(done, timeoutMs)
timer.unref?.()
set.add(done)
signal?.addEventListener('abort', done, { once: true })
})
}
@@ -43,9 +43,11 @@ export function agentMessageSender(
): AgentMessageSender {
const party = senderParty(address, db)
const snapshot = snapshotSender(senderSnapshot, party, reportedDispatchId)
// Mail from another server is named by its label: "term_9f3c on Jinwoo's Mac".
const peerLabel = !snapshot.name && db?.isPeerMailSenderLabel(address) ? address : null
return {
party,
name: agentMessageSenderName(snapshot.name),
name: agentMessageSenderName(snapshot.name ?? peerLabel),
...(snapshot.agent ? { agent: snapshot.agent } : {})
}
}
+2 -9
View File
@@ -15,6 +15,7 @@ import {
import type { RpcEnvelopeMeta, RpcFailure, RpcSuccess } from './core'
import { CONNECTOR_REPLY_ERROR_CODES } from '../../../shared/rpc-contract/connector-params'
import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES } from '../../../shared/orchestration/orchestration-session-caller-codes'
import { ORCHESTRATION_FEDERATION_ERROR_CODES } from '../../../shared/orchestration/orchestration-federation-error-codes'
import { computerUseErrorRecoveryData } from '../../../shared/computer-use-error-recovery'
import { COMPUTER_ERROR_CODES } from '../../../shared/computer-use-runtime-types'
import { TerminalSplitOutcomeError } from '../../../shared/workspace-layout/terminal-split-outcome'
@@ -144,15 +145,7 @@ const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet<string> = new Set([
'cursor_dispatch_mismatch',
'source_changed',
'transcript_required',
'server_required',
'worktree_not_found_on_server',
'resource_server_mismatch',
'peer_changed',
'remote_runtime_unavailable',
'runtime_timeout',
'invalid_runtime_response',
'capability_unsupported',
'relay_quota_exceeded',
...ORCHESTRATION_FEDERATION_ERROR_CODES,
'dispatch_capability_invalid',
'agent_unconfigured',
'worker_prompt_too_large',
@@ -69,10 +69,19 @@ export const ORCHESTRATION_CALLER_METHODS = [
permission: 'workspace',
params: null,
// Dispatch already admitted the environment's session; do not resolve another caller from params.
handler: (_params, { orchestrationCaller }): OrchestrationCallerShowResult => ({
handler: (
_params,
{ orchestrationCaller, orchestrationCompatibilityEvidence, runtime }
): OrchestrationCallerShowResult => ({
caller: orchestrationCaller
? { orcaSessionId: formatOrcaSessionAddress(orchestrationCaller.orcaSessionId), live: true }
: null
: null,
// An Orca-launched agent's own pane and launch secret prove it is one; no hook needs to have fired.
terminal:
!orchestrationCaller &&
runtime.verifyOrchestrationCompatibilityCaller(orchestrationCompatibilityEvidence, {
currentRuntimeLaunchSufficient: true
}) !== null
})
}),
defineMethod({
@@ -1,9 +1,11 @@
import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from './federation-control'
import { ORCHESTRATION_FEDERATION_RELAY_METHODS } from './federation-relay'
import { ORCHESTRATION_FEDERATION_ATTACH_METHODS } from './federation'
import { ORCHESTRATION_PEER_MAIL_METHODS } from './peer-mail-methods'
export const ORCHESTRATION_FEDERATION_METHODS = [
...ORCHESTRATION_FEDERATION_ATTACH_METHODS,
...ORCHESTRATION_FEDERATION_RELAY_METHODS,
...ORCHESTRATION_FEDERATION_CONTROL_METHODS
...ORCHESTRATION_FEDERATION_CONTROL_METHODS,
...ORCHESTRATION_PEER_MAIL_METHODS
]
@@ -0,0 +1,181 @@
import { defineMethod, type RpcContext } from '../../../core'
import { OrchestrationError } from '../../../../orchestration/orchestration-error'
import { isGeneratedId } from '../../../../orchestration/db/generated-id'
import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db'
import type { FederationRelayItemRow } from '../../../../orchestration/db/orchestration-records'
import { resolveBareOrchestrationRecipient } from '../messaging/recipient-routing'
import { mayNameSession } from '../messaging/session-recipient'
import { waitForPeerMail } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters'
import {
PeerMailAckParams,
PeerMailDeliverParams,
PeerMailPullParams
} from '../../../../../../shared/rpc-contract/orchestration-peer-mail-params'
const NOTHING_DELIVERED = { effectsApplied: false } as const
const MAX_PULL_WAIT_MS = 25_000
const PULL_PAGE_SIZE = 50
/** Mail between servers comes only from a paired computer's Orca, never a phone or this Orca's own clients. */
function requireRuntimePairing(
ctx: Pick<RpcContext, 'clientKind' | 'pairedDeviceId' | 'authenticatedCallerFingerprint'>
): string {
if (
ctx.clientKind !== 'runtime' ||
ctx.pairedDeviceId === undefined ||
!ctx.authenticatedCallerFingerprint
) {
throw new OrchestrationError(
'mail_requires_server_pairing',
'Agent mail between Orca servers comes only from a paired computer. Nothing was delivered.',
NOTHING_DELIVERED
)
}
return ctx.authenticatedCallerFingerprint
}
function pendingReplies(db: OrchestrationDb, peerFingerprint: string): FederationRelayItemRow[] {
const items: FederationRelayItemRow[] = []
for (const conversationId of db.listPeerConversationIds(peerFingerprint)) {
if (items.length >= PULL_PAGE_SIZE) {
break
}
items.push(
...db.listPendingFederationRelay(conversationId, 'to_home', PULL_PAGE_SIZE - items.length)
)
}
return items
}
export const ORCHESTRATION_PEER_MAIL_METHODS = [
defineMethod({
name: 'orchestration.peerMailDeliver',
permission: 'workspace',
params: PeerMailDeliverParams,
handler: async (params, ctx) => {
const peerFingerprint = requireRuntimePairing(ctx)
const { runtime } = ctx
const db = runtime.getOrchestrationDb()
if (!isGeneratedId(params.messageId, 'msg')) {
throw new OrchestrationError('invalid_argument', 'Mail between servers needs a message ID.')
}
// Replies wait in the relay keyed by conversation; any other id could name another Orca's dispatch there.
if (!isGeneratedId(params.conversationId, 'peerconv')) {
throw new OrchestrationError(
'invalid_argument',
'Mail between servers needs a conversation ID.',
NOTHING_DELIVERED
)
}
const to = params.to
if (/^(run|dispatch|task):/.test(to) || to.startsWith('@')) {
throw new OrchestrationError(
'invalid_argument',
`--on sends to one terminal or chat agent on this server; ${to} is a mailbox. Nothing was delivered.`,
NOTHING_DELIVERED
)
}
// A retry after a lost answer is acknowledged even if the recipient has since gone.
const delivered = db.getPeerMailMessage(params.messageId)
if (delivered) {
const conversation = db.getPeerMailConversation(delivered.conversation_id)
if (
delivered.conversation_id !== params.conversationId ||
conversation?.peer_fingerprint !== peerFingerprint
) {
throw new OrchestrationError(
'request_mismatch',
`Message ${params.messageId} already belongs to another conversation. Nothing was delivered.`,
NOTHING_DELIVERED
)
}
return { message: { id: params.messageId, to } }
}
if (mayNameSession(to)) {
// Recipient routing reads the session record store, which the host opens lazily.
await runtime.ensureStructuredAgentSessionHost().catch(() => undefined)
}
const recipient = resolveBareOrchestrationRecipient({ runtime, db, handle: to })
if (!recipient.ok) {
throw new OrchestrationError(
recipient.code,
`${recipient.message} Nothing was delivered.`,
NOTHING_DELIVERED
)
}
const paneKey = runtime.getLiveTerminalPaneKey(recipient.to)
if (paneKey && db.findActiveRemoteAttachmentForPane(paneKey)) {
// Its mailbox is its Dispatch, which only its Run home writes to.
throw new OrchestrationError(
'invalid_argument',
`${to} is a worker for another Orca's Run; message it through that Run's coordinator. Nothing was delivered.`,
NOTHING_DELIVERED
)
}
const stored = db.insertPeerMailMessage({
conversationId: params.conversationId,
peerFingerprint,
remoteParty: null,
message: {
id: params.messageId,
from: params.senderLabel,
to: recipient.to,
subject: params.subject,
body: params.body,
type: params.type,
priority: params.priority,
threadId: params.threadId,
runId: recipient.runId
}
})
if (!stored.duplicate) {
runtime.notifyMessageArrived(stored.message.to_handle, stored.message.type)
}
return { message: { id: params.messageId, to } }
}
}),
defineMethod({
name: 'orchestration.peerMailPull',
permission: 'workspace',
params: PeerMailPullParams,
handler: async (params, ctx) => {
const peerFingerprint = requireRuntimePairing(ctx)
const db = ctx.runtime.getOrchestrationDb()
let items = pendingReplies(db, peerFingerprint)
const waitMs = Math.min(Math.max(params.waitMs ?? 0, 0), MAX_PULL_WAIT_MS)
if (items.length === 0 && waitMs > 0) {
await waitForPeerMail(db, waitMs, ctx.signal)
items = pendingReplies(ctx.runtime.getOrchestrationDb(), peerFingerprint)
}
return {
items: items.map((item) => ({
conversationId: item.dispatch_id,
sequence: item.sequence,
messageId: item.message_id,
payload: item.payload
}))
}
}
}),
defineMethod({
name: 'orchestration.peerMailAck',
permission: 'workspace',
params: PeerMailAckParams,
handler: (params, ctx) => {
const peerFingerprint = requireRuntimePairing(ctx)
const db = ctx.runtime.getOrchestrationDb()
for (const ack of params.acknowledgments) {
const conversation = db.getPeerMailConversation(ack.conversationId)
if (conversation?.role !== 'peer' || conversation.peer_fingerprint !== peerFingerprint) {
continue
}
db.acknowledgeFederationRelay({
dispatchId: ack.conversationId,
direction: 'to_home',
throughSequence: ack.throughSequence
})
}
return { acknowledged: params.acknowledgments.length }
}
})
]
@@ -0,0 +1,439 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
ORCHESTRATION_CONTRACT_VERSION,
ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY
} from '../../../../../../shared/orchestration/orchestration-runtime-capabilities'
import type { RuntimeRpcResponse } from '../../../../../../shared/runtime-rpc-envelope'
import { OrcaRuntimeService } from '../../../../orca-runtime'
import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db'
import type { OrchestrationEnvironmentTransport } from '../../../../orchestration/federation/environment-transport'
import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity'
import { RpcDispatcher } from '../../../dispatcher'
import type { RpcContext } from '../../../core'
import { ORCHESTRATION_METHODS } from '../orchestration'
import { ORCHESTRATION_REPLY_METHOD } from '../messaging/reply-method'
import { notifyPeerMailQueued } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters'
// Retries run at once so a recovering pull loop is observable without waiting out its backoff.
vi.mock(
'../../../../orchestration/federation/relay/federation-relay-scheduler',
async (original) => ({
...(await original<object>()),
federationRelayRetryDelayMs: () => 0
})
)
const A_PANE = 'tab_a:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
const B_PANE = 'tab_b:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
const CHAT_ON_A = 'orca_session_id:11111111-1111-4111-8111-111111111111'
const CHAT_ON_B = 'orca_session_id:22222222-2222-4222-8222-222222222222'
type Side = { db: OrchestrationDb; runtime: OrcaRuntimeService; dispatcher: RpcDispatcher }
describe('agent mail between paired Orca servers', () => {
let dir: string
let a: Side
let b: Side
let bCapabilities: (capabilities: string[]) => string[]
let bClientKind: 'runtime' | 'mobile'
let aCredential: string
let hasEnvironment: () => boolean
function openSide(name: string, machine: string, transport?: OrchestrationEnvironmentTransport) {
const db = new OrchestrationDb(join(dir, `${name}.db`))
const runtime = new OrcaRuntimeService(null, undefined, {
orchestrationEnvironmentTransport: transport
})
vi.spyOn(runtime, 'readMachineName').mockReturnValue(machine)
vi.spyOn(runtime, 'getTerminalHandleForPaneKey').mockReturnValue(null)
const panes: Record<string, string> = { term_a: A_PANE, term_b: B_PANE }
vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation(
(handle) => panes[handle] ?? null
)
vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => panes[handle] ?? null)
runtime.setOrchestrationDb(db)
return {
db,
runtime,
dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS })
}
}
const transport: OrchestrationEnvironmentTransport = {
resolve: () => ({
environmentId: 'env_b',
name: 'devB',
peerFingerprint: 'fingerprint_b',
homePeerFingerprint: aCredential
}),
hasEnvironment: () => hasEnvironment(),
call: async (_selector, method, params) => {
if (method === 'status.get') {
const status = b.runtime.getStatus()
return {
id: 'status',
ok: true,
result: { ...status, capabilities: bCapabilities(status.capabilities ?? []) },
_meta: { runtimeId: b.runtime.getRuntimeId() }
}
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads.
return (await b.dispatcher.dispatch(
{
id: `from_a_${method}`,
authToken: 'a-device-token',
method,
params,
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION
},
{
authenticatedCallerFingerprint: aCredential,
pairedDeviceId: 'device_a',
clientKind: bClientKind
}
)) as RuntimeRpcResponse<unknown>
}
}
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'orca-peer-mail-'))
bCapabilities = (capabilities) => capabilities
bClientKind = 'runtime'
aCredential = 'fingerprint_a'
hasEnvironment = () => true
b = openSide('b', 'Build Box')
a = openSide('a', "Jinwoo's Mac", transport)
})
afterEach(() => {
a.runtime.stopOrchestrationFederationRelay()
b.runtime.stopOrchestrationFederationRelay()
a.db.close()
b.db.close()
rmSync(dir, { recursive: true, force: true })
})
let requestCount = 0
function mutation(side: Side, method: string, params: Record<string, unknown>) {
requestCount += 1
return side.dispatcher.dispatch({
id: `${method}_${requestCount}`,
authToken: 'local',
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
orchestrationRequestId: `request_${requestCount}`,
method,
params
})
}
function chatReply(side: Side, caller: string, params: { id: string; body: string }) {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads.
const orchestrationCaller = {
address: caller,
terminalHandle: null,
orcaSessionId: caller.slice('orca_session_id:'.length),
paneKey: null
} as unknown as OrchestrationSessionCaller
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads.
return ORCHESTRATION_REPLY_METHOD.handler(params, {
runtime: side.runtime,
orchestrationCaller
} as RpcContext)
}
function mailFor(side: Side, handle: string) {
return side.db.getUnreadMessages(handle)
}
it('carries a terminal agent mail to the paired server and its flagless reply back', async () => {
const sent = await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Check the build',
body: 'Is main green?'
})
expect(sent).toMatchObject({ ok: true, result: { server: 'devB', message: { to: 'term_b' } } })
const [onB] = mailFor(b, 'term_b')
expect(onB).toMatchObject({ from_handle: "term_a on Jinwoo's Mac", subject: 'Check the build' })
const replied = await mutation(b, 'orchestration.reply', {
id: onB!.id,
body: 'Green.',
from: 'term_b'
})
expect(replied).toMatchObject({
ok: true,
result: { message: { subject: 'Re: Check the build' } }
})
a.runtime.ensureOrchestrationFederationRelay()
await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1))
const [back] = mailFor(a, 'term_a')
expect(back).toMatchObject({
from_handle: 'term_b on Build Box',
subject: 'Re: Check the build',
body: 'Green.',
thread_id: onB!.id
})
await expect(
mutation(a, 'orchestration.reply', { id: back!.id, body: 'x', from: 'term_a', on: 'devB' })
).resolves.toMatchObject({ ok: false, error: { code: 'request_mismatch' } })
// The opener can keep answering, and the reply reaches the same agent again.
await expect(
mutation(a, 'orchestration.reply', { id: back!.id, body: 'Thanks.', from: 'term_a' })
).resolves.toMatchObject({ ok: true })
expect(mailFor(b, 'term_b').map((message) => message.body)).toEqual(['Thanks.'])
})
it('returns a chat agent reply to the chat on the opening server', async () => {
const send = ORCHESTRATION_METHODS.find((method) => method.name === 'orchestration.send')!
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads.
await send.handler({ from: CHAT_ON_A, on: 'devB', to: 'term_b', subject: 'Plan?' }, {
runtime: a.runtime,
orchestrationCaller: {
address: CHAT_ON_A,
terminalHandle: null,
orcaSessionId: CHAT_ON_A.slice(16),
paneKey: null
}
} as unknown as RpcContext)
const [onB] = mailFor(b, 'term_b')
expect(onB!.from_handle).toBe(`${CHAT_ON_A} on Jinwoo's Mac`)
await chatReply(b, CHAT_ON_B, { id: onB!.id, body: 'Plan attached.' })
a.runtime.ensureOrchestrationFederationRelay()
await vi.waitFor(() => expect(mailFor(a, CHAT_ON_A)).toHaveLength(1))
expect(mailFor(a, CHAT_ON_A)[0]).toMatchObject({
from_handle: `${CHAT_ON_B} on Build Box`,
body: 'Plan attached.'
})
expect(a.db.getPeerMailMessage(mailFor(a, CHAT_ON_A)[0]!.id)?.remote_party).toBe(CHAT_ON_B)
})
it('delivers a reply queued before both servers restart exactly once', async () => {
await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Long job'
})
const [onB] = mailFor(b, 'term_b')
await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Done.', from: 'term_b' })
a.runtime.stopOrchestrationFederationRelay()
a.db.close()
b.db.close()
b = openSide('b', 'Build Box')
a = openSide('a', "Jinwoo's Mac", transport)
a.runtime.ensureOrchestrationFederationRelay()
await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1))
const [conversationId] = b.db.listPeerConversationIds('fingerprint_a')
expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([])
})
it('refuses an older server before sending anything', async () => {
bCapabilities = (capabilities) =>
capabilities.filter((capability) => capability !== ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY)
const sent = await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Hello'
})
expect(sent).toMatchObject({
ok: false,
error: { code: 'server_mail_unsupported', data: { effectsApplied: false } }
})
expect(b.db.getInbox(10)).toEqual([])
})
it('takes mail between servers only from a paired computer, not a phone', async () => {
bClientKind = 'mobile'
const sent = await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Hello'
})
expect(sent).toMatchObject({
ok: false,
error: { code: 'mail_requires_server_pairing' }
})
expect(b.db.getInbox(10)).toEqual([])
})
it('acknowledges a retried delivery after its recipient is gone, storing it once', async () => {
const deliver = {
conversationId: 'peerconv_aaaaaaaaaaaa',
messageId: 'msg_aaaaaaaaaaaa',
to: 'term_b',
senderLabel: "term_a on Jinwoo's Mac",
subject: 'Once'
}
const first = await transport.call('devB', 'orchestration.peerMailDeliver', deliver)
vi.mocked(b.runtime.getLiveTerminalPaneKey).mockReturnValue(null)
const retried = await transport.call('devB', 'orchestration.peerMailDeliver', deliver)
expect(first).toMatchObject({ ok: true })
expect(retried).toMatchObject({ ok: true, result: { message: { id: 'msg_aaaaaaaaaaaa' } } })
expect(b.db.getInbox(10).filter((message) => message.subject === 'Once')).toHaveLength(1)
})
it('refuses payload fields before sending anything', async () => {
const sent = await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Report',
payload: '{"taskId":"task_1"}'
})
expect(sent).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(b.db.getInbox(10)).toEqual([])
})
it('refuses mail to a worker another Orca coordinates', async () => {
vi.spyOn(b.db, 'findActiveRemoteAttachmentForPane').mockImplementation((paneKey) =>
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads.
paneKey === B_PANE ? ({ dispatch_id: 'ctx_remote' } as never) : undefined
)
const sent = await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Side mail'
})
expect(sent).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(b.db.getInbox(10)).toEqual([])
})
it('refuses a conversation ID that is not a peer conversation', async () => {
const delivered = await transport.call('devB', 'orchestration.peerMailDeliver', {
conversationId: 'ctx_aaaaaaaaaaaa',
messageId: 'msg_aaaaaaaaaaaa',
to: 'term_b',
senderLabel: "term_a on Jinwoo's Mac",
subject: 'Into a dispatch'
})
expect(delivered).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
expect(b.db.getInbox(10)).toEqual([])
})
it('keeps conversing with a server after it is re-paired', async () => {
await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'First'
})
const [first] = mailFor(b, 'term_b')
await mutation(b, 'orchestration.reply', { id: first!.id, body: 'One.', from: 'term_b' })
a.runtime.ensureOrchestrationFederationRelay()
await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1))
const [answer] = mailFor(a, 'term_a')
b.db.markAsRead([first!.id])
aCredential = 'fingerprint_a_repaired'
await expect(
mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Second'
})
).resolves.toMatchObject({ ok: true })
await expect(
mutation(a, 'orchestration.reply', { id: answer!.id, body: 'Thanks.', from: 'term_a' })
).resolves.toMatchObject({ ok: true })
expect(mailFor(b, 'term_b').map((message) => message.subject)).toEqual(['Second', 'Re: First'])
})
it('acknowledges a reply replayed after this Orca reset its mail', async () => {
await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Ask'
})
const [onB] = mailFor(b, 'term_b')
await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Answer.', from: 'term_b' })
a.runtime.ensureOrchestrationFederationRelay()
await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1))
const [conversationId] = b.db.listPeerConversationIds('fingerprint_a')
await vi.waitFor(() =>
expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([])
)
a.db.resetMessages()
// The ack was lost: the server serves the stored reply again.
b.db['db'].prepare('UPDATE federation_relay_items SET acked_at = NULL').run()
notifyPeerMailQueued(b.db)
await vi.waitFor(() =>
expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([])
)
expect(mailFor(a, 'term_a')).toEqual([])
})
it('keeps a queued reply when the server resets its tasks', async () => {
await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Ask'
})
a.runtime.stopOrchestrationFederationRelay()
const [onB] = mailFor(b, 'term_b')
await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Kept.', from: 'term_b' })
b.db.resetTasks()
a.runtime.ensureOrchestrationFederationRelay()
await vi.waitFor(() =>
expect(mailFor(a, 'term_a').map((message) => message.body)).toEqual(['Kept.'])
)
})
it('keeps pulling after a failed pull when the server list cannot be read', async () => {
await mutation(a, 'orchestration.send', {
from: 'term_a',
on: 'devB',
to: 'term_b',
subject: 'Ask'
})
a.runtime.stopOrchestrationFederationRelay()
const [onB] = mailFor(b, 'term_b')
await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Later.', from: 'term_b' })
const call = vi.spyOn(transport, 'call')
call.mockRejectedValueOnce(new Error('offline'))
hasEnvironment = () => {
hasEnvironment = () => true
throw new Error('registry unreadable')
}
a.runtime.ensureOrchestrationFederationRelay()
await vi.waitFor(() =>
expect(mailFor(a, 'term_a').map((message) => message.body)).toEqual(['Later.'])
)
call.mockRestore()
})
})
@@ -0,0 +1,106 @@
import type { OrcaRuntimeService } from '../../../../orca-runtime'
import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity'
import type { PeerMailMessageRow } from '../../../../orchestration/db/federation/peer-mail-store'
import type { MessageRow } from '../../../../orchestration/db/orchestration-records'
import { OrchestrationError } from '../../../../orchestration/orchestration-error'
import {
deliverPeerMail,
peerMailMessageId,
peerMailPairing,
peerMailSenderLabel,
requirePeerMailServer
} from '../../../../orchestration/federation/peer-mail/peer-mail-delivery'
import { notifyPeerMailQueued } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters'
import { recordReceiptBeforeNudge } from './mutation-replay-nudge'
const NOTHING_SENT = { effectsApplied: false } as const
/** A reply to mail that came from another Orca goes back over that mail's conversation. */
export async function replyOverPeerMail(args: {
runtime: OrcaRuntimeService
original: MessageRow
route: PeerMailMessageRow
params: { body: string; from?: string; on?: string }
orchestrationCaller: OrchestrationSessionCaller | undefined
orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined
recordMutationReceipt: ((receipt: unknown) => void) | undefined
}): Promise<unknown> {
const { runtime, original, route, params } = args
const db = runtime.getOrchestrationDb()
const conversation = db.getPeerMailConversation(route.conversation_id)
if (!conversation) {
throw new OrchestrationError(
'request_mismatch',
`The conversation ${original.id} came on is gone from this Orca. No reply was sent.`,
NOTHING_SENT
)
}
const replier = args.orchestrationCaller?.address ?? params.from ?? original.to_handle
const id = peerMailMessageId(args.orchestrationMutation)
const subject = original.subject.startsWith('Re: ') ? original.subject : `Re: ${original.subject}`
const threadId = original.thread_id ?? original.id
const senderLabel = peerMailSenderLabel(runtime, replier)
if (params.on !== undefined) {
throw new OrchestrationError(
'request_mismatch',
`${original.id} came from ${original.from_handle}; its reply goes back there by itself. Drop --on. No reply was sent.`,
NOTHING_SENT
)
}
if (conversation.role === 'peer') {
db.enqueueFederationRelay({
dispatchId: conversation.conversation_id,
direction: 'to_home',
kind: 'peer_mail',
messageId: id,
payload: JSON.stringify({
senderLabel,
fromAddress: replier,
subject,
body: params.body,
threadId
})
})
db.markAsRead([original.id])
return recordReceiptBeforeNudge(
args.recordMutationReceipt,
{ message: { id, subject }, to: original.from_handle },
() => notifyPeerMailQueued(db),
{ kind: 'messages', targets: [] }
)
}
const environmentId = conversation.environment_id ?? ''
if (!route.remote_party) {
throw new OrchestrationError(
'request_mismatch',
`${original.id} does not say who sent it. No reply was sent.`,
NOTHING_SENT
)
}
const server = await requirePeerMailServer(runtime, environmentId)
// After a re-pair the server no longer knows the old conversation; continue it under the new pairing.
const current = db.openHomePeerMailConversation({
environmentId,
peerFingerprint: peerMailPairing(server),
localParty: conversation.local_party ?? '',
localPaneKey: conversation.local_pane_key
})
await deliverPeerMail(runtime, server, current, {
id,
to: route.remote_party,
senderLabel,
subject,
body: params.body,
threadId
})
db.markAsRead([original.id])
return recordReceiptBeforeNudge(
args.recordMutationReceipt,
{ message: { id, subject }, to: original.from_handle, server: server.name },
() => runtime.ensureOrchestrationFederationRelay(),
{ kind: 'federation' }
)
}
@@ -0,0 +1,133 @@
import type { z } from 'zod'
import type { OrcaRuntimeService } from '../../../../orca-runtime'
import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity'
import type { OrchestrationCompatibilityCallerAuthority } from '../../../../orchestration/terminal-authority/orchestration-compatibility-authority'
import { OrchestrationError } from '../../../../orchestration/orchestration-error'
import {
deliverPeerMail,
peerMailMessageId,
peerMailPairing,
peerMailSenderLabel,
requirePeerMailServer
} from '../../../../orchestration/federation/peer-mail/peer-mail-delivery'
import type { RpcContext } from '../../../core'
import { recordReceiptBeforeNudge } from './mutation-replay-nudge'
import type { SendParams } from './send-params'
import type { ORCHESTRATION_SEND_METHODS } from './send-methods'
const NOTHING_SENT = { effectsApplied: false } as const
/** The agent on this Orca that mail sent elsewhere answers to: a chat by its session, a terminal by its live pane. */
export function peerMailLocalCaller(args: {
runtime: OrcaRuntimeService
from: string | undefined
orchestrationCaller: OrchestrationSessionCaller | undefined
attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined
}): { address: string; paneKey: string | null } {
if (args.orchestrationCaller) {
return { address: args.orchestrationCaller.address, paneKey: null }
}
const paneKey =
args.from === undefined
? null
: (args.attestedCaller?.paneKey ?? args.runtime.getLiveTerminalPaneKey(args.from))
if (!args.from || !paneKey) {
throw new OrchestrationError(
'invalid_argument',
'--on needs a terminal or chat agent on this Orca to receive the replies. Run it from that agent. Nothing was sent.',
NOTHING_SENT
)
}
if (args.runtime.getOrchestrationDb().findActiveRemoteAttachmentForPane(paneKey)) {
throw new OrchestrationError(
'invalid_argument',
"This terminal is a worker for another Orca's Run; its mail goes to that Run's coordinator, not to other servers. Nothing was sent.",
NOTHING_SENT
)
}
return { address: args.from, paneKey }
}
/** `send --on <server>`: this Orca carries the mail and keeps the conversation the replies come back on. */
export async function sendPeerMail(args: {
params: z.infer<typeof SendParams> & { on: string }
runtime: OrcaRuntimeService
orchestrationCaller: OrchestrationSessionCaller | undefined
attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined
orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined
recordMutationReceipt: ((receipt: unknown) => void) | undefined
}): Promise<unknown> {
const { params, runtime } = args
const to = params.to
if (!to || /^(run|dispatch|task):/.test(to) || to.startsWith('@')) {
throw new OrchestrationError(
'invalid_argument',
`--on sends to one terminal or chat agent on that server: --to term_… or --to orca_session_id:…${to ? `, not ${to}` : ''}. Nothing was sent.`,
NOTHING_SENT
)
}
const type = params.type ?? 'status'
if (type !== 'status' && type !== 'handoff') {
throw new OrchestrationError(
'invalid_argument',
`--on carries --type status or handoff, not ${type}. Nothing was sent.`,
NOTHING_SENT
)
}
if (params.payload !== undefined) {
throw new OrchestrationError(
'invalid_argument',
'--on carries a subject and body; payload fields such as --task-id or --report-path name work on this Orca only. Nothing was sent.',
NOTHING_SENT
)
}
const caller = peerMailLocalCaller({ ...args, from: params.from })
const server = await requirePeerMailServer(runtime, params.on)
const conversation = runtime.getOrchestrationDb().openHomePeerMailConversation({
environmentId: server.environmentId,
peerFingerprint: peerMailPairing(server),
localParty: caller.address,
localPaneKey: caller.paneKey
})
const id = peerMailMessageId(args.orchestrationMutation)
await deliverPeerMail(runtime, server, conversation, {
id,
to,
senderLabel: peerMailSenderLabel(runtime, caller.address),
subject: params.subject,
body: params.body,
type,
priority: params.priority,
threadId: params.threadId
})
return recordReceiptBeforeNudge(
args.recordMutationReceipt,
{ message: { id, to }, server: server.name },
() => runtime.ensureOrchestrationFederationRelay(),
{ kind: 'federation' }
)
}
/** `orchestration.send` with `on` set goes to the paired server; every other send runs unchanged. */
export function withPeerMailSend(
methods: typeof ORCHESTRATION_SEND_METHODS
): typeof ORCHESTRATION_SEND_METHODS {
return methods.map((method) => ({
...method,
handler: (params: Parameters<typeof method.handler>[0], ctx: RpcContext) => {
const on = params.on
if (on === undefined || ctx.replayedMutationReceipt !== undefined) {
return method.handler(params, ctx)
}
const attested = ctx.orchestrationCompatibilityCallerAuthority
return sendPeerMail({
params: { ...params, on },
runtime: ctx.runtime,
orchestrationCaller: ctx.orchestrationCaller,
attestedCaller: attested?.terminalHandle === params.from ? attested : undefined,
orchestrationMutation: ctx.orchestrationMutation,
recordMutationReceipt: ctx.recordMutationReceipt
})
}
}))
}
@@ -14,6 +14,7 @@ import { recordReceiptBeforeNudge, replayMutationNudge } from './mutation-replay
import { resolveReplyRecipient } from './recipient-routing'
import { helperQuestionAnswerer } from './helper-question-answerer'
import { replyToRemoteRunHome } from './reply-remote'
import { replyOverPeerMail } from './peer-mail-reply'
import { withAnswerNext } from '../receipt-next'
import { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration-params'
import {
@@ -35,6 +36,7 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({
legacyCoordinatorRunId,
recordMutationReceipt,
replayedMutationReceipt,
orchestrationMutation,
signal
}
) => {
@@ -157,6 +159,25 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({
)
}
const peerRoute = db.getPeerMailMessage(original.id)
if (peerRoute) {
return await replyOverPeerMail({
runtime,
original,
route: peerRoute,
params,
orchestrationCaller,
orchestrationMutation,
recordMutationReceipt
})
}
if (params.on !== undefined) {
throw new OrchestrationError(
'invalid_argument',
`${params.id} did not come from another server, so its reply stays on this Orca. Drop --on. No reply was sent.`,
{ effectsApplied: false }
)
}
if (db.getRun(original.run_id)?.home_database === 'remote') {
return await replyToRemoteRunHome({ runtime, db, original, params, signal })
}
@@ -38,6 +38,7 @@ import {
settledDispatchId
} from './settled-worker-follow-through'
// `send --on <server>` is carried by withPeerMailSend (peer-mail-send.ts) before this handler runs.
export const ORCHESTRATION_SEND_METHODS = [
defineMethod({
name: 'orchestration.send',
@@ -33,6 +33,8 @@ export const SendParams = z
// Use remint-stable pane keys to attest worker_done/heartbeat; from handles only route.
senderPaneKey: OptionalString,
run: OptionalString,
// A paired server: this Orca carries the mail there and the replies back (`send --on`).
on: OptionalString,
waitForLifecycleSettlement: OptionalBoolean,
devMode: OptionalBoolean
})
@@ -5,6 +5,7 @@ import { ORCHESTRATION_WORKER_METHODS } from './worker/worker-methods'
import { ORCHESTRATION_FEDERATION_METHODS } from './federation/federation-methods'
import { ORCHESTRATION_MUTATION_REQUEST_METHODS } from './runs/mutation-request-show'
import { ORCHESTRATION_SEND_METHODS } from './messaging/send-methods'
import { withPeerMailSend } from './messaging/peer-mail-send'
import { ORCHESTRATION_CHECK_METHODS } from './messaging/check-methods'
import { ORCHESTRATION_MESSAGE_METHODS } from './messaging/message-methods'
import { ORCHESTRATION_DISPATCH_METHODS } from './runs/dispatch-methods'
@@ -20,7 +21,7 @@ export const ORCHESTRATION_METHODS = requiringOrcadFeature('orchestration', [
...ORCHESTRATION_WORKER_METHODS,
...ORCHESTRATION_FEDERATION_METHODS,
...ORCHESTRATION_MUTATION_REQUEST_METHODS,
...ORCHESTRATION_SEND_METHODS,
...withPeerMailSend(ORCHESTRATION_SEND_METHODS),
...ORCHESTRATION_CHECK_METHODS,
...ORCHESTRATION_MESSAGE_METHODS,
...ORCHESTRATION_DISPATCH_METHODS,
+2
View File
@@ -29,4 +29,6 @@ export type SttRecognizer = {
finish(streamId: string): Promise<void>
/** Drop the stream's audio undecoded. */
discard(streamId: string): void
/** Called on a cancel's arrival, ahead of the queue: skip the stream's remaining chunks; the running decode finishes. */
cancel(streamId: string): void
}
+42
View File
@@ -13,6 +13,8 @@ const { MockWorker, getCreatedWorkerCount, getLastWorker, resetWorkers } = vi.ho
terminated = false
emitStoppedOnStop = true
answerDiscard = true
/** False: a decode for the canceled stream never ends, so the queue never reaches its discard. */
reachDiscard = true
emitReadyOnInit = HoistedMockWorker.emitReadyOnInit
emitExitOnTerminate = true
terminatePromise: Promise<number> | null = null
@@ -64,6 +66,11 @@ const { MockWorker, getCreatedWorkerCount, getLastWorker, resetWorkers } = vi.ho
) {
queueMicrotask(() => this.emit('message', { type: 'stopped', streamId: message.streamId }))
}
if (message.type === 'discard' && this.answerDiscard && this.reachDiscard) {
queueMicrotask(() =>
this.emit('message', { type: 'discarded', streamId: message.streamId })
)
}
}
attachAudioPort(streamId: string, port: unknown): boolean {
@@ -464,6 +471,41 @@ describe('SttService', () => {
expect(worker!.messages.filter((message) => message.type === 'feed')).toHaveLength(0)
})
it('ends a finishing dictation at once when it is canceled, without waiting for its decode', async () => {
const service = new SttService(readyModels(), spawnMockWorker)
const sink = vi.fn()
await service.startDictation('model-a', sink, undefined, 'desktop')
const worker = getLastWorker()!
worker.emitStoppedOnStop = false
const finishing = service.stopDictation('desktop')
await service.stopDictation('desktop', { discard: true })
await finishing
expect(worker.terminated).toBe(false)
expect(sink).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))
})
it('restarts the speech process when a canceled decode is still running as the next dictation starts', async () => {
vi.useFakeTimers()
try {
const service = new SttService(readyModels(), spawnMockWorker)
await service.startDictation('model-a', vi.fn(), undefined, 'desktop')
const hung = getLastWorker()!
hung.reachDiscard = false
await service.stopDictation('desktop', { discard: true })
const next = service.startDictation('model-a', vi.fn(), undefined, 'desktop')
await vi.advanceTimersByTimeAsync(2_000)
await next
expect(hung.terminated).toBe(true)
expect(getLastWorker()).not.toBe(hung)
} finally {
vi.useRealTimers()
}
})
it('drops in-flight audio while stop is waiting for the worker', async () => {
const service = new SttService(readyModels(), spawnMockWorker)
+5
View File
@@ -154,6 +154,10 @@ async function acquireSttEngine(
const current = state.engine
// Bound in the same step it is chosen, so an idle teardown never sees it unused.
if (current && sameSttRecognizerConfig(current, config)) {
if (current.draining) {
await current.draining
continue
}
clearSttIdleTeardownTimer(state)
return bindSttEngine(session, current)
}
@@ -212,6 +216,7 @@ export function spawnSttEngine(
retired: false,
vadModelPath,
onUnloaded: [],
draining: null,
ready: readyPromise.catch((error: unknown) => {
failSttEngine(state, engine, STT_WORKER_EXITED_ERROR)
throw error
+2
View File
@@ -23,6 +23,8 @@ export type SttEngine = SttRecognizerConfig & {
vadModelPath: string | undefined
/** Called once this process is gone; set when it must not outlive its last dictation. */
onUnloaded: (() => void)[]
/** Set while a canceled stream's last decode finishes; a new dictation waits for it before reusing this process. */
draining: Promise<void> | null
}
export type SttSession = {
+64 -2
View File
@@ -27,9 +27,12 @@ export function stopSttDictation(
return Promise.resolve()
}
if (session.phase === 'stopping') {
// A cancel after Finish still aborts the cloud upload whose text it would throw away.
// A cancel after Finish still drops the work whose text it would throw away.
if (options.discard) {
session.cloud?.cancel()
if (session.engine) {
discardLocalStream(state, session.engine, session.streamId)
}
}
return session.stopPromise ?? Promise.resolve()
}
@@ -78,10 +81,69 @@ function stopLocalSession(
discard,
finish: (outcome) => finishLocalStop(state, session, engine, outcome, discard)
})
engine.worker.postMessage({ type: discard ? 'discard' : 'stop', streamId: session.streamId })
if (discard) {
discardLocalStream(state, engine, session.streamId)
} else {
engine.worker.postMessage({ type: 'stop', streamId: session.streamId })
}
return stopped
}
/**
* The speech process answers a cancel at once and skips the stream's queued work, but a decode already running
* finishes first. One that outlasts the grace (hung in native code, or just long) restarts the process, as a
* cancel always did, so the next dictation isn't stuck behind it.
*/
function discardLocalStream(state: SttSessionState, engine: SttEngine, streamId: string): void {
const reached = waitForSttWorkerMessage(
engine.worker,
(message) => message.type === 'discarded' && message.streamId === streamId,
DISCARD_DICTATION_TIMEOUT_MS
)
engine.worker.postMessage({ type: 'discard', streamId })
const draining = reached.then(async (inTime) => {
// Another device's decode may hold the queue; never kill its dictation.
if (!inTime && state.engine === engine && sttEngineUsers(state, engine).length === 0) {
// A failed kill must not fail the dictation waiting on this; it starts on a fresh process either way.
await teardownSttEngine(state, engine).catch((error: unknown) =>
console.warn('[speech] Could not stop the busy speech process after a cancel:', error)
)
}
})
engine.draining = draining
void draining.finally(() => {
if (engine.draining === draining) {
engine.draining = null
}
})
}
/** Resolves true when the worker sends a matching message (or exits), false after `timeoutMs`. */
function waitForSttWorkerMessage(
worker: SttEngine['worker'],
matches: (message: { type: string; streamId?: string }) => boolean,
timeoutMs: number
): Promise<boolean> {
return new Promise((resolve) => {
const settle = (inTime: boolean): void => {
clearTimeout(timer)
worker.off('message', onMessage)
worker.off('exit', onExit)
resolve(inTime)
}
const onMessage = (message: { type: string; streamId?: string }): void => {
if (matches(message)) {
settle(true)
}
}
const onExit = (): void => settle(true)
const timer = setTimeout(() => settle(false), timeoutMs)
timer.unref?.()
worker.on('message', onMessage)
worker.on('exit', onExit)
})
}
function finishLocalStop(
state: SttSessionState,
session: SttSession,
@@ -174,9 +174,15 @@ export async function createTranscribeCppRecognizer(
})
}
// Canceled streams, until their queued discard runs; also covers a finish that already closed its stream.
const canceled = new Set<string>()
const decode = async (streamId: string, stream: StreamCoverage, chunks: Float32Array[]) => {
let undecoded = chunks.reduce((total, chunk) => total + chunk.length, 0)
for (const chunk of chunks) {
if (canceled.has(streamId)) {
return
}
const startedAt = performance.now()
const text = await transcribeChunk(chunk, stream.options)
const decodeMs = performance.now() - startedAt
@@ -254,7 +260,11 @@ export async function createTranscribeCppRecognizer(
}
},
discard(streamId) {
canceled.delete(streamId)
closeStream(streamId)?.vad?.dispose()
},
cancel(streamId) {
canceled.add(streamId)
}
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ type ChildMessage =
| { type: 'chunk'; streamId: string; text: string; samples: number }
| { type: 'speech-pending'; streamId: string; pending: boolean }
| {
type: 'ready' | 'loading' | 'stopped' | 'error' | 'partial' | 'final'
type: 'ready' | 'loading' | 'stopped' | 'discarded' | 'error' | 'partial' | 'final'
streamId?: string
text?: string
error?: string
+27 -3
View File
@@ -16,6 +16,8 @@ type AudioPortInput = {
const parentPort = connectSttWorkerParentPort()
let recognizer: SttRecognizer | null = null
const audioPorts = new Map<string, AudioPortInput>()
// Canceled streams whose queued work is skipped instead of decoded; cleared when their discard runs.
const discarded = new Set<string>()
// transcribe-cpp decodes off the event loop; one queue keeps feeds behind init and stop behind feeds.
let queue: Promise<void> = Promise.resolve()
@@ -37,6 +39,9 @@ async function handleInit(init: SttRecognizerInit): Promise<void> {
}
async function handleFeed(msg: Extract<SttWorkerRequest, { type: 'feed' }>): Promise<void> {
if (discarded.has(msg.streamId)) {
return
}
try {
await recognizer?.feed(msg.streamId, msg.samples, msg.sampleRate)
} catch (err) {
@@ -48,6 +53,11 @@ function attachAudioPort(streamId: string, port: MessagePortMain | undefined): v
if (!port) {
return
}
// A cancel that arrived while this attach waited in line must not let the port's frames reopen the stream.
if (discarded.has(streamId)) {
port.close()
return
}
const input: AudioPortInput = { port, onEnded: null, ending: false }
const end = (): void => {
if (audioPorts.get(streamId) !== input) {
@@ -83,6 +93,9 @@ function attachAudioPort(streamId: string, port: MessagePortMain | undefined): v
}
async function handleStop(streamId: string): Promise<void> {
if (discarded.has(streamId)) {
return
}
const input = audioPorts.get(streamId)
// Main's stop can overtake the renderer's last frames on the port; finish only after them.
if (input) {
@@ -98,15 +111,23 @@ async function handleStop(streamId: string): Promise<void> {
}
}
// A canceled dictation drops its audio undecoded.
function handleDiscard(streamId: string): void {
// A cancel answers at once, even during Finish, and the stream's queued audio is skipped rather than decoded.
function cancelStream(streamId: string): void {
discarded.add(streamId)
recognizer?.cancel(streamId)
const input = audioPorts.get(streamId)
audioPorts.delete(streamId)
input?.port.close()
recognizer?.discard(streamId)
parentPort.post({ type: 'stopped', streamId })
}
// Runs in queue order, after everything queued for the stream before the cancel; the host waits for it.
function handleDiscard(streamId: string): void {
discarded.delete(streamId)
recognizer?.discard(streamId)
parentPort.post({ type: 'discarded', streamId })
}
function handleMessage(
msg: SttWorkerRequest,
ports: readonly MessagePortMain[]
@@ -130,5 +151,8 @@ function handleMessage(
parentPort.onMessage((message, ports) => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the session host posts here, and it sends SttWorkerRequest.
const msg = message as SttWorkerRequest
if (msg.type === 'discard') {
cancelStream(msg.streamId)
}
enqueue(() => handleMessage(msg, ports))
})
+3
View File
@@ -61,6 +61,7 @@
--color-chat-foreground: var(--chat-foreground);
--color-chat-foreground-strong: var(--chat-foreground-strong);
--color-chat-foreground-faint: var(--chat-foreground-faint);
--color-chat-unread: var(--chat-unread);
--color-chat-user-surface: var(--chat-user-surface);
--color-chat-user-border: var(--chat-user-border);
--color-chat-code-foreground: var(--chat-code-foreground);
@@ -741,6 +742,8 @@ body[data-modal-overlay-open]
/* Mixed toward the foreground so each clears text contrast on the canvas in either scheme. */
--chat-focus-ring: color-mix(in srgb, var(--chat-source-foreground) 50%, var(--chat-canvas));
--chat-warning: color-mix(in srgb, var(--status-warning) 70%, var(--chat-source-foreground));
/* What the reader has not seen yet: the transcript's "New" marker, in the note hue. */
--chat-unread: color-mix(in srgb, var(--callout-note) 70%, var(--chat-source-foreground));
--chat-diff-added: color-mix(in srgb, var(--diff-added) 70%, var(--chat-source-foreground));
--chat-diff-removed: color-mix(in srgb, var(--diff-removed) 70%, var(--chat-source-foreground));
--chat-link: color-mix(
@@ -4,13 +4,14 @@ import {
NATIVE_CHAT_TRANSCRIPT_COLUMN_CLASS
} from './appearance/native-chat-appearance-style'
import { NativeChatJumpToLatest } from './viewport/scroll/NativeChatJumpToLatest'
import { NativeChatNewRowsAnnouncement } from './viewport/new-rows/NativeChatNewRowsMarker'
import { useNativeChatNewRowsMarker } from './viewport/new-rows/native-chat-new-rows-marker'
import { withoutPullRequestEventRows } from '../../../../shared/native-chat/native-chat-pull-request-event'
import { useNativeChatRowTypography } from './viewport/virtualization/use-native-chat-row-typography'
import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslate } from '@/i18n/use-translate'
import { useAppStore } from '@/store'
import {
nativeChatScrollsToLatestOnSend,
nativeChatShowsCiResultLines,
nativeChatShowsTurnDiffSummary
} from '../../../../shared/native-chat/native-chat-appearance-settings'
@@ -243,12 +244,18 @@ export function NativeChatMessageList({
[allSlots, journalItems, stopping, journalSubmissions, latestTurn, hostWork]
)
const navigationRequest = useNativeChatNavigationRequest(slots, messages, subagentSections)
const newRows = useNativeChatNewRowsMarker(
slots,
waitingSlots,
isVisible && session.readCurrent === true
)
const transcriptWindow = useNativeChatTranscriptWindow({
scrollRef,
slots,
isVisible,
// Rail jumps, diff reveals and subagent reveals share one mutually exclusive pin.
revealIndex: navigationRequest.revealIndex,
newRowsMarkerIndex: newRows.index,
typography
})
const transcriptScroll = useNativeChatTranscriptScroll({
@@ -326,25 +333,15 @@ export function NativeChatMessageList({
onLeaveEnd: readerLeavesEnd,
onScrollGesture: transcriptScroll.forwardedGesture
})
// Off keeps a reader who scrolled up in place; one at the end still follows the reply.
const revealSent = useCallback(
(readerWasAtEnd = readerAtEnd()) => {
if (!nativeChatScrollsToLatestOnSend(useAppStore.getState().settings) && !readerWasAtEnd) {
return
}
beginNavigation()
scrollToBottom('send')
},
[beginNavigation, readerAtEnd, scrollToBottom]
)
useNativeChatMessageListHandle(
ref,
revealSent,
readerInput.revealFindMatch,
allSlots,
useNativeChatMessageListHandle(ref, {
readerAtEnd,
navigation.revealSubagent
)
beginNavigation,
scrollToBottom,
onSent: newRows.dismiss,
revealFindMatch: readerInput.revealFindMatch,
slots: allSlots,
revealSubagent: navigation.revealSubagent
})
const rowContext = useNativeChatTranscriptRowContext({
agent: session.agent,
@@ -397,6 +394,7 @@ export function NativeChatMessageList({
loadedMessageIds={loadedMessageIds}
context={rowContext}
window={transcriptWindow}
newRowsMarker={newRows.marker}
forwardGesture={readerInput.forwardedGesture}
/>
{liveLine ? (
@@ -417,6 +415,7 @@ export function NativeChatMessageList({
pendingId={navigation.pendingRailId}
/>
<NativeChatJumpToLatest visible={showJump} onJump={jumpToLatest} />
<NativeChatNewRowsAnnouncement marked={newRows.marker !== undefined} />
</div>
<NativeChatDockedTaskList key={session.sessionId} messages={messages} />
</div>
@@ -1,5 +1,7 @@
import { useCallback, useImperativeHandle, useMemo, useRef } from 'react'
import { useAppStore } from '@/store'
import { hasAskAnswer } from '../../../../../../shared/native-chat/input/native-chat-ask-answer'
import { nativeChatScrollsToLatestOnSend } from '../../../../../../shared/native-chat/native-chat-appearance-settings'
import { nativeChatSlotCopyText } from './native-chat-message-copy-text'
import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-chat-transcript-slots'
import type { NativeChatInteractiveSend } from '../../session/terminal/send/use-native-chat-interactive-send'
@@ -86,22 +88,36 @@ export function useNativeChatRevealLatest(): {
return { messageListRef, revealLatest, captureRevealLatest }
}
function ignoreFindMatch(): void {}
function alwaysAtEnd(): boolean {
return true
}
function ignoreSubagent(): void {}
/** Own sends follow the latest; with that setting off, only a reader who was at the end does. */
export function useNativeChatMessageListHandle(
ref: React.Ref<NativeChatMessageListHandle> | undefined,
revealLatest: NativeChatMessageListHandle['revealLatest'],
revealFindMatch: NativeChatMessageListHandle['revealFindMatch'] = ignoreFindMatch,
slots: readonly NativeChatTranscriptSlot[] = [],
readerAtEnd: NativeChatMessageListHandle['readerAtEnd'] = alwaysAtEnd,
revealSubagent: NativeChatMessageListHandle['revealSubagent'] = ignoreSubagent
{
readerAtEnd,
beginNavigation,
scrollToBottom,
onSent,
revealFindMatch,
slots,
revealSubagent
}: Pick<NativeChatMessageListHandle, 'readerAtEnd' | 'revealFindMatch' | 'revealSubagent'> & {
beginNavigation: () => void
scrollToBottom: (reason: 'send') => void
/** The reader answered, whether or not the view moves. */
onSent: () => void
slots: readonly NativeChatTranscriptSlot[]
}
): void {
const revealLatest = useCallback(
(readerWasAtEnd = readerAtEnd()) => {
onSent()
if (!nativeChatScrollsToLatestOnSend(useAppStore.getState().settings) && !readerWasAtEnd) {
return
}
beginNavigation()
scrollToBottom('send')
},
[beginNavigation, onSent, readerAtEnd, scrollToBottom]
)
useImperativeHandle(
ref,
() => ({
@@ -20,6 +20,8 @@ import { nativeChatRowOffersRewind } from '../../../../../../shared/native-chat/
import { NativeChatForkContext } from '../actions/native-chat-fork-context'
import { nativeChatSlotOffersFork } from '../actions/native-chat-side-chat-fork-point'
import { isActionableStructuredAgentSessionPrompt } from '../../../../../../shared/agent-session/view/structured-agent-session-live-turn'
import { NativeChatNewRowsMarker } from '../../viewport/new-rows/NativeChatNewRowsMarker'
import type { NativeChatNewRowsMarkerState } from '../../viewport/new-rows/native-chat-new-rows-marker'
/** Memoize shared context so unchanged rows keep their props during transcript updates. */
export type NativeChatTranscriptRowContext = {
@@ -45,10 +47,13 @@ export type NativeChatTranscriptRowContext = {
/** Wrap message, status and rollup for one virtualized measurement; internal spacing is the row’s, inter-row gaps the window’s. */
export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({
slot,
context
context,
newRowsMarker
}: {
slot: NativeChatTranscriptSlot
context: NativeChatTranscriptRowContext
/** The "New" marker, when it draws in this row. */
newRowsMarker?: NativeChatNewRowsMarkerState
}): React.JSX.Element {
// Offered only on the conversation's own turn-opening prompts (`nativeChatRowOffersRewind`).
const rewind = useContext(NativeChatRewindContext)
@@ -84,6 +89,9 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({
const deliveryNotice = context.deliveryNotices?.get(message.id)
const predecessors = context.taskListPredecessors.get(message.id)
const expanded = turnKey ? context.expandedTurnIds.has(turnKey) : undefined
const marker = newRowsMarker ? (
<NativeChatNewRowsMarker marker={newRowsMarker} onReveal={context.onScrollMessageToTop} />
) : null
const statusRow = status ? (
<NativeChatWorkingStatus
startedAt={status.startedAt}
@@ -105,6 +113,7 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({
sectionClassName
)}
>
{newRowsMarker?.place === 'above-row' ? marker : null}
{/* A turn with no user bubble carries its bar above its first row. */}
{slot.statusAbove ? statusRow : null}
{!slot.drawsMessage ? null : receipt ? (
@@ -154,6 +163,7 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({
workRun={workRun}
/>
)}
{newRowsMarker?.place === 'above-turn-bar' ? marker : null}
{slot.statusAbove ? null : statusRow}
{turnDiff ? <NativeChatTurnDiffRollup diff={turnDiff} /> : null}
{openedPullRequests ? (
@@ -4,7 +4,6 @@ import { useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as I18n from '@/i18n/i18n'
import { createGlobalSettingsFixture } from '../../../../../shared/global-settings-test-fixture'
import { getOverlayFocusOwners } from '@/lib/overlay-focus-ownership'
import { useAppStore } from '../../../store/index'
import type { NativeChatComposerHandle } from '../composer/native-chat-composer-types'
import { NativeChatMarkdown } from '../markdown/NativeChatMarkdown'
@@ -89,31 +88,6 @@ describe('NativeChatSelectionQuote', () => {
vi.useRealTimers()
})
it('quotes a selection from an agent reply into the composer as a blockquote', () => {
render(<Chat />)
releaseSelection(screen.getByTestId('first'))
const quote = screen.getByRole('button', { name: 'Add to chat' })
fireEvent.pointerDown(quote, { button: 0 })
fireEvent.click(quote)
expect(appendText).toHaveBeenCalledWith('> Use the draft store.\n>\n> It already appends.\n\n')
expect(screen.queryByRole('button', { name: 'Add to chat' })).toBeNull()
})
it('closes the offer before the composer takes the quote and focus', () => {
let focusOwners: HTMLElement[] | undefined
appendText.mockImplementationOnce(() => {
focusOwners = getOverlayFocusOwners()
})
render(<Chat />)
releaseSelection(screen.getByTestId('first'))
fireEvent.click(screen.getByRole('button', { name: 'Add to chat' }))
expect(focusOwners).toEqual([])
})
it('takes a selection that runs on over text that cannot be selected', () => {
render(<Chat />)
releaseSelection(screen.getByTestId('first'), screen.getByTestId('time'))
@@ -126,28 +100,6 @@ describe('NativeChatSelectionQuote', () => {
releaseSelection(screen.getByTestId('first'), screen.getByTestId('next'))
expect(screen.queryByRole('button', { name: 'Add to chat' })).toBeNull()
})
it('offers nothing when a press leaves the selection as it was', () => {
render(<Chat />)
releaseSelection(screen.getByTestId('first'))
fireEvent.pointerDown(screen.getByTestId('time'), { button: 0 })
fireEvent.mouseUp(screen.getByTestId('time'), { button: 0 })
settle()
expect(screen.queryByRole('button', { name: 'Add to chat' })).toBeNull()
})
it('withdraws the offer once the selection is gone', () => {
render(<Chat />)
releaseSelection(screen.getByTestId('first'))
expect(screen.getByRole('button', { name: 'Add to chat' })).toBeTruthy()
act(() => {
window.getSelection()!.removeAllRanges()
document.dispatchEvent(new Event('selectionchange'))
})
expect(screen.queryByRole('button', { name: 'Add to chat' })).toBeNull()
})
})
describe('NativeChatSelectionQuote copy on select', () => {
@@ -22,11 +22,6 @@ vi.mock('../media/visuals/NativeChatInlineVisual', () => ({
vi.mock('@/lib/open-agent-message-sender', () => ({
openAgentMessageSender: unusedChatLeaves.openSender
}))
afterEach(() => {
expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled()
expect(unusedChatLeaves.openSender).not.toHaveBeenCalled()
})
import type {
AgentJournalItemBody,
AgentJournalProducerLinkage,
@@ -132,60 +127,6 @@ import { session, stubLayout } from '../viewport/virtualization/native-chat-wind
vi.restoreAllMocks()
})
it("draws an open agent's rows between its entry and the next one", () => {
const agents = [
{ id: 'task-a', label: 'lane a', state: 'completed' as const },
{ id: 'task-b', label: 'lane b', state: 'completed' as const },
{ id: 'task-c', label: 'lane c', state: 'completed' as const }
]
const items = [
itemsWith('completed', false)[0]!,
journalItem(
'spawn',
{
kind: 'message',
role: 'system',
blocks: [{ type: 'subagent-group', groupId: 'group-1', agents }]
},
2
),
...agents.map(({ id, label }, index) =>
journalItem(
`${id}-said`,
{
kind: 'message',
role: 'assistant',
blocks: [{ type: 'text', text: `Read ${label}.` }]
},
3 + index,
{ agentId: id, producerKind: 'agent' }
)
)
]
render(
<NativeChatMessageList
session={session(projectStructuredItemsToNativeChat(items))}
journalItems={items}
isWorking={false}
expandSignal={false}
/>
)
fireEvent.click(screen.getByRole('button', { name: /Ran 3 subagents/ }))
fireEvent.click(screen.getByRole('button', { name: /lane b/ }))
const order = [
screen.getByRole('button', { name: /lane a/, expanded: false }),
screen.getByRole('button', { name: /lane b/, expanded: true }),
screen.getByText('Read lane b.'),
screen.getByRole('button', { name: /lane c/, expanded: false })
]
for (const [index, node] of order.slice(1).entries()) {
expect(order[index]!.compareDocumentPosition(node)).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
}
expect(screen.queryByText('Read lane a.')).toBeNull()
expect(screen.getAllByText(/^lane [abc]$/)).toHaveLength(3)
})
// Journal turn records own subagent edits, even when a newer send is queued or the opener is unloaded.
it("counts a subagent's edit in the turn the journal says it was made in", () => {
const say = (itemId: string, role: 'user' | 'assistant', text: string, sequence: number) =>
@@ -275,16 +216,6 @@ import { session, stubLayout } from '../viewport/virtualization/native-chat-wind
expect(screen.getByText('The PR is CLEAN.')).toBeInTheDocument()
})
it('opens a working subagent while the session waits on it, and closes it once the parent moves on', () => {
const { rerender } = render(listOf('working', true))
expect(screen.getByText('The PR is CLEAN.')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /explore the lane/, expanded: true })).toBeVisible()
expect(screen.getAllByText('explore the lane')).toHaveLength(1)
rerender(listOf('working'))
expect(screen.queryByText('The PR is CLEAN.')).toBeNull()
expect(screen.getByRole('button', { name: /Kicked off 1 subagent/ })).toBeInTheDocument()
})
it("keeps the reader's choice over the frontier, in either direction", () => {
const { rerender } = render(listOf('working', true))
fireEvent.click(screen.getByRole('button', { name: /explore the lane/, expanded: true }))
@@ -1,136 +0,0 @@
import { describe, expect, it } from 'vitest'
import type {
NativeChatMessage,
NativeChatSubagentState
} from '../../../../../shared/native-chat/native-chat-types'
import { projectNativeChatTranscript } from '../../../../../shared/native-chat/transcript/native-chat-transcript-projection'
import { nativeChatTurnMembership } from '../../../../../shared/native-chat/transcript/native-chat-turn-membership'
import { compareNativeChatDisplayMessages as compareMessages } from '../../../../../shared/native-chat/transcript/native-chat-message-order'
import { nativeChatSubagentSections } from './native-chat-subagent-sections'
import {
buildNativeChatTranscriptSlots,
type NativeChatTranscriptSlot
} from '../conversation/slots/native-chat-transcript-slots'
let sequence = 0
function row(
id: string,
blocks: NativeChatMessage['blocks'],
overrides: Partial<NativeChatMessage> = {}
): NativeChatMessage {
sequence += 1
return {
id,
role: 'assistant',
blocks,
timestamp: 1,
source: 'transcript',
journalPosition: { sequence, index: 0 },
...overrides
}
}
const say = (value: string) => [{ type: 'text' as const, text: value }]
const call = (name: string) => [{ type: 'tool-call' as const, name, input: { name } }]
const by = (agentId: string) => ({ agentId, producerKind: 'agent' as const })
const thought = (id: string, agentId?: string, state: 'running' | 'completed' = 'completed') =>
row(id, say(`thinking ${id}`), {
role: 'reasoning',
state,
...(agentId ? by(agentId) : {})
})
const roster = (id: string, agentId: string, state: NativeChatSubagentState) =>
row(
id,
[
{
type: 'subagent-group',
groupId: `group-${id}`,
agents: [{ id: agentId, label: agentId, state }]
}
],
{ role: 'system' }
)
function slotsOf(rows: NativeChatMessage[], open: Record<string, boolean>) {
const { conversation, subagentRows } = projectNativeChatTranscript(rows, compareMessages)
const { turnKeys, liveTurnKey } = nativeChatTurnMembership(conversation)
return buildNativeChatTranscriptSlots({
messages: conversation,
turnKeys,
liveTurnKey,
receipts: new Map(),
turnStatuses: { active: null, completedByTurn: {} },
turnDiffs: new Map(),
expandedTurnKeys: new Set(),
isWorking: false,
lifecycleWorking: false,
subagentSections: nativeChatSubagentSections(conversation, subagentRows),
subagentChoices: { sections: new Map(Object.entries(open)), rosters: new Map() }
})
}
/** `>` per section a row sits in, then its id, its run's member ids, or `[agent]` for a head. */
function outline(slots: readonly NativeChatTranscriptSlot[]): string[] {
return slots.map((slot) => {
const indent = '>'.repeat(slot.depth)
if (slot.kind === 'subagent') {
return `${indent}[${slot.agentId}]`
}
if (slot.kind === 'subagent-entries') {
return `${indent}${slot.agents.map((agent) => agent.id).join()}`
}
return `${indent}${slot.workRun?.map((member) => member.id).join('+') ?? slot.message.id}`
})
}
describe('work runs and subagent sections', () => {
it('never runs across a section head', () => {
const rows = [
row('ask', say('go'), { role: 'user' }),
row('a', call('Read')),
row('s-a', call('Bash'), by('helper')),
thought('r1'),
row('c', call('Grep'))
]
expect(outline(slotsOf(rows, { helper: false }))).toEqual(['ask', 'a', '[helper]', 'r1+c'])
expect(outline(slotsOf(rows, { helper: true }))).toEqual([
'ask',
'a',
'[helper]',
'>s-a',
'r1+c'
])
})
it("keeps a working section's open thought out of its run until it ends", () => {
const rows = (state: NativeChatSubagentState, last: 'running' | 'completed') => {
sequence = 0
return [
row('ask', say('go'), { role: 'user' }),
roster('spawn', 'helper', state),
thought('s-r1', 'helper'),
row('s-a', call('Read'), by('helper')),
thought('s-r2', 'helper', last)
]
}
expect(outline(slotsOf(rows('working', 'running'), { helper: true }))).toEqual([
'ask',
'spawn',
'>s-r1+s-a',
'>s-r2'
])
expect(outline(slotsOf(rows('working', 'completed'), { helper: true }))).toEqual([
'ask',
'spawn',
'>s-r1+s-a+s-r2'
])
// A thought its finished agent never closed is not still being thought.
expect(outline(slotsOf(rows('completed', 'running'), { helper: true }))).toEqual([
'ask',
'spawn',
'>s-r1+s-a+s-r2'
])
})
})
@@ -1,163 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract'
import type { NativeChatComposerProps } from '../../composer/native-chat-composer-types'
import type { AgentStatusPayload } from '../../../../../../shared/agent-status/contracts/agent-status-types'
import type * as StreamingModule from '../../../../../../shared/native-chat/native-chat-streaming'
import { clearPendingSendCacheForTests } from '../../session/terminal/delivery/native-chat-pending'
const probe = vi.hoisted<{
session: NativeChatLiveSession | null
inputs: (readonly NativeChatMessage[])[]
shown: NativeChatMessage[]
}>(() => ({ session: null, inputs: [], shown: [] }))
vi.mock('../../session/terminal/read/use-native-chat-retained-session', () => ({
useNativeChatRetainedSession: () => probe.session
}))
vi.mock('../../NativeChatMessageList', () => ({
NativeChatMessageList: ({ session }: { session: NativeChatLiveSession }) => {
probe.shown = session.messages
return null
}
}))
vi.mock('../../composer/NativeChatComposer', () => ({
NativeChatComposer: ({ onOptimisticSend }: NativeChatComposerProps) => (
<button onClick={() => onOptimisticSend?.('Follow up')}>send</button>
)
}))
vi.mock('../../../../../../shared/native-chat/native-chat-streaming', async (importOriginal) => {
const original = await importOriginal<typeof StreamingModule>()
return {
...original,
deriveNativeChatStreamingText: (
args: Parameters<typeof original.deriveNativeChatStreamingText>[0]
) => {
probe.inputs.push(args.messages)
return original.deriveNativeChatStreamingText(args)
}
}
})
const { NativeChatResolvedView } = await import('../../NativeChatResolvedView')
const { TooltipProvider } = await import('@/components/ui/tooltip')
const { useAppStore } = await import('../../../../store/index')
const paneKey = 'preview-perf:leaf'
const message = (id: string, role: 'user' | 'assistant', text: string): NativeChatMessage => ({
id,
role,
blocks: [{ type: 'text', text }],
timestamp: 1,
source: 'transcript'
})
function setPreview(text: string, extra: Partial<AgentStatusPayload> = {}): void {
useAppStore.getState().setAgentStatus(paneKey, {
prompt: 'Prompt',
agentType: 'claude',
state: 'working',
lastAssistantMessage: text,
...extra
})
}
function previewTicks(expected: readonly NativeChatMessage[], extra = {}): void {
probe.inputs = []
for (let tick = 0; tick < 20; tick += 1) {
act(() => setPreview(`Current reply ${tick}`, extra))
}
expect(probe.inputs.length).toBeGreaterThanOrEqual(20)
expect(new Set(probe.inputs).size).toBe(1)
expect(probe.inputs[0]).toBe(expected)
}
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(1_000)
clearPendingSendCacheForTests()
probe.inputs = []
probe.shown = []
useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} })
})
afterEach(() => {
cleanup()
vi.useRealTimers()
clearPendingSendCacheForTests()
useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} })
})
describe('preview input allocation at realistic history sizes', () => {
it.each([1_000, 10_000])('reuses input across ticks with %i loaded messages', (size) => {
const transcript = Array.from({ length: size }, (_, index) =>
message(`history-${index}`, index % 2 ? 'assistant' : 'user', `History ${index}`)
)
probe.session = {
messages: transcript,
status: 'working',
sessionId: 'preview-perf',
agent: 'claude',
hasMore: false,
loadingEarlier: false,
olderHistoryGeneration: 0,
loadEarlier: vi.fn(),
readPhase: 'ready'
}
setPreview('Current reply')
render(
<TooltipProvider>
<NativeChatResolvedView
paneKey={paneKey}
agent="claude"
sessionId="preview-perf"
transcriptPath={null}
isVisible
isFocusedGroup
targetPtyId="preview-perf-pty"
terminalTabId="preview-perf"
ownsTabWideLaunchDraft={false}
/>
</TooltipProvider>
)
previewTicks(transcript)
act(() => fireEvent.click(screen.getByRole('button', { name: 'send' })))
const queued = probe.inputs.at(-1)!
expect(queued).toHaveLength(size + 1)
expect(queued.at(-1)?.pendingSend).toBe('queued')
previewTicks(queued)
expect(probe.shown.at(-2)?.id).toBe('streaming')
expect(probe.shown.at(-1)?.pendingSend).toBe('queued')
previewTicks(queued, { lastAssistantMessageIsToolOutput: true })
const caughtUp = [...transcript, message('reply', 'assistant', 'Current reply 19')]
act(() => {
probe.session = { ...probe.session!, messages: caughtUp }
setPreview('Current reply 19')
})
const updated = probe.inputs.at(-1)!
expect(updated).not.toBe(queued)
expect(updated.at(-2)?.id).toBe('reply')
expect(updated.at(-1)?.pendingSend).toBe('queued')
previewTicks(updated)
act(() => {
probe.session = { ...probe.session!, status: 'ready' }
setPreview('Idle', { state: 'done' })
})
const idle = probe.inputs.at(-1)!
expect(idle).not.toBe(updated)
previewTicks(idle, { state: 'done' })
const retired = [
...caughtUp,
{ ...message('follow-up', 'user', 'Follow up'), timestamp: 1_001 },
{ ...message('next-reply', 'assistant', 'Done'), timestamp: 1_002 }
]
act(() => {
probe.session = { ...probe.session!, messages: retired }
setPreview('Done', { state: 'done' })
})
previewTicks(retired, { state: 'done' })
})
})
@@ -140,15 +140,6 @@ function turnRow(): AgentJournalRenderItem {
}
}
it('leaves an auth turn row as the explanation when the catalog also says signed out', () => {
mocks.unavailable = { reason: 'notSignedIn', account: 'system' }
const row = startFailureRow({ kind: 'notSignedIn', account: 'system' })
mocks.journalItems = [turnRow(), { ...row, itemId: 'codex-unauthorized-error', sequence: 3 }]
render(pane())
expect(screen.queryByText(CODEX_SIGNED_OUT)).toBeNull()
expect(mocks.composerProps?.structuredTransport).not.toHaveProperty('unavailable')
})
it('stays dismissed for the same verdict, and shows again when it changes or comes back', () => {
mocks.unavailable = { reason: 'notSignedIn', account: 'system' }
const view = render(pane())
@@ -175,21 +166,6 @@ it('stays dismissed for the same verdict, and shows again when it changes or com
expect(screen.getByText(CODEX_SIGNED_OUT)).toBeTruthy()
})
it('says a reason once when the failed start already says it, keeping its Retry', () => {
mocks.launchLifecycle = 'failed'
mocks.launchFailure = {
kind: 'refused',
code: 'agent_session_operation_invalid',
details: { reason: 'notSignedIn' }
}
mocks.unavailable = { reason: 'notSignedIn', account: 'system' }
render(pane())
expect(screen.getAllByText(new RegExp(CODEX_SIGNED_OUT.replace(/[.`]/g, '\\$&')))).toHaveLength(1)
expect(screen.getByText(`Chat could not be started. ${CODEX_SIGNED_OUT}`)).toBeTruthy()
expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()
})
it("leaves the reason to the transcript's start-failure row, but not a different one", () => {
mocks.journalItems = [startFailureRow({ kind: 'notSignedIn' })]
mocks.unavailable = { reason: 'notSignedIn', account: 'system' }
@@ -61,7 +61,6 @@ vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChat
vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard())
import { NativeChatStructuredSession } from '../../NativeChatStructuredSession'
import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types'
import type { NativeChatStructuredComposerTransport } from '../../composer/submit/native-chat-structured-composer-transport'
const SESSION_ID = 'notice-card-session'
@@ -118,29 +117,3 @@ it('keeps a send failure’s raw error apart and lets the user dismiss it', () =
fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
expect(screen.queryByText('Your message was not sent.')).toBeNull()
})
const APPROVAL: AgentJournalRenderItem = JSON.parse(
JSON.stringify({
itemId: 'approval-item',
revision: 1,
sequence: 1,
observedAt: 1,
body: {
kind: 'approval',
title: 'Run the plan?',
detail: null,
subject: { kind: 'plan', text: 'x' },
options: [{ id: 'allow', label: 'Approve' }],
resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null }
}
})
)
it("keeps the notices above an approval card that takes the composer's place", () => {
mocks.launchLifecycle = 'failed'
mocks.promptItems = [APPROVAL]
renderPane()
expect(screen.queryByTestId('structured-composer')).toBeNull()
expect(screen.getByText('Chat could not be started.')).toBeTruthy()
expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()
})
@@ -35,72 +35,6 @@ afterEach(() => {
resetStructuredSessionMocks()
})
{
function renderPane(): void {
render(
<NativeChatStructuredSession
isVisible
isFocusedGroup
tabId="structured-read-error-tab"
sessionId="read-error-session"
target={{ kind: 'local' }}
agent="codex"
/>
)
}
function journalRefusal(
reason: 'journalCorrupt' | 'journalUnavailable' | 'journalWrittenByNewerOrca'
) {
return { code: 'agent_session_journal_unreadable', details: { reason } } as const
}
it('says a damaged history cannot load in one line, without claiming Orca keeps trying', () => {
mocks.status = 'error'
mocks.readRefusal = journalRefusal('journalCorrupt')
mocks.messages = []
renderPane()
expect(screen.getAllByText('Unable to load this chat.')).toHaveLength(1)
expect(screen.queryByText('Could not load conversation')).toBeNull()
expect(screen.queryByText(/keeps trying/)).toBeNull()
expect(screen.queryByText(/agent_session_/)).toBeNull()
// Nothing to send into: a send would only be refused and say it again.
expect(mocks.composerProps).toBeNull()
})
it("names a history that couldn't open right now once, in its one line", () => {
mocks.status = 'error'
mocks.readRefusal = journalRefusal('journalUnavailable')
mocks.messages = []
renderPane()
expect(screen.getAllByText("Orca couldn't open this chat's history right now.")).toHaveLength(1)
expect(screen.queryByText('Could not load conversation')).toBeNull()
expect(screen.queryByText(/keeps trying/)).toBeNull()
expect(screen.queryByText(/Try again/)).toBeNull()
// It can clear, so the composer stays and a send waits for the read.
expect(mocks.composerProps).not.toBeNull()
})
it('says once that a newer Orca saved the chat and only an update opens it, with no composer', () => {
mocks.status = 'error'
mocks.readRefusal = journalRefusal('journalWrittenByNewerOrca')
mocks.messages = []
renderPane()
expect(
screen.getAllByText('This chat was saved by a newer Orca. Update Orca to open it.')
).toHaveLength(1)
expect(screen.queryByText('Could not load conversation')).toBeNull()
expect(screen.queryByText(/keeps trying/)).toBeNull()
expect(mocks.composerProps).toBeNull()
})
}
{
const STILL_WORKING = "The agent is still working. Run /clear when it's done."
const BACKGROUND =
@@ -158,15 +92,4 @@ afterEach(() => {
pane.rerender()
expect(screen.queryByText(BACKGROUND)).toBeNull()
})
it('a line naming nothing the chat shows stays until the next send, as before', () => {
mocks.turnId = 'turn-1'
const pane = renderPane()
composerSays('Remove attachments before using a chat-session command.')
mocks.turnId = null
pane.rerender()
expect(screen.getByText('Remove attachments before using a chat-session command.')).toBeTruthy()
composerSays(null)
expect(screen.queryByText('Remove attachments before using a chat-session command.')).toBeNull()
})
}
@@ -1,164 +0,0 @@
// @vitest-environment happy-dom
import type * as LaunchRegistry from '@/lib/agent-session/launch/structured-agent-session-launch-registry'
import type * as LaunchOptions from '@/lib/agent-session/launch/structured-agent-session-launch-options'
import { act, cleanup, render, screen } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { ManagedRuntimeInstallObservation } from '@/runtime/hosts/installation/use-managed-runtime-install'
const { mocks, moduleFactories, resetStructuredSessionMocks, launchModule } = await vi.hoisted(
async () => {
const setup = (
await import('./NativeChatStructuredSession.test-harness')
).createStructuredSessionMocks()
return {
...setup,
launchModule: setup.moduleFactories.structuredAgentSessionLaunch()
}
}
)
const install = vi.hoisted((): { observation: ManagedRuntimeInstallObservation } => ({
observation: { kind: 'inactive' }
}))
vi.mock('@/lib/agent-session/launch/structured-agent-session-launch', () => ({
retryStructuredAgentSessionLaunch: launchModule.retryStructuredAgentSessionLaunch,
relaunchFailedStructuredAgentSessionForMessage:
launchModule.relaunchFailedStructuredAgentSessionForMessage
}))
vi.mock(
'@/lib/agent-session/launch/structured-agent-session-launch-registry',
async (importOriginal) => ({
...(await importOriginal<typeof LaunchRegistry>()),
getStructuredAgentSessionLaunchLifecycle: launchModule.getStructuredAgentSessionLaunchLifecycle,
getStructuredAgentSessionLaunchResumes: launchModule.getStructuredAgentSessionLaunchResumes,
useStructuredAgentSessionLaunchLifecycle: launchModule.useStructuredAgentSessionLaunchLifecycle,
useStructuredAgentSessionLaunchFailure: launchModule.useStructuredAgentSessionLaunchFailure
})
)
vi.mock(
'@/lib/agent-session/launch/structured-agent-session-launch-options',
async (importOriginal) => ({
...(await importOriginal<typeof LaunchOptions>()),
useStructuredAgentSessionLaunchSelection: launchModule.useStructuredAgentSessionLaunchSelection
})
)
vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-message', () =>
moduleFactories.structuredAgentSessionLaunchMessage()
)
vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () =>
moduleFactories.structuredAgentSessionCall()
)
vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () =>
moduleFactories.structuredAgentSessionSubscriptions()
)
vi.mock('@/components/machine-identity/use-published-machine-name', () => ({
usePublishedMachineName: () => null
}))
vi.mock('../../session/structured/use-structured-agent-session', () =>
moduleFactories.useStructuredAgentSession()
)
vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize())
vi.mock('../../links/actions/use-native-chat-file-link-context', () =>
moduleFactories.useNativeChatFileLinkContext()
)
vi.mock('../../pane/ownership/use-native-chat-tab-owner', () =>
moduleFactories.useNativeChatTabOwner()
)
vi.mock('../../links/actions/use-native-chat-file-link-click', () =>
moduleFactories.useNativeChatFileLinkClick()
)
vi.mock('../../NativeChatMessageList', () => moduleFactories.nativeChatMessageList())
vi.mock('../../host-access/NativeChatEmptyState', () => moduleFactories.nativeChatEmptyState())
vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard())
vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard())
vi.mock('@/runtime/hosts/installation/use-managed-runtime-install', () => ({
useManagedRuntimeInstall: () => install.observation
}))
import { NativeChatStructuredSession } from '../../NativeChatStructuredSession'
import { clearNativeChatComposerDraftsForTests } from '../../drafts/native-chat-draft-reset'
import { hydrateNativeChatComposerDrafts } from '../../drafts/native-chat-composer-draft-load'
import {
readNativeChatComposerDraft,
updateNativeChatComposerDraft
} from '../../drafts/native-chat-composer-draft-store'
import { structuredAgentSessionDraftScopeKey } from '../../drafts/native-chat-draft-scope'
import { TooltipProvider } from '@/components/ui/tooltip'
import { promptEditor } from '../../composer/editor/native-chat-prompt-editor.test-support'
import { promptTextContent } from '../../composer/editor/native-chat-prompt-document-text'
import {
createMemoryNativeChatComposerDraftStorage,
setNativeChatComposerDraftStorageForTests
} from '../../drafts/native-chat-composer-draft-storage'
afterEach(() => {
cleanup()
resetStructuredSessionMocks()
clearNativeChatComposerDraftsForTests()
})
it('shows and copies the ordinary source of an unsupported installed launch', async () => {
const text = 'Hand Off context\nwith trailing bytes '
clearNativeChatComposerDraftsForTests()
setNativeChatComposerDraftStorageForTests(createMemoryNativeChatComposerDraftStorage())
await hydrateNativeChatComposerDrafts()
mocks.launchLifecycle = 'failed'
mocks.launchFailure = { kind: 'refused', code: 'structured_agent_session_unsupported' }
mocks.messages = []
install.observation = {
kind: 'active',
subject: { target: { kind: 'local' }, runtimeId: null, agent: 'codex' },
snapshot: {
kind: 'known',
state: {
agent: 'codex',
revision: 1,
available: true,
version: '1.3.0',
installedVersion: '1.3.0',
installedCurrent: true,
downloadBytes: 0,
source: 'external',
operation: null
}
},
removable: false
}
updateNativeChatComposerDraft(
structuredAgentSessionDraftScopeKey('session-1'),
{ text, document: promptTextContent(text) },
'immediate'
)
render(
<TooltipProvider>
<NativeChatStructuredSession
isVisible
isFocusedGroup
tabId="structured-tab-1"
sessionId="session-1"
target={{ kind: 'local' }}
agent="codex"
/>
</TooltipProvider>
)
const field = await screen.findByRole('textbox')
expect(field.getAttribute('contenteditable')).toBe('true')
const editor = promptEditor(field)
act(() => {
editor.commands.selectAll()
})
let copied: string | undefined
editor.view.someProp('clipboardTextSerializer', (serializer) => {
copied = serializer(
editor.state.doc.slice(editor.state.selection.from, editor.state.selection.to),
editor.view
)
return true
})
expect(copied).toBe(text)
expect(editor.state.doc.textBetween(0, editor.state.doc.content.size, '\n')).toBe(text)
expect(readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey('session-1')).text).toBe(
text
)
})
@@ -1,11 +1,8 @@
import { getDefaultSettings } from '../../../../../../shared/constants'
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
const { mocks, moduleFactories, resetStructuredSessionMocks } = await vi.hoisted(async () =>
(await import('./NativeChatStructuredSession.test-harness')).createStructuredSessionMocks()
)
@@ -38,59 +35,6 @@ vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChat
import { NativeChatStructuredSession } from '../../NativeChatStructuredSession'
describe('NativeChatStructuredSession', () => {
it('isolates mounted chats from unrelated settings and renders their live follow-up choice', async () => {
const original = useAppStore.getState().settings
const settings = { ...getDefaultSettings('/tmp'), nativeChatQueueFollowUps: false }
useAppStore.setState({ settings })
const view = render(
<>
{['local-chat', 'ssh-chat'].map((sessionId) => (
<NativeChatStructuredSession
key={sessionId}
isVisible
isFocusedGroup
tabId={sessionId}
sessionId={sessionId}
target={
sessionId === 'local-chat'
? { kind: 'local' }
: { kind: 'environment', environmentId: 'ssh-host' }
}
agent="codex"
/>
))}
</>
)
try {
await act(async () => {})
mocks.controllerRender.mockClear()
act(() =>
useAppStore.setState({ settings: { ...settings, nativeChatQueueFollowUps: false } })
)
expect(mocks.controllerRender).not.toHaveBeenCalled()
act(() =>
useAppStore.setState({
settings: { ...settings, showTasksButton: !settings.showTasksButton }
})
)
expect(mocks.controllerRender).not.toHaveBeenCalled()
act(() => useAppStore.setState({ settings: { ...settings, nativeChatQueueFollowUps: true } }))
expect(new Set(mocks.controllerRender.mock.calls.map(([sessionId]) => sessionId))).toEqual(
new Set(['local-chat', 'ssh-chat'])
)
expect(mocks.controllerRender.mock.calls.every(([, queue]) => queue === true)).toBe(true)
mocks.controllerRender.mockClear()
act(() => useAppStore.setState({ settings }))
expect(new Set(mocks.controllerRender.mock.calls.map(([sessionId]) => sessionId))).toEqual(
new Set(['local-chat', 'ssh-chat'])
)
expect(mocks.controllerRender.mock.calls.every(([, queue]) => queue === false)).toBe(true)
} finally {
view.unmount()
useAppStore.setState({ settings: original })
}
})
afterEach(() => {
cleanup()
resetStructuredSessionMocks()
@@ -1,83 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { WslHostStatus } from '../../../../../../shared/wsl-host-types'
const { moduleFactories, resetStructuredSessionMocks } = await vi.hoisted(async () =>
(await import('./NativeChatStructuredSession.test-harness')).createStructuredSessionMocks()
)
const reconnectHost = vi.hoisted(() =>
vi.fn<(environmentId: string, failureMessage?: string) => Promise<boolean>>()
)
vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () =>
moduleFactories.structuredAgentSessionCall()
)
vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () =>
moduleFactories.structuredAgentSessionSubscriptions()
)
vi.mock('../../session/structured/use-structured-agent-session', () =>
moduleFactories.useStructuredAgentSession()
)
vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize())
vi.mock('../../links/actions/use-native-chat-file-link-context', () =>
moduleFactories.useNativeChatFileLinkContext()
)
vi.mock('../../links/actions/use-native-chat-file-link-click', () =>
moduleFactories.useNativeChatFileLinkClick()
)
vi.mock('../../NativeChatMessageList', () => moduleFactories.nativeChatMessageList())
vi.mock('../../composer/NativeChatComposer', () => moduleFactories.nativeChatComposer())
vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard())
vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard())
vi.mock('@/components/status-bar/runtime-environment-explicit-connect', () => ({
connectRuntimeHostAndReloadProjects: reconnectHost
}))
import { useAppStore } from '@/store/index'
import { NativeChatStructuredSession } from '../../NativeChatStructuredSession'
const initialState = useAppStore.getState()
function setWslStatus(state: WslHostStatus['state']): void {
act(() => {
useAppStore.setState({
wslHostStatuses: {
'wsl:ubuntu': { environmentId: 'wsl:ubuntu', distro: 'Ubuntu', state, detail: null }
}
})
})
}
function renderPane() {
return render(
<NativeChatStructuredSession
isVisible
isFocusedGroup
tabId="structured-wsl-stopped-tab"
sessionId="wsl-stopped-session"
target={{ kind: 'environment', environmentId: 'wsl:ubuntu' }}
agent="claude"
/>
)
}
afterEach(() => {
cleanup()
resetStructuredSessionMocks()
reconnectHost.mockReset()
useAppStore.setState({ wslHostStatuses: initialState.wslHostStatuses })
})
it('still offers Start after a start that failed', async () => {
renderPane()
setWslStatus('distro-stopped')
reconnectHost.mockResolvedValue(false)
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Start' }))
})
expect(screen.getByText('Ubuntu is stopped')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Start' })).toBeEnabled()
})
@@ -16,42 +16,6 @@ function msg(
}
describe('foldToolMessages', () => {
// Invisible provider events must not split visible runs; rendered plan updates do.
it('keeps one run across a wordless provider event, but not across a plan update', () => {
const frameRow = (id: string, kind: string): NativeChatMessage =>
msg({
id,
role: 'system',
blocks: [
{
type: 'text',
text: `codex · ${kind}`,
providerFrame: {
provider: 'codex',
kind,
payload: { head: '{}', byteLength: 2, digest: 'digest', truncated: false }
}
}
]
})
const run = (between: NativeChatMessage): string[] =>
foldToolMessages([
msg({
id: 'a1',
blocks: [
{ type: 'text', text: 'go' },
{ type: 'tool-call', name: 'Bash', input: {} }
]
}),
msg({ id: 'r1', role: 'tool', blocks: [{ type: 'tool-result', output: 'ok' }] }),
between,
msg({ id: 'a2', blocks: [{ type: 'tool-call', name: 'Bash', input: {} }] }),
msg({ id: 'r2', role: 'tool', blocks: [{ type: 'tool-result', output: 'ok' }] })
]).map((message) => message.id)
expect(run(frameRow('frame', 'notification:future/event'))).toEqual(['a1', 'frame'])
expect(run(frameRow('plan', 'notification:turn/plan/updated'))).toEqual(['a1', 'plan', 'a2'])
})
it('drops a result after a user turn abandons the pending call', () => {
const folded = foldToolMessages([
msg({ id: 'c', role: 'assistant', blocks: [{ type: 'tool-call', name: 'Bash', input: {} }] }),
@@ -61,21 +25,6 @@ describe('foldToolMessages', () => {
expect(folded.map((m) => m.id)).toEqual(['c', 'u'])
})
it('does not fold a message carrying prose alongside a tool block', () => {
const folded = foldToolMessages([
msg({ id: 'a', role: 'assistant', blocks: [{ type: 'text', text: 'first' }] }),
msg({
id: 'b',
role: 'assistant',
blocks: [
{ type: 'text', text: 'more' },
{ type: 'tool-call', name: 'Read', input: {} }
]
})
])
expect(folded.map((m) => m.id)).toEqual(['a', 'b'])
})
it('attributes a Claude tool result carried with a harness sidecar', () => {
const folded = foldToolMessages([
msg({
@@ -136,54 +85,4 @@ describe('foldToolMessages', () => {
})
])
})
it('folds through a harness noise boundary but not a real user turn', () => {
const folded = foldToolMessages([
msg({ id: 'a', role: 'assistant', blocks: [{ type: 'tool-call', name: 'Read', input: {} }] }),
msg({ id: 'n', role: 'user', blocks: [{ type: 'text', text: '<task-notification>done' }] }),
msg({ id: 'r', role: 'tool', blocks: [{ type: 'tool-result', output: 'ok' }] })
])
expect(folded.find((message) => message.id === 'a')?.blocks).toEqual([
{ type: 'tool-call', name: 'Read', input: {} },
{ type: 'tool-result', output: 'ok' }
])
})
})
describe('spawn-group roster rows', () => {
const roster = msg({
id: 'roster',
role: 'system',
blocks: [
{ type: 'text', text: 'Kicked off 1 subagent — 1 working' },
{
type: 'subagent-group',
groupId: 'thread:turn-1',
agents: [{ id: 'child-1', label: 'read', state: 'working' }]
}
]
})
it('does not end the assistant run the following tool messages fold into', () => {
const folded = foldToolMessages([
msg({
id: 'a',
role: 'assistant',
blocks: [
{ type: 'text', text: 'working' },
{ type: 'tool-call', name: 'Bash', input: {} }
]
}),
roster,
msg({ id: 't', role: 'tool', blocks: [{ type: 'tool-result', output: 'done' }] })
])
expect(folded.map((message) => message.id)).toEqual(['a', 'roster'])
expect(folded[0]?.blocks.map((block) => block.type)).toEqual([
'text',
'tool-call',
'tool-result'
])
})
})
@@ -1,5 +1,5 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { act, cleanup, render, screen } from '@testing-library/react'
import { useRef, type ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { KeybindingOverrides } from '../../../../../../shared/keybindings/types'
@@ -193,18 +193,6 @@ function findInput(): HTMLInputElement | null {
return inputs.find((input) => input === document.activeElement) ?? inputs[0] ?? null
}
function typeQuery(value: string): void {
const input = findInput()
if (!input) {
throw new Error('find bar is not open')
}
fireEvent.change(input, { target: { value } })
}
function status(): string | null | undefined {
return findInput()?.parentElement?.querySelector('[aria-live]')?.textContent
}
const TRANSCRIPT = (
<>
<p>alpha one</p>
@@ -231,26 +219,6 @@ afterEach(() => {
})
describe('native chat find', () => {
it('refocuses on Mod+F without moving the match, and keeps the query on reopen', () => {
const composer = composerHandle()
render(<Chat composer={composer} transcript={TRANSCRIPT} />)
pressModF(composer.element)
typeQuery('alpha')
press(findInput()!, 'Enter')
composer.element.focus()
expect(pressModF(composer.element).defaultPrevented).toBe(true)
const input = findInput()!
expect(document.activeElement).toBe(input)
expect([input.selectionStart, input.selectionEnd]).toEqual([0, 5])
expect(status()).toBe('2/2')
press(input, 'Escape')
expect(findInput()).toBeNull()
pressModF(composer.element)
expect(findInput()?.value).toBe('alpha')
})
it('falls back to the composer when the element find was opened from is gone', () => {
const composer = composerHandle()
const view = render(
@@ -134,7 +134,6 @@ function flowAboveSpacer(spacer: HTMLElement): number {
}
type LoadEarlier = () => Promise<NativeChatOlderPageResult>
const lands = (): LoadEarlier => vi.fn(async (): Promise<NativeChatOlderPageResult> => 'applied')
function paging({
messages,
@@ -359,23 +358,6 @@ describe('older history auto-load', () => {
}
})
it('stops, and shows neither status nor button, once history runs out', async () => {
const loadEarlier = lands()
const base = markers(100, 150)
const { rerender } = render(paging({ messages: base, loadEarlier }))
sentinelInRange = true
deliverIntersections()
rerender(paging({ messages: base, loadEarlier, loadingEarlier: true }))
await settle()
rerender(paging({ messages: [...markers(90, 100), ...base], loadEarlier, hasMore: false }))
deliverIntersections()
expect(loadEarlier).toHaveBeenCalledTimes(1)
expect(observations.size).toBe(0)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /load earlier/i })).not.toBeInTheDocument()
})
it('offers a manual load after a failed page, and resumes auto-loading once it succeeds', async () => {
const loadEarlier = vi
.fn<LoadEarlier>()
@@ -0,0 +1,172 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, cleanup, screen } from '@testing-library/react'
import { render } from '../../messages/actions/native-chat-tooltip-test-harness'
import { createRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
import { getDefaultSettings } from '../../../../../../shared/constants'
import { useAppStore } from '@/store'
import { NativeChatMessageList } from '../../NativeChatMessageList'
import type { NativeChatMessageListHandle } from '../../messages/actions/use-native-chat-reveal-latest'
import {
deliverResizes,
layout,
marker,
ROW_PITCH_PX,
scrollTranscript,
session,
stubLayout,
stubResizeObserver,
TRANSCRIPT_LENGTH
} from '../virtualization/native-chat-windowing-test-harness'
// Pacing is not this test's subject.
vi.mock('../../markdown/use-native-chat-paced-text', async (importOriginal) =>
(await import('../../markdown/native-chat-unpaced-text-fixture')).unpacedTextModule(
importOriginal
)
)
afterEach(cleanup)
function chat(
length: number,
isVisible: boolean,
{
ref,
readCurrent = true
}: { ref?: React.Ref<NativeChatMessageListHandle>; readCurrent?: boolean } = {}
): React.JSX.Element {
const messages: NativeChatMessage[] = Array.from({ length }, (_, index) => ({
...marker(index),
journalPosition: { sequence: index + 1, index: 0 }
}))
return (
<NativeChatMessageList
ref={ref}
session={{ ...session(messages), readCurrent }}
isVisible={isVisible}
isWorking={false}
expandSignal={false}
/>
)
}
describe('the "New" marker in the transcript', () => {
let paneShown = true
let restore: (() => void)[] = []
beforeEach(() => {
paneShown = true
vi.spyOn(document, 'hasFocus').mockReturnValue(true)
restore = [
stubLayout({ scrollGeometry: true, offsetChain: true, isVisible: () => paneShown }),
stubResizeObserver()
]
})
afterEach(() => {
for (const undo of restore.toReversed()) {
undo()
}
layout.measuredRowHeights = []
vi.restoreAllMocks()
})
// The window mounts only rows near the view; the marker's row is far from the end it opens at.
it('is drawn above the first row that came while the chat was hidden, however far back', () => {
const { rerender } = render(chat(TRANSCRIPT_LENGTH, true))
rerender(chat(TRANSCRIPT_LENGTH, false))
rerender(chat(TRANSCRIPT_LENGTH + 60, true))
const row = screen.getByRole('separator', { name: 'New' }).closest<HTMLElement>('[data-index]')
expect(row?.dataset.index).toBe(String(TRANSCRIPT_LENGTH))
})
it('tells a screen reader that new messages came, in a region that was already there', () => {
const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true))
const region = container.querySelector('[data-native-chat-scroll] ~ [aria-live="polite"]')
expect(region).toBeEmptyDOMElement()
rerender(chat(TRANSCRIPT_LENGTH, false))
rerender(chat(TRANSCRIPT_LENGTH + 60, true))
expect(region).toHaveTextContent('New messages arrived while you were away')
})
it('is neither drawn nor announced when the reader turned it off', () => {
const settings = useAppStore.getState().settings
useAppStore.setState({
settings: { ...getDefaultSettings('/tmp'), nativeChatMarkNewMessages: false }
})
try {
const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true))
rerender(chat(TRANSCRIPT_LENGTH, false))
rerender(chat(TRANSCRIPT_LENGTH + 60, true))
expect(screen.queryByRole('separator', { name: 'New' })).toBeNull()
expect(
container.querySelector('[data-native-chat-scroll] ~ [aria-live="polite"]')
).toBeEmptyDOMElement()
} finally {
useAppStore.setState({ settings })
}
})
it('goes once the reader sends something', () => {
const ref = createRef<NativeChatMessageListHandle>()
const { rerender } = render(chat(TRANSCRIPT_LENGTH, true, { ref }))
rerender(chat(TRANSCRIPT_LENGTH, false, { ref }))
rerender(chat(TRANSCRIPT_LENGTH + 60, true, { ref }))
expect(screen.getByRole('separator', { name: 'New' })).toBeInTheDocument()
act(() => ref.current?.revealLatest())
expect(screen.queryByRole('separator', { name: 'New' })).toBeNull()
})
describe('when the reader comes back to new rows', () => {
/** Catch up after restoring the hidden pane’s scroll position. */
function returnToNewRows(rerender: (ui: React.JSX.Element) => void, count = 60): void {
paneShown = false
rerender(chat(TRANSCRIPT_LENGTH, false, { readCurrent: false }))
paneShown = true
rerender(chat(TRANSCRIPT_LENGTH, true, { readCurrent: false }))
rerender(chat(TRANSCRIPT_LENGTH + count, true))
}
const scrollTop = (container: HTMLElement): number | undefined =>
container.querySelector('[data-native-chat-scroll]')?.scrollTop
it('brings a reader who was at the end to where the new rows begin', () => {
const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true))
returnToNewRows(rerender)
expect(scrollTop(container)).toBe(TRANSCRIPT_LENGTH * ROW_PITCH_PX)
})
it('keeps the reader where the new rows begin while a reply is still being drawn', async () => {
const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true))
returnToNewRows(rerender, 1)
const drawn: number[] = []
drawn[TRANSCRIPT_LENGTH] = 2_000
layout.measuredRowHeights = drawn
act(() => void deliverResizes())
await act(async () => {
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
})
expect(scrollTop(container)).toBe(TRANSCRIPT_LENGTH * ROW_PITCH_PX)
})
it('leaves a reader who was parked further up where they were', () => {
const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true))
const readingAt = 2_000
scrollTranscript(container, readingAt)
returnToNewRows(rerender)
expect(screen.getByRole('separator', { name: 'New' })).toBeInTheDocument()
expect(scrollTop(container)).toBe(readingAt)
})
})
})
@@ -0,0 +1,92 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { NativeChatNewRowsMarker } from './NativeChatNewRowsMarker'
import type { NativeChatNewRowsMarkerState as Marker } from './native-chat-new-rows-marker'
import { overrideLayoutProperty } from '../virtualization/native-chat-windowing-test-harness'
afterEach(cleanup)
function marker(overrides: Partial<Marker> = {}): Marker {
return {
key: 'answer',
place: 'above-row',
arriving: true,
onArrived: vi.fn(),
onDismiss: vi.fn(),
...overrides
}
}
const VIEWPORT_PX = 600
const ROW_TOP_PX = 1_000
let restoreLayout: (() => void)[] = []
/** Place the view bottom aboveMarkerPx short of a marker positioned intoRowPx within its row. */
function pane(
value: Marker,
{ intoRowPx = 0, aboveMarkerPx = 0 }: { intoRowPx?: number; aboveMarkerPx?: number } = {}
) {
const isRow = (element: HTMLElement): boolean => element.hasAttribute('data-index')
const isMarker = (element: HTMLElement): boolean => element.getAttribute('role') === 'separator'
const layout = (name: string, get: (this: HTMLElement) => unknown) =>
overrideLayoutProperty(name, { get })
restoreLayout = [
layout('clientHeight', () => VIEWPORT_PX),
layout('scrollTop', () => ROW_TOP_PX + intoRowPx - VIEWPORT_PX - aboveMarkerPx),
layout('offsetTop', function () {
return isRow(this) ? ROW_TOP_PX : isMarker(this) ? intoRowPx : 0
}),
layout('offsetParent', function () {
return isRow(this) || isMarker(this) ? this.parentElement : null
})
]
const onReveal = vi.fn()
const view = render(
<div data-native-chat-root="true">
<div data-native-chat-typing-redirect-ignore="true">
<input aria-label="Find in chat" />
</div>
<div data-native-chat-scroll>
<div data-index="3">
<NativeChatNewRowsMarker marker={value} onReveal={onReveal} />
</div>
</div>
<textarea aria-label="composer" />
</div>
)
return { ...view, onReveal }
}
describe('NativeChatNewRowsMarker', () => {
afterEach(() => {
for (const restore of restoreLayout) {
restore()
}
})
it('brings itself to the top when it sits too far down its row to show with it', () => {
const { onReveal } = pane(marker({ place: 'above-turn-bar' }), { intoRowPx: 500 })
expect(onReveal).toHaveBeenCalledWith(screen.getByRole('separator'))
})
it('does not pull the reader back to it once it has arrived', () => {
const { onReveal } = pane(marker({ arriving: false }))
expect(onReveal).not.toHaveBeenCalled()
})
it('goes once the reader writes to this chat, not to another pane or its find field', () => {
const value = marker()
pane(value)
const typeIn = (target: Element) =>
fireEvent(target, new Event('beforeinput', { bubbles: true }))
typeIn(document.body)
typeIn(screen.getByLabelText('Find in chat'))
expect(value.onDismiss).not.toHaveBeenCalled()
typeIn(screen.getByLabelText('composer'))
expect(value.onDismiss).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,84 @@
import { useEffect, useLayoutEffect, useRef } from 'react'
import { useTranslate } from '@/i18n/use-translate'
import { NATIVE_CHAT_BOTTOM_THRESHOLD_PX } from '../scroll/native-chat-autoscroll'
import type { NativeChatNewRowsMarkerState } from './native-chat-new-rows-marker'
import { nativeChatScrollOffsetWithin } from '../virtualization/use-native-chat-viewport-align'
/** Fields in the pane that take text for something other than the conversation. */
const NOT_THE_CONVERSATION = '[data-native-chat-typing-redirect-ignore="true"]'
export function NativeChatNewRowsMarker({
marker: { arriving, onArrived, onDismiss },
onReveal
}: {
marker: NativeChatNewRowsMarkerState
/** Scrolls a transcript element to the top of the view, and stops following the end. */
onReveal: (element: HTMLElement) => void
}): React.JSX.Element {
const t = useTranslate()
const ref = useRef<HTMLDivElement>(null)
const label = t('components.native-chat.newRowsMarker', 'New')
useLayoutEffect(() => {
if (!arriving) {
return
}
onArrived()
const marker = ref.current
const row = marker?.closest<HTMLElement>('[data-index]')
const scroller = row?.closest<HTMLElement>('[data-native-chat-scroll]')
if (!marker || !row || !scroller) {
return
}
const top = nativeChatScrollOffsetWithin(marker, scroller)
// Preserve a reader parked above new rows; replies can still be short while paced rendering catches up.
if (
top === null ||
top - (scroller.scrollTop + scroller.clientHeight) > NATIVE_CHAT_BOTTOM_THRESHOLD_PX
) {
return
}
// Reveal the prompt’s row unless it would leave the marker too low in the viewport.
const intoRow = top - (nativeChatScrollOffsetWithin(row, scroller) ?? top)
onReveal(intoRow < scroller.clientHeight / 2 ? row : marker)
}, [arriving, onArrived, onReveal])
useEffect(() => {
const pane = ref.current?.closest('[data-native-chat-root]')
// Only conversation input dismisses the marker; Find and other unrelated fields do not.
const onInput = (event: Event): void => {
if (!(event.target instanceof Element && event.target.closest(NOT_THE_CONVERSATION))) {
onDismiss()
}
}
pane?.addEventListener('beforeinput', onInput)
return () => pane?.removeEventListener('beforeinput', onInput)
}, [onDismiss])
return (
<div
ref={ref}
role="separator"
aria-label={label}
className="flex items-center gap-3 text-2xs font-semibold uppercase tracking-[0.05em] text-chat-unread transition-opacity duration-300 ease-out starting:opacity-0 motion-reduce:transition-none"
>
<span>{label}</span>
<span aria-hidden className="h-px flex-1 bg-chat-unread/50" />
</div>
)
}
/** Keep the live region mounted before inserting text so screen readers announce it. */
export function NativeChatNewRowsAnnouncement({ marked }: { marked: boolean }): React.JSX.Element {
const t = useTranslate()
return (
<div aria-live="polite" className="sr-only">
{marked
? t(
'components.native-chat.newRowsAnnouncement',
'New messages arrived while you were away'
)
: null}
</div>
)
}
@@ -0,0 +1,355 @@
// @vitest-environment happy-dom
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
import { buildNativeChatTranscriptSlots } from '../../conversation/slots/native-chat-transcript-slots'
import {
nativeChatNewRowsMarkerPlacement,
useNativeChatNewRowsMarker
} from './native-chat-new-rows-marker'
const at = (sequence: number) => ({ sequence, index: 0 })
/** A row the journal placed at `sequence`; null for one it has not (a terminal-backed chat's). */
function row(
id: string,
sequence: number | null,
role: NativeChatMessage['role'] = 'assistant',
text = id
): NativeChatMessage {
return {
id,
role,
blocks: [{ type: 'text', text }],
timestamp: 1,
source: 'transcript',
...(sequence === null ? {} : { journalPosition: at(sequence) })
}
}
type Turn = { working?: boolean; worked?: number; expanded?: boolean }
function slotsOf(
messages: NativeChatMessage[],
{ working = false, worked, expanded = false }: Turn = {}
) {
const turnKey = working || worked !== undefined ? 'prompt' : undefined
return buildNativeChatTranscriptSlots({
messages,
turnKeys: messages.map(() => turnKey),
liveTurnKey: working ? turnKey : undefined,
receipts: new Map(),
turnStatuses: {
active: null,
completedByTurn:
worked === undefined
? {}
: { prompt: { startedAt: null, thinking: false, workedSeconds: worked } }
},
turnDiffs: new Map(),
expandedTurnKeys: new Set(expanded && turnKey ? [turnKey] : []),
isWorking: working,
lifecycleWorking: working
})
}
const SEEN = [row('prompt', 1, 'user'), row('reply', 2)]
const LATER = [...SEEN, row('answer', 3), row('more', 4)]
const ASKED = [row('prompt', 1, 'user')]
const DONE = [...ASKED, row('step', 2), row('answer', 3)]
const missed = (key: string, after: number, through: number) => ({
key,
after: at(after),
through: at(through)
})
describe('where the "New" marker draws', () => {
it('is above the first row that came while the reader was away', () => {
expect(nativeChatNewRowsMarkerPlacement(slotsOf(LATER), missed('answer', 2, 4))).toEqual({
key: 'answer',
place: 'above-row'
})
})
it("is above the turn bar when only that bar parts the row from the reader's prompt", () => {
const asked = [row('prompt', 1, 'user'), row('answer', 2)]
expect(
nativeChatNewRowsMarkerPlacement(slotsOf(asked, { worked: 17 }), missed('answer', 1, 2))
).toEqual({ key: 'prompt', place: 'above-turn-bar' })
})
it('stays under the rows of an opened turn the reader had already seen', () => {
expect(
nativeChatNewRowsMarkerPlacement(
slotsOf(DONE, { worked: 17, expanded: true }),
missed('answer', 2, 3)
)
).toEqual({ key: 'answer', place: 'above-row' })
})
it('is above the bar of a turn the agent opened, whether the turn is open or shut', () => {
const turn = DONE.slice(1)
for (const expanded of [false, true]) {
expect(
nativeChatNewRowsMarkerPlacement(
slotsOf(turn, { worked: 17, expanded }),
missed('answer', 1, 3)
)
).toEqual({ key: 'step', place: 'above-row' })
}
})
it('is absent when nothing came, or the row that did is gone', () => {
expect(nativeChatNewRowsMarkerPlacement(slotsOf(LATER), null)).toBeUndefined()
expect(nativeChatNewRowsMarkerPlacement(slotsOf(SEEN), missed('answer', 2, 4))).toBeUndefined()
})
})
describe('useNativeChatNewRowsMarker', () => {
let hasFocus: ReturnType<typeof vi.spyOn>
beforeEach(() => {
hasFocus = vi.spyOn(document, 'hasFocus').mockReturnValue(true)
})
afterEach(() => hasFocus.mockRestore())
type ChatProps = {
messages: NativeChatMessage[]
showing: boolean
waiting?: NativeChatMessage[]
turn?: Turn
}
function chat(messages: NativeChatMessage[], turn?: Turn) {
const initialProps: ChatProps = { messages, showing: true }
return renderHook(
(props: ChatProps) =>
useNativeChatNewRowsMarker(
slotsOf(props.messages, props.turn ?? turn),
slotsOf(props.waiting ?? []),
props.showing
),
{ initialProps }
)
}
function leaveAndReturn(left: NativeChatMessage[], onReturn: NativeChatMessage[], turn?: Turn) {
const view = chat(left, turn)
view.rerender({ messages: left, showing: false })
view.rerender({ messages: onReturn, showing: true })
return view
}
it('marks nothing that arrives while the reader is looking', () => {
const view = chat(SEEN)
view.rerender({ messages: LATER, showing: true })
expect(view.result.current.marker).toBeUndefined()
})
it('marks what a hidden chat is handed when the reader comes back to it', () => {
expect(leaveAndReturn(SEEN, LATER).result.current.marker?.key).toBe('answer')
})
it("is never above the reader's own prompt", () => {
const sent = [...SEEN, row('next-prompt', 3, 'user'), row('answer', 4)]
expect(leaveAndReturn(SEEN, sent).result.current.marker?.key).toBe('answer')
})
it('marks nothing the reader watches arrive after missing nothing', () => {
const view = leaveAndReturn(SEEN, SEEN)
view.rerender({ messages: LATER, showing: true })
expect(view.result.current.marker).toBeUndefined()
})
it('marks what came while the window was in the background', () => {
const view = chat(SEEN)
hasFocus.mockReturnValue(false)
act(() => {
window.dispatchEvent(new Event('blur'))
})
view.rerender({ messages: LATER, showing: true })
hasFocus.mockReturnValue(true)
act(() => {
window.dispatchEvent(new Event('focus'))
})
expect(view.result.current.marker?.key).toBe('answer')
})
it('goes once the reader answers', () => {
const view = leaveAndReturn(SEEN, LATER)
act(() => view.result.current.dismiss())
expect(view.result.current.marker).toBeUndefined()
})
it('does not appear when the reader answered before the chat had caught up', () => {
const view = chat(SEEN)
view.rerender({ messages: SEEN, showing: false })
act(() => view.result.current.dismiss())
view.rerender({ messages: LATER, showing: true })
expect(view.result.current.marker).toBeUndefined()
})
it('marks the first reply to a chat that held no row the journal had placed', () => {
const sending = [row('prompt', null, 'user')]
const view = leaveAndReturn(sending, [row('prompt', 1, 'user'), row('answer', 2)])
expect(view.result.current.marker?.key).toBe('answer')
})
it('is arriving on the return, until the row that draws it has brought it into view', () => {
const view = leaveAndReturn(SEEN, LATER)
expect(view.result.current.marker?.arriving).toBe(true)
act(() => view.result.current.marker?.onArrived())
expect(view.result.current.marker).toMatchObject({ key: 'answer', arriving: false })
})
it('stays where it is through another look away, until the reader answers', () => {
const view = leaveAndReturn(SEEN, LATER)
act(() => view.result.current.marker?.onArrived())
view.rerender({ messages: LATER, showing: false })
expect(view.result.current.marker?.key).toBe('answer')
view.rerender({ messages: [...LATER, row('newer', 5)], showing: true })
expect(view.result.current.marker).toMatchObject({ key: 'answer', arriving: false })
})
it('marks the next time away afresh once the reader has answered', () => {
const view = leaveAndReturn(SEEN, LATER)
act(() => view.result.current.dismiss())
view.rerender({ messages: LATER, showing: false })
view.rerender({ messages: [...LATER, row('newer', 5)], showing: true })
expect(view.result.current.marker).toMatchObject({ key: 'newer', arriving: true })
})
it('marks the next time away afresh when the row it marked has gone', () => {
const view = leaveAndReturn(SEEN, LATER)
view.rerender({ messages: SEEN, showing: true })
expect(view.result.current.marker).toBeUndefined()
view.rerender({ messages: SEEN, showing: false })
view.rerender({ messages: [...SEEN, row('newer', 5)], showing: true })
expect(view.result.current.marker?.key).toBe('newer')
})
it('marks a message that was held behind the running turn once it joins the transcript', () => {
const view = chat(SEEN)
view.rerender({ messages: SEEN, showing: false })
view.rerender({ messages: SEEN, showing: true, waiting: [row('held', 3)] })
expect(view.result.current.marker).toBeUndefined()
// The turn writes on in front of the reader, then the handover places the message after that.
view.rerender({ messages: [...SEEN, row('live', 4)], showing: true, waiting: [row('held', 3)] })
expect(view.result.current.marker).toBeUndefined()
view.rerender({ messages: [...SEEN, row('live', 4), row('held', 5)], showing: true })
expect(view.result.current.marker?.key).toBe('held')
})
it('stays above a queued message while the turn writes on ahead of it', () => {
const queued: NativeChatMessage = { ...row('held', 3), queued: true }
const view = leaveAndReturn(SEEN, [...SEEN, queued])
expect(view.result.current.marker?.key).toBe('held')
view.rerender({ messages: [...SEEN, row('live', 4), queued], showing: true })
expect(view.result.current.marker?.key).toBe('held')
})
it('keeps its place when the reader opens the turn that came while they were away', () => {
const view = leaveAndReturn(ASKED, DONE, { worked: 17 })
expect(view.result.current.marker).toMatchObject({ key: 'prompt', place: 'above-turn-bar' })
view.rerender({ messages: DONE, showing: true, turn: { worked: 17, expanded: true } })
expect(view.result.current.marker).toMatchObject({ key: 'prompt', place: 'above-turn-bar' })
})
it('stays through another look away after the reader shuts the turn they opened', () => {
const shut = { worked: 17 }
const view = leaveAndReturn(ASKED, DONE, { worked: 17, expanded: true })
view.rerender({ messages: DONE, showing: true, turn: shut })
view.rerender({ messages: DONE, showing: false, turn: shut })
view.rerender({ messages: DONE, showing: true, turn: shut })
expect(view.result.current.marker).toMatchObject({ key: 'prompt', place: 'above-turn-bar' })
})
describe('a reply still being written when the reader left', () => {
const begun = [row('prompt', 1, 'user'), row('reply', 2, 'assistant', 'The plan')]
const grown = [row('prompt', 1, 'user'), row('reply', 2, 'assistant', 'The plan has parts.')]
const marked = (onReturn: NativeChatMessage[]) =>
leaveAndReturn(begun, onReturn, { working: true }).result.current.marker?.key
it('is marked new when it grew while they were away', () => {
expect(marked(grown)).toBe('reply')
})
it('is not marked when it is as they left it', () => {
expect(marked(begun)).toBeUndefined()
})
it('gives way to the next row when it is as they left it', () => {
expect(marked([...begun, row('more', 3)])).toBe('more')
})
it('is marked new when it grew with no row placed before it', () => {
const alone = [row('reply', 2, 'assistant', 'The plan')]
const grownAlone = [row('reply', 2, 'assistant', 'The plan has parts.')]
const view = leaveAndReturn(alone, grownAlone, { working: true })
expect(view.result.current.marker?.key).toBe('reply')
})
describe('with a follow-up delivered into the turn after it', () => {
const followUp = row('follow-up', 3, 'user')
const marked = (onReturn: NativeChatMessage[]) =>
leaveAndReturn([...begun, followUp], onReturn, { working: true }).result.current.marker?.key
it('is still marked new when it grew', () => {
expect(marked([...grown, followUp])).toBe('reply')
})
it('gives way to what answers the follow-up when it is as they left it', () => {
expect(marked([...begun, followUp, row('answer', 4)])).toBe('answer')
})
it('marks nothing when nothing changed', () => {
expect(marked([...begun, followUp])).toBeUndefined()
})
})
describe('with a message held behind the turn, placed after it', () => {
const markedWith = (held: NativeChatMessage, onReturn: NativeChatMessage[]) => {
const view = chat(begun, { working: true })
view.rerender({ messages: begun, showing: true, waiting: [held] })
view.rerender({ messages: begun, showing: false, waiting: [held] })
view.rerender({ messages: onReturn, showing: true, waiting: [held] })
return view.result.current.marker?.key
}
it('is still marked new when it grew', () => {
expect(markedWith(row('held', 3, 'user'), grown)).toBe('reply')
})
it('marks nothing when neither it nor the held message changed', () => {
const fromAgent: NativeChatMessage = {
...row('held', 3, 'user'),
from: {
kind: 'agent',
senders: [
{
party: { address: 'term_peer', terminalHandle: 'term_peer', orcaSessionId: null },
name: 'Claude'
}
],
orchestration: null
}
}
// Seen while it waited, it is not news once the turn ends and it joins the transcript.
expect(markedWith(fromAgent, [...begun, fromAgent])).toBeUndefined()
})
})
})
it('marks nothing in a chat read from a terminal, whose rows the journal never placed', () => {
const view = leaveAndReturn([row('a', null)], [row('a', null), row('b', null)])
expect(view.result.current.marker).toBeUndefined()
})
})
@@ -0,0 +1,211 @@
// Mark the first row that arrived or kept growing while the reader was away.
import { useCallback, useMemo, useState } from 'react'
import { useOrcaWindowForegroundFocused } from '@/hooks/use-orca-window-foreground-focused'
import { compareAgentJournalPositions } from '../../../../../../shared/agent-session/journal/agent-session-journal-position'
import type { AgentJournalPosition } from '../../../../../../shared/agent-session/journal/agent-session-journal-types'
import { useAppStore } from '@/store'
import { nativeChatMarksNewMessages } from '../../../../../../shared/native-chat/native-chat-appearance-settings'
import {
nativeChatSlotIndexOf,
nativeChatSlotKey
} from '../../conversation/slots/native-chat-transcript-slot-selection'
import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-chat-transcript-slots'
/** Use journal positions for conversation rows, including folded-turn bars; terminal-backed rows have none and remain unmarked. */
function rowPosition(slot: NativeChatTranscriptSlot): AgentJournalPosition | undefined {
return slot.kind === 'message' && slot.depth === 0 && (slot.drawsMessage || slot.statusAbove)
? slot.message.journalPosition
: undefined
}
/** Before every row the journal places: what the reader has read to when no row precedes. */
const BEFORE_EVERY_ROW: AgentJournalPosition = { sequence: -1, index: 0 }
/** Where a reader who looks away now has read to, and the reply the agent is still writing. */
type NativeChatLeftAt = {
/** The newest row there was, as a position: that row may have folded away by the return. */
position: AgentJournalPosition
/** A growing reply counts as missed from the position immediately before it. */
writing: { key: string; size: number; before: AgentJournalPosition } | null
}
function rowSize(slot: NativeChatTranscriptSlot): number {
return slot.kind === 'message'
? JSON.stringify((slot.workRun ?? [slot.message]).map((message) => message.blocks)).length
: 0
}
function newestRowPosition(
slots: readonly NativeChatTranscriptSlot[],
limit?: AgentJournalPosition
): AgentJournalPosition {
let newest = BEFORE_EVERY_ROW
for (const slot of slots) {
const at = rowPosition(slot)
if (
at &&
(!limit || compareAgentJournalPositions(at, limit) < 0) &&
compareAgentJournalPositions(at, newest) > 0
) {
newest = at
}
}
return newest
}
function nativeChatLeftAt(
slots: readonly NativeChatTranscriptSlot[],
waitingSlots: readonly NativeChatTranscriptSlot[]
): NativeChatLeftAt {
const all = [...slots, ...waitingSlots]
// Later user prompts or held sends do not stop the turn’s latest assistant row from growing.
const writer = slots.findLast(
(slot) =>
slot.kind === 'message' &&
slot.activeTurnIsWorking &&
slot.message.role !== 'user' &&
rowPosition(slot) !== undefined
)
const at = writer && rowPosition(writer)
const writing = at
? { key: nativeChatSlotKey(writer), size: rowSize(writer), before: newestRowPosition(all, at) }
: null
return { position: newestRowPosition(all), writing }
}
/** The first row that came while the reader was away, and the journal stretch it came in. */
export type NativeChatMissedRows = {
/** The row, not a position: a queued message is placed again when it is handed over. */
key: string
after: AgentJournalPosition
/** The newest row on the return: what is written after it was watched arriving. */
through: AgentJournalPosition
}
function isMissedRow(
slot: NativeChatTranscriptSlot,
after: AgentJournalPosition,
through: AgentJournalPosition
): boolean {
const at = rowPosition(slot)
return (
at !== undefined &&
compareAgentJournalPositions(at, after) > 0 &&
compareAgentJournalPositions(at, through) <= 0 &&
(slot.kind !== 'message' || slot.message.role !== 'user' || slot.message.from !== undefined)
)
}
function nativeChatMissedRows(
slots: readonly NativeChatTranscriptSlot[],
{ position, writing }: NativeChatLeftAt
): NativeChatMissedRows | null {
const row = writing && slots.find((slot) => nativeChatSlotKey(slot) === writing.key)
const after = writing && !(row && rowSize(row) === writing.size) ? writing.before : position
const through = newestRowPosition(slots)
const first = slots.find((slot) => isMissedRow(slot, after, through))
return first ? { key: nativeChatSlotKey(first), after, through } : null
}
export type NativeChatNewRowsMarkerPlacement = {
/** Key of the row the marker draws in. */
key: string
place: 'above-row' | 'above-turn-bar'
}
export type NativeChatNewRowsMarkerState = NativeChatNewRowsMarkerPlacement & {
/** The reader has just come back: bring the marker into view, once. */
arriving: boolean
onArrived: () => void
onDismiss: () => void
}
/** Place above the first missed row, or its turn bar when the two lines would otherwise touch. */
export function nativeChatNewRowsMarkerPlacement(
slots: readonly NativeChatTranscriptSlot[],
missed: NativeChatMissedRows | null
): NativeChatNewRowsMarkerPlacement | undefined {
if (missed === null) {
return undefined
}
const { key, after, through } = missed
// Opening a folded turn draws missed rows above the one marked while it was shut.
const index = slots.findIndex(
(slot) => nativeChatSlotKey(slot) === key || isMissedRow(slot, after, through)
)
const first = slots[index]
if (!first) {
return undefined
}
const before = slots[index - 1]
return before?.kind === 'message' &&
before.status &&
!before.statusAbove &&
!before.turnDiff &&
!before.openedPullRequests
? { key: nativeChatSlotKey(before), place: 'above-turn-bar' }
: { key: nativeChatSlotKey(first), place: 'above-row' }
}
export function useNativeChatNewRowsMarker(
slots: readonly NativeChatTranscriptSlot[],
/** Rows held behind the running turn: seen and missed like any other, drawn outside `slots`. */
waitingSlots: readonly NativeChatTranscriptSlot[],
/** The pane is the one showing, and shows what the host holds now. */
isShowingLatest: boolean
): {
marker: NativeChatNewRowsMarkerState | undefined
/** The slot drawing the marker, or -1. */
index: number
/** The reader answered the conversation, so nothing in it is news to them. */
dismiss: () => void
} {
// Off tracks nothing, so nothing is ever marked.
const enabled = useAppStore((state) => nativeChatMarksNewMessages(state.settings))
const focused = useOrcaWindowForegroundFocused(enabled && isShowingLatest)
const watching = !enabled || focused
const [seen, setSeen] = useState<{
watching: boolean
/** While the reader is away: where they had read to. */
left: NativeChatLeftAt | null
/** Stands until the reader answers. */
missed: NativeChatMissedRows | null
arriving: boolean
}>({ watching, left: null, missed: null, arriving: false })
if (!enabled) {
if (!seen.watching || seen.left !== null || seen.missed !== null) {
setSeen({ watching, left: null, missed: null, arriving: false })
}
} else if (seen.watching !== watching) {
const all = [...slots, ...waitingSlots]
if (watching) {
const missed = seen.left ? nativeChatMissedRows(all, seen.left) : seen.missed
setSeen({ watching, left: null, missed, arriving: seen.left !== null && missed !== null })
} else {
// An unanswered marker whose row still stands is kept: the reader may be midway through it.
const marked = nativeChatNewRowsMarkerPlacement(all, seen.missed) !== undefined
setSeen({ ...seen, watching, left: marked ? null : nativeChatLeftAt(slots, waitingSlots) })
}
}
const { missed } = seen
const placement = useMemo(() => nativeChatNewRowsMarkerPlacement(slots, missed), [slots, missed])
const dismiss = useCallback(() => {
// Where they left as well: an answer sent before the chat has caught up settles that too.
setSeen((held) =>
held.missed === null && held.left === null ? held : { ...held, missed: null, left: null }
)
}, [])
const onArrived = useCallback(() => {
setSeen((held) => (held.arriving ? { ...held, arriving: false } : held))
}, [])
const { key, place } = placement ?? {}
const marker = useMemo(
() =>
key && place
? { key, place, arriving: seen.arriving, onArrived, onDismiss: dismiss }
: undefined,
[key, place, seen.arriving, onArrived, dismiss]
)
return { marker, index: nativeChatSlotIndexOf(slots, key), dismiss }
}
@@ -1,5 +1,5 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useEffect, useRef, useState } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -70,30 +70,6 @@ const preview = (): HTMLElement | null =>
document.querySelector<HTMLElement>('[data-slot="hover-card-content"]')
describe('message rail interaction', () => {
it('previews only the hovered tick: its message and the reply to it', async () => {
render(<Rail />)
fireEvent.pointerEnter(tick('Prompt 1'), { pointerType: 'mouse' })
await waitFor(() => expect(preview()).not.toBeNull())
expect(preview()?.textContent).toBe('Prompt 1Reply 1')
fireEvent.pointerEnter(tick('Prompt 0'), { pointerType: 'mouse' })
await waitFor(() => expect(preview()?.textContent).toBe('Prompt 0Reply 0'))
})
it('keeps focus where it was while a hover preview opens and closes', async () => {
render(<Rail />)
const composer = screen.getByRole('textbox')
composer.focus()
const rail = screen.getByRole('toolbar', { name: 'Your messages' })
fireEvent.pointerEnter(rail, { pointerType: 'mouse' })
fireEvent.pointerEnter(tick('Prompt 0'), { pointerType: 'mouse' })
await waitFor(() => expect(preview()).not.toBeNull())
expect(document.activeElement).toBe(composer)
fireEvent.pointerLeave(rail, { pointerType: 'mouse' })
await waitFor(() => expect(preview()).toBeNull())
expect(document.activeElement).toBe(composer)
})
it('is one tab stop on the current tick, walked by arrow keys, each previewing itself', async () => {
const user = userEvent.setup()
const select = vi.fn()
@@ -131,19 +107,4 @@ describe('message rail interaction', () => {
await user.keyboard('{ArrowDown}')
expect(document.activeElement).toBe(tick('Prompt 2'))
})
it.each([
[0, 7],
[1, 112],
[2, 2800]
])('forwards wheel delta mode %i', (deltaMode, expected) => {
const element = railScroller()
Object.defineProperty(element, 'clientHeight', { value: 400 })
render(<Rail scroller={element} />)
fireEvent.wheel(screen.getByRole('toolbar', { name: 'Your messages' }), {
deltaY: 7,
deltaMode
})
expect(element.scrollTop).toBe(expected)
})
})
@@ -21,10 +21,6 @@ vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({
vi.mock('@/lib/open-agent-message-sender', () => ({
openAgentMessageSender: unusedChatLeaves.openSender
}))
afterEach(() => {
expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled()
expect(unusedChatLeaves.openSender).not.toHaveBeenCalled()
})
import type {
AgentJournalItemBody,
AgentJournalRenderItem
@@ -176,7 +172,6 @@ describe('revealing a diff from a turn rollup', () => {
// The pinned tail holds the rollup; its target diff has scrolled out of the window.
scrollTranscript(container, 4000)
expect(screen.queryByRole('button', { name: /^Edited .*a\.ts(?:\s|$)/ })).toBeNull()
const mountedBefore = windowState(container).indexes.length
scrollTo.mockClear()
fireEvent.click(screen.getByRole('button', { name: /src\/a.ts/ }))
@@ -184,8 +179,6 @@ describe('revealing a diff from a turn rollup', () => {
expect(screen.getByText('Edited')).toBeInTheDocument()
expect(screen.getByText('after')).toBeInTheDocument()
expect(scrollTo).not.toHaveBeenCalled()
// The outcome reuses the bounded transcript window.
expect(windowState(container).indexes.length).toBeLessThanOrEqual(mountedBefore + 2)
})
})
@@ -8,6 +8,7 @@ import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-c
import type { NativeChatTranscriptWindow } from './use-native-chat-transcript-window'
import type { ReaderGesture } from '../scroll/native-chat-autoscroll'
import { NativeChatForwardedGestureContext } from '../scroll/native-chat-reader-scroll-input'
import type { NativeChatNewRowsMarkerState } from '../new-rows/native-chat-new-rows-marker'
import {
NativeChatReplyRevealsContext,
useNativeChatReplyReveals
@@ -19,12 +20,14 @@ export function NativeChatTranscriptItems({
loadedMessageIds,
context,
window,
newRowsMarker,
forwardGesture
}: {
slots: readonly NativeChatTranscriptSlot[]
loadedMessageIds: ReadonlySet<string>
context: NativeChatTranscriptRowContext
window: NativeChatTranscriptWindow
newRowsMarker?: NativeChatNewRowsMarkerState
/** A reader gesture a row's visual frame took before the transcript could see it. */
forwardGesture: (gesture: ReaderGesture) => void
}): React.JSX.Element {
@@ -44,7 +47,13 @@ export function NativeChatTranscriptItems({
<Fragment key={item.key}>
<div aria-hidden style={{ height: Math.max(0, item.start - previousEnd) }} />
<div data-index={item.index} ref={window.measureRow} className="flow-root w-full">
<NativeChatTranscriptRow slot={slot} context={context} />
<NativeChatTranscriptRow
slot={slot}
context={context}
newRowsMarker={
rowKeys[item.index] === newRowsMarker?.key ? newRowsMarker : undefined
}
/>
</div>
</Fragment>
)
@@ -9,20 +9,25 @@ export type NativeChatPinnedRowsInput = {
count: number
/** Mount reveal targets before their cards expand and report scroll positions. */
revealIndex?: number | null
/** Keep the New marker mounted so it can reveal itself and detect reader replies. */
newRowsMarkerIndex?: number | null
}
/** Pin the live tail for aria-live announcements and measured-height accuracy during streaming. */
export function nativeChatPinnedRowIndexes({
count,
revealIndex
revealIndex,
newRowsMarkerIndex
}: NativeChatPinnedRowsInput): ReadonlySet<number> {
const pinned = new Set<number>()
if (count <= 0) {
return pinned
}
pinned.add(count - 1)
if (revealIndex != null && revealIndex >= 0 && revealIndex < count) {
pinned.add(revealIndex)
for (const index of [revealIndex, newRowsMarkerIndex]) {
if (index != null && index >= 0 && index < count) {
pinned.add(index)
}
}
return pinned
}
@@ -54,6 +54,7 @@ export function useNativeChatTranscriptWindow({
slots,
isVisible,
revealIndex,
newRowsMarkerIndex,
typography = DEFAULT_ROW_TYPOGRAPHY
}: {
scrollRef: React.RefObject<HTMLDivElement | null>
@@ -61,6 +62,8 @@ export function useNativeChatTranscriptWindow({
isVisible: boolean
/** Slot the transcript was asked to reveal, or -1. */
revealIndex: number
/** Slot drawing the "New" marker, or -1. */
newRowsMarkerIndex?: number
/** Chat text scale; gap scales with the text size. */
typography?: NativeChatRowTypography
}): NativeChatTranscriptWindow {
@@ -71,8 +74,8 @@ export function useNativeChatTranscriptWindow({
const previousMeasurementKeysRef = useRef<ReadonlySet<string> | null>(null)
const retiredMeasurementCountRef = useRef(0)
const pinned = useMemo(
() => nativeChatPinnedRowIndexes({ count: slots.length, revealIndex }),
[slots.length, revealIndex]
() => nativeChatPinnedRowIndexes({ count: slots.length, revealIndex, newRowsMarkerIndex }),
[slots.length, revealIndex, newRowsMarkerIndex]
)
// Keep measured offsets through content-only growth to preserve the end anchor; rebuild only on structural changes.
// Encoded only when the slots change: scroll and range renders reuse it.
@@ -14,7 +14,10 @@ import { NativeChatShellEnvironmentSetting } from './NativeChatShellEnvironmentS
import { NativeChatIdleStopSetting } from './NativeChatIdleStopSetting'
import { SearchableSetting } from '../section-layout/SearchableSetting'
import { nativeChatQueueFollowUps } from '../../../../../shared/native-chat/input/native-chat-follow-up-behavior'
import { nativeChatScrollsToLatestOnSend } from '../../../../../shared/native-chat/native-chat-appearance-settings'
import {
nativeChatMarksNewMessages,
nativeChatScrollsToLatestOnSend
} from '../../../../../shared/native-chat/native-chat-appearance-settings'
import { SettingsSubsectionHeader, SettingsSwitchRow } from '../form-controls/SettingsFormControls'
import { getChatBehaviorEntriesByKey, getChatBehaviorTitle } from './chat-behavior-search'
import { getChatPermissionSearchEntry } from './chat-permission-search'
@@ -54,6 +57,7 @@ export function ChatBehaviorSetting({
...(hostContinuesUsageLimits ? [entries.autoContinueAfterUsageLimit] : []),
...(hostQueuesMessages ? [entries.queueFollowUps] : []),
entries.scrollToLatestOnSend,
entries.markNewMessages,
entries.linkPreviews,
entries.shellEnvironment
]
@@ -64,6 +68,7 @@ export function ChatBehaviorSetting({
const queueFollowUps = nativeChatQueueFollowUps(settings)
const autoContinueEnabled = settings.nativeChatAutoContinueAfterUsageLimit === true
const scrollToLatestOnSend = nativeChatScrollsToLatestOnSend(settings)
const markNewMessages = nativeChatMarksNewMessages(settings)
const linkPreviewsEnabled = settings.nativeChatLinkPreviews !== false
return (
<section id="chat-behavior" className="space-y-3">
@@ -162,6 +167,20 @@ export function ChatBehaviorSetting({
}
/>
</SearchableSetting>
<SearchableSetting
{...entries.markNewMessages}
id={entries.markNewMessages.targetSectionId}
forceVisible={forceVisible}
className="max-w-none"
>
<SettingsSwitchRow
label={entries.markNewMessages.title}
description={entries.markNewMessages.description}
checked={markNewMessages}
ariaLabel={entries.markNewMessages.title}
onChange={() => updateSettings({ nativeChatMarkNewMessages: !markNewMessages })}
/>
</SearchableSetting>
<SearchableSetting
{...entries.linkPreviews}
id={entries.linkPreviews.targetSectionId}
@@ -78,6 +78,18 @@ export const getChatBehaviorEntriesByKey = createLocalizedCatalog(() => ({
translate('components.settings.nativeChat.scrollToLatestOnSendSearchPosition', 'position')
]
},
markNewMessages: {
targetSectionId: 'chat-mark-new-messages',
title: translate(
'components.settings.nativeChat.markNewMessagesTitle',
'Mark new messages when returning to a chat'
),
description: translate(
'components.settings.nativeChat.markNewMessagesCopy',
'Coming back to a chat draws a New line above what arrived while you were away, and scrolls to it if you were reading the latest.'
),
keywords: [translate('components.settings.nativeChat.markNewMessagesSearchUnread', 'unread')]
},
linkPreviews: {
targetSectionId: 'chat-link-previews',
title: translate('components.settings.nativeChat.linkPreviewsTitle', 'Link previews'),
@@ -64,83 +64,6 @@ export function registerPtyConnectionTypedAgentIdentityTests(): void {
await restoreTerminalTestGlobals()
})
it('normalizes Pi-compatible remote runtime status to OMP after typed omp command', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
enableActiveRuntimeEnvironment()
const paneKey = makePaneKey('tab-1', LEAF_1)
const pane = createPane(1)
const transport = createMockTransport('remote:web-env-1@@pty-omp')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks)
)
sendTerminalInputThroughPane(pane, 'omp\r')
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
const onAgentStatus = createdTransportOptions[0]?.onAgentStatus as
| ((payload: { state: 'done'; prompt: string; agentType: 'pi' }) => void)
| undefined
if (!onTitleChange || !onAgentStatus) {
throw new Error('missing remote PTY callbacks')
}
onTitleChange('Pi ready', 'Pi ready')
onAgentStatus({
state: 'done',
prompt: '',
agentType: 'pi'
})
expect(transport.sendInput).toHaveBeenCalledWith('omp\r', 'query-reply')
expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'OMP ready')
expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', 'OMP ready')
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({
state: 'done',
agentType: 'omp'
})
})
it('drives runtime title, tab title, and renderer policy from one title decision', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks2 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const pane = createPane(1)
const transport = createMockTransport('pty-gemini')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks2)
)
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
if (!onTitleChange) {
throw new Error('missing title callback')
}
onTitleChange('✦ Gemini CLI', '✦ Gemini CLI')
// Display/runtime/tab title and the GPU gate all come from the same decision.
expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, '✦ Gemini CLI')
expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', '✦ Gemini CLI')
// Genuine Gemini under the default `auto` setting takes the DOM fallback.
expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, false)
})
it('keeps GPU enabled when a pane-scoped OMP owner emits a Gemini-looking title', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks3 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -222,311 +145,6 @@ export function registerPtyConnectionTypedAgentIdentityTests(): void {
expect(gpuCalls.every(([paneId]) => paneId !== 2)).toBe(true)
})
it('DOM-gates a genuine Gemini split pane even when the tab launched a non-Gemini agent', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks5 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
// The shared tab.launchAgent must not veto the renderer for a sibling pane.
mockStoreState = {
...mockStoreState,
tabsByWorktree: {
'wt-1': [{ id: 'tab-1', ptyId: 'tab-pty', launchAgent: 'omp' }]
}
} as StoreState
const pane1 = createPane(1)
const pane2 = createPane(2)
const transport1 = createMockTransport('pty-split-owner-1')
const transport2 = createMockTransport('pty-split-owner-2')
transportFactoryQueue.push(transport1, transport2)
const manager = createManager(2, 2)
connectPanePty(
pane1 as never,
manager as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks5)
)
connectPanePty(
pane2 as never,
manager as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks5)
)
await flushAsyncTicks()
const onTitleChange2 = createdTransportOptions[1]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
if (!onTitleChange2) {
throw new Error('missing title callback for split pane 2')
}
onTitleChange2('✦ Gemini CLI', '✦ Gemini CLI')
expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(2, false)
})
it('DOM-gates a genuine Gemini title in a pane whose launch agent was non-Gemini', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks6 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const pane = createPane(1)
const transport = createMockTransport('pty-reused-gemini')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
// Stale, never-cleared launch identity must not veto the renderer.
const deps = createDeps({ startup: { command: 'claude', launchAgent: 'claude' } })
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks6)
)
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
if (!onTitleChange) {
throw new Error('missing title callback')
}
onTitleChange('✦ Gemini CLI', '✦ Gemini CLI')
expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, false)
})
it('DOM-gates a genuine Gemini title when the only pane row is a done non-Gemini agent', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks7 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState = {
...mockStoreState,
agentStatusByPaneKey: {
[paneKey]: {
paneKey,
agentType: 'claude',
state: 'done',
prompt: '',
updatedAt: Date.now(),
stateStartedAt: Date.now(),
stateHistory: []
}
}
} as StoreState
const pane = createPane(1)
const transport = createMockTransport('pty-reused-done-row')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks7)
)
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
if (!onTitleChange) {
throw new Error('missing title callback')
}
onTitleChange('✦ Gemini CLI', '✦ Gemini CLI')
// A `done` row is a leftover from a prior agent, so it must not veto.
expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, false)
})
it('DOM-gates a genuine Gemini title when the only pane row is a stale non-Gemini agent', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks8 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const paneKey = makePaneKey('tab-1', LEAF_1)
const staleAt = Date.now() - 60 * 60 * 1000
mockStoreState = {
...mockStoreState,
agentStatusByPaneKey: {
[paneKey]: {
paneKey,
agentType: 'claude',
state: 'working',
prompt: '',
updatedAt: staleAt,
stateStartedAt: staleAt,
stateHistory: []
}
}
} as StoreState
const pane = createPane(1)
const transport = createMockTransport('pty-reused-stale-row')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks8)
)
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
if (!onTitleChange) {
throw new Error('missing title callback')
}
onTitleChange('✦ Gemini CLI', '✦ Gemini CLI')
// A stale working row (older than AGENT_STATUS_STALE_AFTER_MS) must not veto.
expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, false)
})
it('normalizes after shell word deletion edits a typed command to omp', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks9 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
enableActiveRuntimeEnvironment()
const paneKey = makePaneKey('tab-1', LEAF_1)
const pane = createPane(1)
const transport = createMockTransport('remote:web-env-1@@pty-omp-edited')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks9)
)
sendTerminalInputThroughPane(pane, 'pi \x17omp\r')
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
const onAgentStatus = createdTransportOptions[0]?.onAgentStatus as
| ((payload: { state: 'done'; prompt: string; agentType: 'pi' }) => void)
| undefined
if (!onTitleChange || !onAgentStatus) {
throw new Error('missing remote PTY callbacks')
}
onTitleChange('Pi ready', 'Pi ready')
onAgentStatus({
state: 'done',
prompt: '',
agentType: 'pi'
})
expect(transport.sendInput).toHaveBeenCalledWith('pi \x17omp\r', 'query-reply')
expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'OMP ready')
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({
state: 'done',
agentType: 'omp'
})
})
it('keeps Pi-compatible remote runtime status as Pi after typed pi command', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks10 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
enableActiveRuntimeEnvironment()
const paneKey = makePaneKey('tab-1', LEAF_1)
const pane = createPane(1)
const transport = createMockTransport('remote:web-env-1@@pty-pi')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks10)
)
sendTerminalInputThroughPane(pane, 'pi\r')
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
const onAgentStatus = createdTransportOptions[0]?.onAgentStatus as
| ((payload: { state: 'done'; prompt: string; agentType: 'pi' }) => void)
| undefined
if (!onTitleChange || !onAgentStatus) {
throw new Error('missing remote PTY callbacks')
}
onTitleChange('Pi ready', 'Pi ready')
onAgentStatus({
state: 'done',
prompt: '',
agentType: 'pi'
})
expect(transport.sendInput).toHaveBeenCalledWith('pi\r', 'query-reply')
expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'Pi ready')
expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', 'Pi ready')
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({
state: 'done',
agentType: 'pi'
})
})
it('does not infer shell ownership from prompts typed inside an existing Pi session', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks11 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
enableActiveRuntimeEnvironment()
const paneKey = makePaneKey('tab-1', LEAF_1)
const now = Date.now()
mockStoreState.agentStatusByPaneKey[paneKey] = {
state: 'done',
prompt: '',
agentType: 'pi',
paneKey,
terminalTitle: 'Pi ready',
updatedAt: now,
stateStartedAt: now,
stateHistory: []
}
mockStoreState.runtimePaneTitlesByTabId = { 'tab-1': { 1: 'Pi ready' } }
const pane = createPane(1)
const transport = createMockTransport('remote:web-env-1@@pty-pi-prompt')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks11)
)
sendTerminalInputThroughPane(pane, 'omp\r')
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
const onAgentStatus = createdTransportOptions[0]?.onAgentStatus as
| ((payload: { state: 'done'; prompt: string; agentType: 'pi' }) => void)
| undefined
if (!onTitleChange || !onAgentStatus) {
throw new Error('missing remote PTY callbacks')
}
onTitleChange('Pi ready', 'Pi ready')
onAgentStatus({
state: 'done',
prompt: '',
agentType: 'pi'
})
expect(transport.sendInput).toHaveBeenCalledWith('omp\r', 'query-reply')
expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'Pi ready')
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({
state: 'done',
agentType: 'pi',
terminalTitle: 'Pi ready'
})
})
it('does not infer shell ownership from prompts typed in a title-only Pi session', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks12 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -627,91 +245,6 @@ export function registerPtyConnectionTypedAgentIdentityTests(): void {
})
})
it('tracks cursor edits when inferring a typed omp command', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks14 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
enableActiveRuntimeEnvironment()
const paneKey = makePaneKey('tab-1', LEAF_1)
const pane = createPane(1)
const transport = createMockTransport('remote:web-env-1@@pty-cursor-edit')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks14)
)
sendTerminalInputThroughPane(pane, 'op\x1b[Dm\r')
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
const onAgentStatus = createdTransportOptions[0]?.onAgentStatus as
| ((payload: { state: 'done'; prompt: string; agentType: 'pi' }) => void)
| undefined
if (!onTitleChange || !onAgentStatus) {
throw new Error('missing remote PTY callbacks')
}
onTitleChange('Pi ready', 'Pi ready')
onAgentStatus({
state: 'done',
prompt: '',
agentType: 'pi'
})
expect(transport.sendInput).toHaveBeenCalledWith('op\x1b[Dm\r', 'query-reply')
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({
state: 'done',
agentType: 'omp'
})
})
it('tracks delete-key cursor edits when inferring a typed omp command', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks15 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
enableActiveRuntimeEnvironment()
const paneKey = makePaneKey('tab-1', LEAF_1)
const pane = createPane(1)
const transport = createMockTransport('remote:web-env-1@@pty-delete-edit')
transportFactoryQueue.push(transport)
const manager = createManager(1, 1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks15)
)
sendTerminalInputThroughPane(pane, 'ommp\x1b[D\x1b[D\x1b[3~\r')
await flushAsyncTicks()
const onTitleChange = createdTransportOptions[0]?.onTitleChange as
| ((title: string, rawTitle: string) => void)
| undefined
const onAgentStatus = createdTransportOptions[0]?.onAgentStatus as
| ((payload: { state: 'done'; prompt: string; agentType: 'pi' }) => void)
| undefined
if (!onTitleChange || !onAgentStatus) {
throw new Error('missing remote PTY callbacks')
}
onTitleChange('Pi ready', 'Pi ready')
onAgentStatus({
state: 'done',
prompt: '',
agentType: 'pi'
})
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({
state: 'done',
agentType: 'omp'
})
})
it('skips manual agent inference for large paste chunks', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks16 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -1,410 +0,0 @@
import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushAsyncTicks } from '../test-fixtures/pty-connection-test-async'
import {
createMockTransport,
createPane,
createManager,
type ConnectCallbacks,
type MockTransport
} from '../test-fixtures/pty-connection-test-pane-fixtures'
import {
buildPaneConnectionDeps,
type PtyConnectionAgentTitleMocks,
bindPaneAgentTitleMocks
} from '../test-fixtures/pty-connection-test-deps'
import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures'
import type { StoreState } from '../test-fixtures/pty-connection-test-store-state'
import {
installTerminalTestGlobals,
restoreTerminalTestGlobals
} from '../test-fixtures/pty-connection-test-environment'
import { mockPanePtyArgs } from '../test-fixtures/pty-connection-test-connect-mock-pane'
export function registerPtyConnectionHiddenCodexQueriesTests(): void {
let mockStoreState: StoreState
let transportFactoryQueue: MockTransport[] = []
let createdTransportOptions: Record<string, unknown>[] = []
let storeSubscribers: ((state: StoreState) => void)[] = []
function createDeps(overrides: Record<string, unknown> = {}) {
return buildPaneConnectionDeps(() => mockStoreState, overrides)
}
describe('connectPanePty', () => {
beforeEach(async () => {
vi.clearAllMocks()
transportFactoryQueue = []
createdTransportOptions = []
storeSubscribers = []
mockStoreState = createInitialStoreState(() => mockStoreState)
bindPtyConnectionTestMocks({
getState: () => mockStoreState,
getTransportQueue: () => transportFactoryQueue,
getTransportOptions: () => createdTransportOptions,
getStoreSubscribers: () => storeSubscribers,
setStoreSubscribers: (subscribers) => {
storeSubscribers = subscribers
}
})
await installTerminalTestGlobals()
})
afterEach(async () => {
await restoreTerminalTestGlobals()
})
it('keeps hidden Codex redraw floods off the live xterm path', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
...mockPanePtyArgs(
pane,
manager,
bindPaneAgentTitleMocks(
createDeps({
isVisibleRef: { current: false },
startup: { command: 'codex' }
}),
agentTitleMocks
)
)
)
await flushAsyncTicks(6)
vi.useFakeTimers()
try {
const hiddenCodexRedraw = `\x1b[?2026h\x1b[2J\x1b[H${'codex redraw '.repeat(8_000)}`
capturedDataCallback.current?.(hiddenCodexRedraw)
vi.advanceTimersByTime(50)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hiddenCodexRedraw)
expect(window.api.pty.getMainBufferSnapshot).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
binding.dispose()
})
it.each(['codex', 'sleep 30 && codex', 'sleep 30 && claude'])(
'keeps hidden %s terminal query chunks on the live xterm path',
async (command) => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks2 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
...mockPanePtyArgs(
pane,
manager,
bindPaneAgentTitleMocks(
createDeps({
isVisibleRef: { current: false },
startup: { command }
}),
agentTitleMocks2
)
)
)
await flushAsyncTicks(6)
capturedDataCallback.current?.('\x1b[c')
expect(pane.terminal.write).toHaveBeenCalledWith('\x1b[c', expect.any(Function))
binding.dispose()
}
)
it('keeps only coalesced hidden Codex terminal queries on the live xterm path', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks3 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
...mockPanePtyArgs(
pane,
manager,
bindPaneAgentTitleMocks(
createDeps({
isVisibleRef: { current: false },
startup: { command: 'codex' }
}),
agentTitleMocks3
)
)
)
await flushAsyncTicks(6)
const coalescedChunk = `\x1b[c\x1b[?2026h\x1b[2J\x1b[H${'codex redraw '.repeat(8_000)}`
capturedDataCallback.current?.(coalescedChunk)
expect(pane.terminal.write).toHaveBeenCalledWith('\x1b[c', expect.any(Function))
expect(pane.terminal.write).not.toHaveBeenCalledWith(coalescedChunk, expect.any(Function))
binding.dispose()
})
it('answers hidden OSC color queries directly inside a mixed capability-query burst', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks4 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
...mockPanePtyArgs(
pane,
manager,
bindPaneAgentTitleMocks(
createDeps({
isVisibleRef: { current: false },
startup: { command: 'codex' }
}),
agentTitleMocks4
)
)
)
await flushAsyncTicks(6)
const queryBurst = '\x1b[c\x1b]11;?\x1b\\\x1b[>q\x1b[14t\x1b[16t'
const coalescedChunk = `${queryBurst}\x1b[?2026h${'codex redraw '.repeat(8_000)}`
capturedDataCallback.current?.(coalescedChunk)
expect(transport.sendInput).toHaveBeenCalledWith('\x1b]11;rgb:1111/1111/1111\x1b\\')
expect(pane.terminal.write).toHaveBeenCalledWith(
'\x1b[c\x1b[>q\x1b[14t\x1b[16t',
expect.any(Function)
)
expect(pane.terminal.write).not.toHaveBeenCalledWith(coalescedChunk, expect.any(Function))
binding.dispose()
})
it('answers adjacent hidden Codex OSC color queries directly', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks5 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
...mockPanePtyArgs(
pane,
manager,
bindPaneAgentTitleMocks(
createDeps({
isVisibleRef: { current: false },
startup: { command: 'codex' }
}),
agentTitleMocks5
)
)
)
await flushAsyncTicks(6)
const queries = '\x1b]10;?\x1b\\\x1b]11;?\x1b\\'
capturedDataCallback.current?.(`${queries}startup frame\r\n`)
expect(transport.sendInput).toHaveBeenCalledWith('\x1b]10;rgb:eeee/eeee/eeee\x1b\\')
expect(transport.sendInput).toHaveBeenCalledWith('\x1b]11;rgb:1111/1111/1111\x1b\\')
expect(pane.terminal.write).not.toHaveBeenCalledWith(queries, expect.any(Function))
expect(pane.terminal.write).not.toHaveBeenCalledWith(
`${queries}startup frame\r\n`,
expect.any(Function)
)
binding.dispose()
})
it('keeps split hidden Codex terminal queries on the live xterm path', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks6 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
...mockPanePtyArgs(
pane,
manager,
bindPaneAgentTitleMocks(
createDeps({
isVisibleRef: { current: false },
startup: { command: 'codex' }
}),
agentTitleMocks6
)
)
)
await flushAsyncTicks(6)
capturedDataCallback.current?.('\x1b[')
capturedDataCallback.current?.(`c\x1b[?2026h${'codex redraw '.repeat(8_000)}`)
expect(pane.terminal.write).toHaveBeenCalledWith('\x1b[c', expect.any(Function))
expect(pane.terminal.write).not.toHaveBeenCalledWith(
`c\x1b[?2026h${'codex redraw '.repeat(8_000)}`,
expect.any(Function)
)
binding.dispose()
})
it('keeps hidden Codex terminal queries split after ESC on the live xterm path', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks7 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
...mockPanePtyArgs(
pane,
manager,
bindPaneAgentTitleMocks(
createDeps({
isVisibleRef: { current: false },
startup: { command: 'codex' }
}),
agentTitleMocks7
)
)
)
await flushAsyncTicks(6)
capturedDataCallback.current?.('\x1b')
capturedDataCallback.current?.(`[c\x1b[?2026h${'codex redraw '.repeat(8_000)}`)
expect(pane.terminal.write).toHaveBeenCalledWith('\x1b[c', expect.any(Function))
expect(pane.terminal.write).not.toHaveBeenCalledWith(
`[c\x1b[?2026h${'codex redraw '.repeat(8_000)}`,
expect.any(Function)
)
binding.dispose()
})
it('flushes pending hidden Codex query prefixes when the pane becomes visible', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks8 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const isVisibleRef = { current: false }
const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
...mockPanePtyArgs(
pane,
manager,
bindPaneAgentTitleMocks(
createDeps({
isVisibleRef,
startup: { command: 'codex' }
}),
agentTitleMocks8
)
)
)
try {
await flushAsyncTicks(6)
capturedDataCallback.current?.('\x1b')
isVisibleRef.current = true
capturedDataCallback.current?.('[c')
expect(pane.terminal.write).toHaveBeenCalledWith('\x1b[c', expect.any(Function))
} finally {
binding.dispose()
}
})
})
}
@@ -134,130 +134,6 @@ export function registerPtyConnectionVisibilityResumeSizeTests(): void {
}
}
it('re-asserts the current size when the PTY drifted from xterm', async () => {
vi.mocked(window.api.pty.getSize).mockResolvedValue({ cols: 80, rows: 24 })
const { binding, transport } = await connectResumablePane()
transport.resize.mockClear()
binding.noteVisibilityResume()
await flushAsyncTicks()
// xterm is 120x40 (createPane default), PTY reports 80x24 → re-assert.
expect(transport.resize).toHaveBeenCalledWith(120, 40, { claim: true })
})
it('does not fit during visibility-resume reassertion', async () => {
vi.mocked(window.api.pty.getSize).mockResolvedValue({ cols: 80, rows: 24 })
const { binding, transport, pane } = await connectResumablePane()
const fit = vi.fn(() => {
pane.terminal.cols = 132
pane.terminal.rows = 40
})
pane.fitAddon = {
...pane.fitAddon,
fit,
proposeDimensions: vi.fn(() => ({ cols: 132, rows: 40 }))
} as never
Object.defineProperty(pane.container, 'getBoundingClientRect', {
configurable: true,
value: () => ({ width: 1130, height: 688 })
})
transport.resize.mockClear()
binding.noteVisibilityResume()
await flushAsyncTicks()
expect(fit).not.toHaveBeenCalled()
expect(transport.resize).toHaveBeenCalledWith(120, 40, { claim: true })
})
it('re-asserts after observed pane geometry changes while visible', async () => {
const pane = createPane(2)
const observer = installObservedPane(pane)
try {
vi.mocked(window.api.pty.getSize).mockResolvedValue({ cols: 200, rows: 40 })
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks2 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-pane-2')
transportFactoryQueue.push(transport)
const manager = createManager(2)
const deps = createDeps({
restoredLeafId: LEAF_2,
paneTransportsRef: { current: new Map([[1, createMockTransport('pty-pane-1')]]) }
})
pane.terminal.cols = 82
pane.terminal.rows = 40
connectPanePty(
...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks2))
)
await flushAsyncTicks()
transport.resize.mockClear()
vi.mocked(window.api.pty.getSize).mockClear()
observer.trigger()
await flushAsyncTicks()
expect(window.api.pty.getSize).toHaveBeenCalledWith('pty-pane-2')
expect(transport.resize).toHaveBeenCalledWith(82, 40, { claim: true })
} finally {
observer.restore()
}
})
it('repairs stale xterm grid drift on foreground output even without a pane resize', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks3 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-pane-2')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-pane-2'
}
)
transportFactoryQueue.push(transport)
const manager = createManager(2)
const deps = createDeps({
restoredLeafId: LEAF_2,
paneTransportsRef: { current: new Map([[1, createMockTransport('pty-pane-1')]]) }
})
const pane = createPane(2)
let proposedGrid = { cols: 62, rows: 63 }
pane.terminal.cols = 62
pane.terminal.rows = 63
pane.fitAddon = {
...pane.fitAddon,
fit: vi.fn(() => {
pane.terminal.cols = proposedGrid.cols
pane.terminal.rows = proposedGrid.rows
}),
proposeDimensions: vi.fn(() => proposedGrid)
} as never
vi.mocked(window.api.pty.getSize).mockResolvedValue({ cols: 62, rows: 63 })
connectPanePty(
...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks3))
)
await flushAsyncTicks()
proposedGrid = { cols: 65, rows: 63 }
vi.mocked(pane.fitAddon.fit).mockClear()
transport.resize.mockClear()
vi.mocked(window.api.pty.getSize).mockClear()
expect(capturedDataCallback.current).not.toBeNull()
capturedDataCallback.current?.('\x1b[?2026hcodex redraw frame')
await flushAsyncTicks()
expect(pane.fitAddon.fit).toHaveBeenCalled()
expect(window.api.pty.getSize).toHaveBeenCalledWith('pty-pane-2')
expect(transport.resize).toHaveBeenCalledWith(65, 63, { claim: true })
})
async function connectStreamingDriftPane(): Promise<{
binding: { noteVisibilityResume: () => void }
transport: MockTransport
@@ -322,40 +198,6 @@ export function registerPtyConnectionVisibilityResumeSizeTests(): void {
}
}
it('defers settled grid drift repair on streaming output until a geometry signal', async () => {
const { binding, transport, fit, setProposedGrid, emitFrame } =
await connectStreamingDriftPane()
emitFrame('frame 1')
await vi.advanceTimersByTimeAsync(300)
setProposedGrid({ cols: 65, rows: 63 })
emitFrame('frame 2')
await vi.advanceTimersByTimeAsync(300)
expect(fit).not.toHaveBeenCalled()
binding.noteVisibilityResume()
emitFrame('frame 3')
await vi.advanceTimersByTimeAsync(50)
expect(fit).toHaveBeenCalled()
expect(transport.resize).toHaveBeenCalledWith(65, 63, { claim: true })
})
it('repairs grid drift after the settled backstop while output keeps streaming', async () => {
const { transport, fit, setProposedGrid, emitFrame } = await connectStreamingDriftPane()
emitFrame('frame 0')
await vi.advanceTimersByTimeAsync(10)
setProposedGrid({ cols: 65, rows: 63 })
for (let frame = 1; frame <= 4; frame += 1) {
await vi.advanceTimersByTimeAsync(290)
emitFrame(`frame ${frame}`)
}
await vi.advanceTimersByTimeAsync(50)
expect(fit).toHaveBeenCalled()
expect(transport.resize).toHaveBeenCalledWith(65, 63, { claim: true })
})
it('repairs grid drift with a trailing probe when output stops inside the settled interval', async () => {
const { transport, fit, setProposedGrid, emitFrame } = await connectStreamingDriftPane()
emitFrame('frame 1')
@@ -369,40 +211,6 @@ export function registerPtyConnectionVisibilityResumeSizeTests(): void {
expect(transport.resize).toHaveBeenCalledWith(65, 63, { claim: true })
})
it('pulls an armed settled trailing probe forward when a geometry signal restores the fast cadence', async () => {
const { binding, transport, fit, setProposedGrid, emitFrame } =
await connectStreamingDriftPane()
emitFrame('frame 1')
await vi.advanceTimersByTimeAsync(50)
setProposedGrid({ cols: 65, rows: 63 })
emitFrame('frame 2')
await vi.advanceTimersByTimeAsync(50)
binding.noteVisibilityResume()
await vi.advanceTimersByTimeAsync(50)
emitFrame('last frame')
await vi.advanceTimersByTimeAsync(50)
expect(fit).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(150)
expect(fit).toHaveBeenCalled()
expect(transport.resize).toHaveBeenCalledWith(65, 63, { claim: true })
})
it('keeps the fast probe cadence when the fit proposal is unavailable', async () => {
const { transport, fit, setProposedGrid, emitFrame } = await connectStreamingDriftPane()
setProposedGrid(undefined)
emitFrame('frame 1')
await vi.advanceTimersByTimeAsync(300)
setProposedGrid({ cols: 65, rows: 63 })
emitFrame('frame 2')
await vi.advanceTimersByTimeAsync(50)
expect(fit).toHaveBeenCalled()
expect(transport.resize).toHaveBeenCalledWith(65, 63, { claim: true })
})
it('skips foreground grid drift repair while mobile owns the PTY without a fit override', async () => {
const { setDriverForPty } = await import('@/lib/pane-manager/mobile-driver-state')
const { connectPanePty } = await import('../connect-pane-pty')
@@ -501,61 +309,6 @@ export function registerPtyConnectionVisibilityResumeSizeTests(): void {
}
})
it('updates the claiming desktop xterm before forwarding an observed viewport claim', async () => {
const originalDocument = globalThis.document
;(globalThis as { document?: Document }).document = {
visibilityState: 'visible',
hasFocus: vi.fn(() => true)
} as unknown as Document
globalThis.requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {
queueMicrotask(() => callback(0))
return 1
})
const { setFitOverride } = await import('@/lib/pane-manager/mobile-fit-overrides')
const pane = createPane(2)
const observer = installObservedPane(pane)
try {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks7 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-pane-2')
transportFactoryQueue.push(transport)
const manager = createManager(2)
const deps = createDeps({
restoredLeafId: LEAF_2,
paneTransportsRef: { current: new Map([[1, createMockTransport('pty-pane-1')]]) }
})
let proposedGrid = { cols: 120, rows: 40 }
pane.fitAddon = {
...pane.fitAddon,
proposeDimensions: vi.fn(() => proposedGrid)
} as never
connectPanePty(
...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks7))
)
await flushAsyncTicks()
observer.trigger()
await flushAsyncTicks()
setFitOverride('pty-pane-2', 'remote-desktop-fit', 80, 24)
proposedGrid = { cols: 70, rows: 30 }
vi.mocked(pane.terminal.resize).mockClear()
transport.resize.mockClear()
observer.trigger()
await flushAsyncTicks()
expect(pane.terminal.resize).toHaveBeenCalledWith(70, 30)
expect(transport.resize).toHaveBeenCalledTimes(1)
expect(transport.resize).toHaveBeenCalledWith(70, 30, { claim: true })
} finally {
setFitOverride('pty-pane-2', 'desktop-fit', 0, 0)
observer.restore()
globalThis.document = originalDocument
}
})
it('defers a remote-desktop viewport claim until structural replay completes', async () => {
const originalDocument = globalThis.document
;(globalThis as { document?: Document }).document = {
@@ -662,28 +415,6 @@ export function registerPtyConnectionVisibilityResumeSizeTests(): void {
}
})
it('does NOT re-assert when the PTY already matches xterm (no spurious SIGWINCH)', async () => {
vi.mocked(window.api.pty.getSize).mockResolvedValue({ cols: 120, rows: 40 })
const { binding, transport } = await connectResumablePane()
transport.resize.mockClear()
binding.noteVisibilityResume()
await flushAsyncTicks()
expect(transport.resize).not.toHaveBeenCalled()
})
it('re-asserts when the PTY size is unknown (cannot confirm synced)', async () => {
vi.mocked(window.api.pty.getSize).mockResolvedValue(null)
const { binding, transport } = await connectResumablePane()
transport.resize.mockClear()
binding.noteVisibilityResume()
await flushAsyncTicks()
expect(transport.resize).toHaveBeenCalledWith(120, 40, { claim: true })
})
it('queues re-asserted resizes while pane resize holds are active', async () => {
const originalCustomEvent = globalThis.CustomEvent
class MockCustomEvent<T> extends Event {
@@ -1,241 +0,0 @@
import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushAsyncTicks } from '../test-fixtures/pty-connection-test-async'
import {
LEAF_1,
createMockTransport,
createPane,
createManager,
type MockTransport
} from '../test-fixtures/pty-connection-test-pane-fixtures'
import {
buildPaneConnectionDeps,
type PtyConnectionAgentTitleMocks,
bindPaneAgentTitleMocks
} from '../test-fixtures/pty-connection-test-deps'
import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures'
import type { StoreState } from '../test-fixtures/pty-connection-test-store-state'
import {
installTerminalTestGlobals,
restoreTerminalTestGlobals
} from '../test-fixtures/pty-connection-test-environment'
export function registerPtyConnectionRuntimeOwnerSpawnRoutingTests(): void {
let mockStoreState: StoreState
let transportFactoryQueue: MockTransport[] = []
let createdTransportOptions: Record<string, unknown>[] = []
let storeSubscribers: ((state: StoreState) => void)[] = []
function createDeps(overrides: Record<string, unknown> = {}) {
return buildPaneConnectionDeps(() => mockStoreState, overrides)
}
describe('connectPanePty', () => {
beforeEach(async () => {
vi.clearAllMocks()
transportFactoryQueue = []
createdTransportOptions = []
storeSubscribers = []
mockStoreState = createInitialStoreState(() => mockStoreState)
bindPtyConnectionTestMocks({
getState: () => mockStoreState,
getTransportQueue: () => transportFactoryQueue,
getTransportOptions: () => createdTransportOptions,
getStoreSubscribers: () => storeSubscribers,
setStoreSubscribers: (subscribers) => {
storeSubscribers = subscribers
}
})
await installTerminalTestGlobals()
})
afterEach(async () => {
await restoreTerminalTestGlobals()
})
it('fails closed when the same SSH worktree id is projected by two HUBs', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const { createRemoteRuntimePtyTransport } =
await import('../../pty-transport/remote-runtime/remote-runtime-pty-transport')
const { createIpcPtyTransport } = await import('../../pty-transport/ipc/pty-transport')
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
worktreesByRepo: {
repo1: [
{
id: 'wt-1',
repoId: 'repo1',
path: '/srv/same-worktree',
hostId: 'ssh:same-private-target',
runtimeOwnerEnvironmentId: 'hub-a'
},
{
id: 'wt-1',
repoId: 'repo1',
path: '/srv/same-worktree',
hostId: 'ssh:same-private-target',
runtimeOwnerEnvironmentId: 'hub-b'
}
]
},
settings: {
...mockStoreState.settings,
activeRuntimeEnvironmentId: 'hub-a'
}
} as StoreState
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(
createDeps({ restoredPtyIdByLeafId: { [LEAF_1]: null } }) as never,
agentTitleMocks
)
)
await flushAsyncTicks()
expect(createRemoteRuntimePtyTransport).not.toHaveBeenCalled()
expect(createIpcPtyTransport).not.toHaveBeenCalled()
expect(window.api.ssh.connect).not.toHaveBeenCalled()
expect(window.api.ssh.needsPassphrasePrompt).not.toHaveBeenCalled()
})
it('fails a missing paired-client owner closed instead of creating a local PTY', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks2 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const { createRemoteRuntimePtyTransport } =
await import('../../pty-transport/remote-runtime/remote-runtime-pty-transport')
const { createIpcPtyTransport } = await import('../../pty-transport/ipc/pty-transport')
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
worktreesByRepo: {
repo1: [{ id: 'wt-1', repoId: 'repo1', path: '/srv/stale-worktree' }]
},
runtimeEnvironments: [{ id: 'hub-a' }, { id: 'hub-b' }],
runtimeEnvironmentCatalogHydrated: true,
settings: { ...mockStoreState.settings, activeRuntimeEnvironmentId: 'hub-a' }
} as StoreState
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(
createDeps({ restoredPtyIdByLeafId: { [LEAF_1]: null } }) as never,
agentTitleMocks2
)
)
await flushAsyncTicks()
expect(createRemoteRuntimePtyTransport).not.toHaveBeenCalled()
expect(createIpcPtyTransport).not.toHaveBeenCalled()
expect(window.api.ssh.connect).not.toHaveBeenCalled()
})
it('spawns fresh PTYs through the worktree owner runtime when focus differs', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks3 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const { createRemoteRuntimePtyTransport } =
await import('../../pty-transport/remote-runtime/remote-runtime-pty-transport')
const transport = createMockTransport('remote:owner-runtime@@terminal-1')
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: {
'wt-1': [{ id: 'tab-1', ptyId: null }]
},
repos: [
{
id: 'repo1',
connectionId: null,
displayName: 'orca',
executionHostId: 'runtime:owner-runtime'
}
],
settings: {
...mockStoreState.settings,
activeRuntimeEnvironmentId: 'focused-runtime'
}
} as StoreState
const pane = createPane(2)
const manager = createManager(2)
const deps = createDeps({
startup: {
command: "codex '--profile' 'recipe'",
launchAgent: 'codex',
launchConfig: { agentArgs: '--profile recipe', agentEnv: {} },
agentArgsOverride: '--profile recipe'
}
})
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks3)
)
expect(createRemoteRuntimePtyTransport).toHaveBeenCalledWith(
'owner-runtime',
expect.any(Object)
)
expect(createdTransportOptions[0]?.cwdFallback).toBeUndefined()
expect(createdTransportOptions[0]?.agentArgsOverride).toBe('--profile recipe')
expect(transport.connect).toHaveBeenCalled()
})
it('spawns fresh PTYs locally for explicitly local worktrees while a runtime is focused', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks4 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const { createRemoteRuntimePtyTransport } =
await import('../../pty-transport/remote-runtime/remote-runtime-pty-transport')
const { createIpcPtyTransport } = await import('../../pty-transport/ipc/pty-transport')
const transport = createMockTransport('pty-local-1')
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: {
'wt-1': [{ id: 'tab-1', ptyId: null }]
},
repos: [
{
id: 'repo1',
connectionId: null,
displayName: 'orca',
executionHostId: 'local'
}
],
settings: {
...mockStoreState.settings,
activeRuntimeEnvironmentId: 'focused-runtime'
}
} as StoreState
const pane = createPane(2)
const manager = createManager(2)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks4)
)
expect(createRemoteRuntimePtyTransport).not.toHaveBeenCalled()
expect(createIpcPtyTransport).toHaveBeenCalled()
expect(createdTransportOptions[0]).not.toHaveProperty('cwdFallback')
expect(transport.connect).toHaveBeenCalled()
})
})
}
@@ -145,140 +145,6 @@ export function registerPtyConnectionInterruptInferenceTests(): void {
}
)
it('clears stale working pane title after inferred interrupt applies', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks2 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const { resolveWorktreeStatus } = await import('@/lib/worktree-status')
vi.mocked(window.api.agentStatus.inferInterrupt).mockResolvedValue(true)
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
vi.setSystemTime(1_100)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState.runtimePaneTitlesByTabId = {
'tab-1': {
1: 'Codex working'
}
}
mockStoreState.agentStatusByPaneKey[paneKey] = {
state: 'working',
prompt: 'stop visible spinner',
updatedAt: 1_000,
stateStartedAt: 900,
agentType: 'custom-agent',
paneKey,
terminalTitle: 'Codex working',
stateHistory: []
}
const terminalTarget = createKeyboardEventTarget()
const pane = createPane(1)
;(pane.terminal as { element?: unknown }).element = terminalTarget.target
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
manager.getActivePane.mockReturnValue({ id: 1 })
const deps = createDeps({
setRuntimePaneTitle: vi.fn((tabId: string, paneId: number, title: string) => {
mockStoreState.runtimePaneTitlesByTabId = {
...mockStoreState.runtimePaneTitlesByTabId,
[tabId]: {
...mockStoreState.runtimePaneTitlesByTabId[tabId],
[paneId]: title
}
}
})
})
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks2)
)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
terminalTarget.dispatch(keyEvent({ key: 'c', ctrlKey: true }))
;(onDataHandler as unknown as (data: string) => void)('\x03')
await flushAsyncTicks()
vi.advanceTimersByTime(500)
await flushAsyncTicks()
expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'Terminal')
expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', 'Terminal')
expect(
resolveWorktreeStatus({
tabs: [{ id: 'tab-1', title: 'Codex working' }],
browserTabs: [],
ptyIdsByTabId: { 'tab-1': ['tab-pty'] },
runtimePaneTitlesByTabId: mockStoreState.runtimePaneTitlesByTabId,
hasPermission: false,
hasLiveWorking: false,
hasLiveDone: true,
hasRetainedDone: false
})
).toBe('done')
})
it('clears unchanged title-only working indicators after acknowledged interrupt input', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks3 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
vi.setSystemTime(1_100)
mockStoreState.runtimePaneTitlesByTabId = {
'tab-1': {
1: 'Codex working'
}
}
const terminalTarget = createKeyboardEventTarget()
const pane = createPane(1)
;(pane.terminal as { element?: unknown }).element = terminalTarget.target
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
manager.getActivePane.mockReturnValue({ id: 1 })
const deps = createDeps({
setRuntimePaneTitle: vi.fn((tabId: string, paneId: number, title: string) => {
mockStoreState.runtimePaneTitlesByTabId = {
...mockStoreState.runtimePaneTitlesByTabId,
[tabId]: {
...mockStoreState.runtimePaneTitlesByTabId[tabId],
[paneId]: title
}
}
})
})
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks3)
)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
terminalTarget.dispatch(keyEvent({ key: 'c', ctrlKey: true }))
;(onDataHandler as unknown as (data: string) => void)('\x03')
await flushAsyncTicks()
vi.advanceTimersByTime(500)
await flushAsyncTicks()
expect(window.api.agentStatus.inferInterrupt).not.toHaveBeenCalled()
expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'Terminal')
expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', 'Terminal')
})
it('does not clear title-only working indicators when interrupt writes are unacknowledged', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks4 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -374,42 +240,6 @@ export function registerPtyConnectionInterruptInferenceTests(): void {
})
})
it('marks bracketed paste as stale after acknowledged Ctrl+C input', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks6 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const { pasteTerminalText } = await import('../../input/paste/terminal-bracketed-paste')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
const pane = createPane(1)
pane.terminal.modes.bracketedPasteMode = true
const observedIgnoreValues: (boolean | undefined)[] = []
pane.terminal.paste.mockImplementation(() => {
observedIgnoreValues.push(pane.terminal.options.ignoreBracketedPasteMode)
})
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
connectPanePty(
pane as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks6)
)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as unknown as (data: string) => void)('\x03')
await flushAsyncTicks()
pasteTerminalText(pane.terminal as never, 'a69ce28e1d092e0c8825cd1a109ac36409962bc1')
expect(observedIgnoreValues).toEqual([true])
expect(pane.terminal.options.ignoreBracketedPasteMode).toBe(false)
})
it('infers captured Ctrl+C even when xterm emits an enhanced keyboard sequence', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks7 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -652,78 +482,6 @@ export function registerPtyConnectionInterruptInferenceTests(): void {
expect(window.api.agentStatus.inferInterrupt).not.toHaveBeenCalled()
})
it('removes agent status and pane title on PTY exit after inferred interrupt', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks11 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
vi.mocked(window.api.agentStatus.inferInterrupt).mockResolvedValue(true)
const transport = createMockTransport('tab-pty')
transportFactoryQueue.push(transport)
vi.useFakeTimers()
vi.setSystemTime(1_100)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState.runtimePaneTitlesByTabId = {
'tab-1': {
1: 'Codex working'
}
}
mockStoreState.agentStatusByPaneKey[paneKey] = {
state: 'working',
prompt: 'stop then exit',
updatedAt: 1_000,
stateStartedAt: 900,
agentType: 'custom-agent',
paneKey,
terminalTitle: 'Codex working',
stateHistory: []
}
const terminalTarget = createKeyboardEventTarget()
const pane = createPane(1)
;(pane.terminal as { element?: unknown }).element = terminalTarget.target
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const deps = createDeps()
connectPanePty(
pane as never,
createManager(1) as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks11)
)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
terminalTarget.dispatch(keyEvent({ key: 'c', ctrlKey: true }))
;(onDataHandler as unknown as (data: string) => void)('\x03')
await flushAsyncTicks()
await vi.advanceTimersByTimeAsync(500)
await flushAsyncTicks()
expect(window.api.agentStatus.inferInterrupt).toHaveBeenCalledWith({
paneKey,
baselineUpdatedAt: 1_000,
baselineStateStartedAt: 900,
baselinePrompt: 'stop then exit',
baselineAgentType: 'custom-agent',
intent: 'ctrl-c'
})
const onPtyExit = createdTransportOptions[0]?.onPtyExit as
| ((ptyId: string) => void)
| undefined
if (!onPtyExit) {
throw new Error('expected onPtyExit callback to be registered')
}
onPtyExit('tab-pty')
expect(deps.clearRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1)
expect(deps.clearTabPtyId).toHaveBeenCalledWith('tab-1', 'tab-pty')
expect(deps.setCacheTimerStartedAt).toHaveBeenCalledWith(paneKey, null)
expect(mockStoreState.removeAgentStatus).toHaveBeenCalledWith(paneKey)
})
it('ignores repeated and Alt-modified Escape input before accepting plain Escape', async () => {
const restoreUserAgent = temporarilySetNavigatorUserAgent('Mozilla/5.0 (X11; Linux x86_64)')
try {
@@ -63,89 +63,6 @@ export function registerPtyConnectionTerminalInputGatingTests(): void {
await restoreTerminalTestGlobals()
})
it('restores input to a Codex pane whose restart notice the user dismissed', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks4 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-live')
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'pty-live' }] },
ptyIdsByTabId: { 'tab-1': ['pty-live'] },
// Dismissal retains launch-account memory, so stale-input gating must inspect its marker rather than record existence.
codexRestartNoticeByPtyId: {
'pty-live': { previousAccountLabel: 'A', nextAccountLabel: 'B', dismissed: true }
}
}
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks4)
)
expect(onDataHandler).toBeDefined()
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as (data: string) => void)('a')
expect(transport.sendInput).toHaveBeenCalledWith('a', 'query-reply')
})
it('restores input through the tab fallback when the dismissed pane has no live PTY binding', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks5 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport(null)
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'pty-live' }] },
ptyIdsByTabId: { 'tab-1': ['pty-live'] },
codexRestartNoticeByPtyId: {
'pty-live': { previousAccountLabel: 'A', nextAccountLabel: 'B', dismissed: true }
}
}
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks5)
)
expect(onDataHandler).toBeDefined()
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as (data: string) => void)('a')
expect(transport.sendInput).toHaveBeenCalledWith('a', 'query-reply')
})
it('keeps a dismissed split pane typing while a sibling still holds the prompt', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks6 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -287,112 +204,6 @@ export function registerPtyConnectionTerminalInputGatingTests(): void {
expect(transport.sendInput).toHaveBeenCalledWith('a', 'query-reply')
})
it('keeps blocking input on a pane whose restart is requested but not yet run', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks9 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const transport = createMockTransport('pty-live')
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'pty-live' }] },
ptyIdsByTabId: { 'tab-1': ['pty-live'] },
// Queued restart retains the old account until relaunch, unlike dismissal.
codexRestartNoticeByPtyId: {
'pty-live': { previousAccountLabel: 'A', nextAccountLabel: 'B', restartRequested: true }
}
}
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks9)
)
expect(onDataHandler).toBeDefined()
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as (data: string) => void)('a')
expect(transport.sendInput).not.toHaveBeenCalled()
})
it('blocks input to stale Codex panes until they restart', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks10 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
vi.useFakeTimers()
vi.setSystemTime(1_100)
const transport = createMockTransport('pty-codex-stale')
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: {
'wt-1': [{ id: 'tab-1', ptyId: 'pty-codex-stale' }]
},
ptyIdsByTabId: {
'tab-1': ['pty-codex-stale']
},
codexRestartNoticeByPtyId: {
'pty-codex-stale': { previousAccountLabel: 'A', nextAccountLabel: 'B' }
},
agentStatusByPaneKey: {
[makePaneKey('tab-1', LEAF_1)]: {
paneKey: makePaneKey('tab-1', LEAF_1),
state: 'working',
prompt: 'stale input',
updatedAt: 1_000,
stateStartedAt: 900,
agentType: 'codex',
stateHistory: []
}
}
}
const pane = createPane(1)
const terminalTarget = createKeyboardEventTarget()
;(pane.terminal as { element?: unknown }).element = terminalTarget.target
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks10)
)
expect(onDataHandler).toBeDefined()
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
const sendTerminalInput = onDataHandler as (data: string) => void
terminalTarget.dispatch(keyEvent({ key: 'c', ctrlKey: true }))
sendTerminalInput('\x03')
vi.advanceTimersByTime(500)
expect(transport.sendInput).not.toHaveBeenCalled()
expect(window.api.agentStatus.inferInterrupt).not.toHaveBeenCalled()
})
it('blocks terminal writes while mobile presence lock owns the PTY', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks11 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -511,100 +322,6 @@ export function registerPtyConnectionTerminalInputGatingTests(): void {
}
})
it('blocks remote locked terminal input before it reaches the runtime transport', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks13 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const { setDriverForPty } = await import('@/lib/pane-manager/mobile-driver-state')
const ptyId = 'remote:env-1@@terminal-1'
setDriverForPty(ptyId, { kind: 'mobile', clientId: 'phone-1' })
try {
const transport = createMockTransport(ptyId)
transportFactoryQueue.push(transport)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId }] },
ptyIdsByTabId: { 'tab-1': [ptyId] }
}
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
connectPanePty(
pane as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks13)
)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as unknown as (data: string) => void)('x')
await flushAsyncTicks()
expect(window.api.runtime.restoreTerminalFit).not.toHaveBeenCalled()
expect(transport.sendInput).not.toHaveBeenCalled()
} finally {
setDriverForPty(ptyId, { kind: 'idle' })
}
})
it('does not infer interrupts when the transport rejects terminal input', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks14 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
vi.useFakeTimers()
vi.setSystemTime(1_100)
const transport = createMockTransport('pty-disconnected')
transport.sendInput.mockReturnValue(false)
transportFactoryQueue.push(transport)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState.agentStatusByPaneKey[paneKey] = {
paneKey,
state: 'working',
prompt: 'disconnected input',
updatedAt: 1_000,
stateStartedAt: 900,
agentType: 'custom-agent',
stateHistory: []
}
const pane = createPane(1)
const terminalTarget = createKeyboardEventTarget()
;(pane.terminal as { element?: unknown }).element = terminalTarget.target
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
connectPanePty(
pane as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks14)
)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
terminalTarget.dispatch(keyEvent({ key: 'c', ctrlKey: true }))
;(onDataHandler as unknown as (data: string) => void)('\x03')
await flushAsyncTicks()
await vi.advanceTimersByTimeAsync(500)
await flushAsyncTicks()
expect(transport.sendInput).toHaveBeenCalledWith('\x03')
expect(window.api.agentStatus.inferInterrupt).not.toHaveBeenCalled()
})
it('does not infer interrupts when the main process rejects acknowledged input', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks15 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -656,40 +373,6 @@ export function registerPtyConnectionTerminalInputGatingTests(): void {
expect(window.api.agentStatus.inferInterrupt).not.toHaveBeenCalled()
})
it('requests a connected pane remount when main reports its daemon write unavailable', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks16 = await vi.importMock<PtyConnectionAgentTitleMocks>(
'@/lib/agent-status/aggregation/worktree-agent-status'
)
const { _resetTerminalPaneRecoveryForTests } =
await import('../../render-health/recovery/terminal-pane-recovery')
_resetTerminalPaneRecoveryForTests()
const remountTerminalTabForRecovery = vi.fn(() => REMOUNTED)
mockStoreState = { ...mockStoreState, remountTerminalTabForRecovery } as StoreState
const transport = createMockTransport('daemon-pty')
let writeUnavailable: (() => void) | undefined
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
writeUnavailable = callbacks.onWriteUnavailable
return { id: 'daemon-pty' }
}
)
transportFactoryQueue.push(transport)
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks16)
)
await flushAsyncTicks(6)
writeUnavailable?.()
await flushAsyncTicks(6)
expect(window.api.pty.hasPty).toHaveBeenCalledWith('daemon-pty')
expect(remountTerminalTabForRecovery).toHaveBeenCalledWith('tab-1', AUTOMATIC_REQUEST)
_resetTerminalPaneRecoveryForTests()
})
it('quarantines the interrupted line after a write-unavailable remount, but never device replies', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks17 = await vi.importMock<PtyConnectionAgentTitleMocks>(
@@ -2,7 +2,6 @@ import { describe } from 'vitest'
import { registerPtyConnectionPendingSpawnTests } from '../spawn/pty-connection-pending-spawn.spec'
import { registerPtyConnectionFreshSpawnGuardsTests } from '../spawn/pty-connection-fresh-spawn-guards.spec'
import { registerPtyConnectionSplitSpawnTests } from '../spawn/pty-connection-split-spawn.spec'
import { registerPtyConnectionRuntimeOwnerSpawnRoutingTests } from '../host-ownership/pty-connection-runtime-owner-spawn-routing.spec'
import { registerPtyConnectionRestoredRuntimePaneBindingTests } from '../reattach/pty-connection-restored-runtime-pane-binding.spec'
import {
registerPtyConnectionLocalStartupCommandDeliveryTests,
@@ -18,7 +17,6 @@ describe('pty-connection-pending-spawn', registerPtyConnectionPendingSpawnTests)
describe('pty-connection-fresh-spawn-guards', registerPtyConnectionFreshSpawnGuardsTests)
describe('pty-connection-split-spawn', registerPtyConnectionSplitSpawnTests)
describe('pty-connection-runtime-owner-spawn-routing', () => {
registerPtyConnectionRuntimeOwnerSpawnRoutingTests()
registerPtyConnectionRestoredRuntimePaneBindingTests()
})
describe('pty-connection-startup-command-delivery', () => {
@@ -1,6 +1,5 @@
import { describe, vi } from 'vitest'
import { registerPtyConnectionVisibilityResumeSizeTests } from '../geometry/pty-connection-visibility-resume-size.spec'
import { registerPtyConnectionHiddenCodexQueriesTests } from '../emulation/pty-connection-hidden-codex-queries.spec'
import { registerPtyConnectionHiddenQuerySnapshotAuthorityTests } from '../output-restore/pty-connection-hidden-query-snapshot-authority.spec'
import { registerPtyConnectionHiddenDeliveryGateTests } from '../output-restore/pty-connection-hidden-delivery-gate.spec'
import { registerPtyConnectionParkRevealModelSnapshotTests } from '../reattach/pty-connection-park-reveal-model-snapshot.spec'
@@ -20,7 +19,6 @@ vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
describe('pty-connection-visibility-resume-size', registerPtyConnectionVisibilityResumeSizeTests)
describe('pty-connection-hidden-codex-queries', () => {
registerPtyConnectionHiddenCodexQueriesTests()
registerPtyConnectionHiddenQuerySnapshotAuthorityTests()
})
describe('pty-connection-hidden-delivery-gate', registerPtyConnectionHiddenDeliveryGateTests)
+5
View File
@@ -19774,6 +19774,8 @@
"showAgent": "{{value0}} im Gespräch anzeigen"
},
"jumpToLatest": "Zur neuesten Nachricht springen",
"newRowsAnnouncement": "Während der Abwesenheit sind neue Nachrichten eingegangen",
"newRowsMarker": "Neu",
"find": {
"label": "Im Chat suchen",
"noResults": "Keine Ergebnisse",
@@ -20643,6 +20645,9 @@
"scrollToLatestOnSendTitle": "Beim Senden zur neuesten Nachricht scrollen",
"scrollToLatestOnSendCopy": "Senden im hochgescrollten Zustand springt zur neuesten Nachricht und folgt der Antwort. Deaktiviere dies, um deine Position zu behalten.",
"scrollToLatestOnSendSearchPosition": "Position",
"markNewMessagesTitle": "Neue Nachrichten bei der Rückkehr in einen Chat markieren",
"markNewMessagesCopy": "Bei der Rückkehr in einen Chat erscheint eine Neu-Linie über dem, was in deiner Abwesenheit eingegangen ist. Warst du bei der neuesten Nachricht, scrollt der Chat dorthin.",
"markNewMessagesSearchUnread": "ungelesen",
"inlineVisualsTitle": "Eingebettete Grafiken",
"inlineVisualsCopy": "Dem Agenten erlauben, Diagramme, Schaubilder und Mockups in seinen Antworten anzuzeigen. Gilt für neu gestartete Chats.",
"inlineVisualsToggleLabel": "Eingebettete Grafiken umschalten",
+5
View File
@@ -20358,6 +20358,8 @@
"showAgent": "Show {{value0}} in the conversation"
},
"jumpToLatest": "Jump to latest",
"newRowsAnnouncement": "New messages arrived while you were away",
"newRowsMarker": "New",
"find": {
"label": "Find in chat",
"noResults": "No results",
@@ -21309,6 +21311,9 @@
"scrollToLatestOnSendTitle": "Scroll to latest when sending",
"scrollToLatestOnSendCopy": "Sending while scrolled up jumps to the latest message and follows the reply. Turn off to keep your place.",
"scrollToLatestOnSendSearchPosition": "position",
"markNewMessagesTitle": "Mark new messages when returning to a chat",
"markNewMessagesCopy": "Coming back to a chat draws a New line above what arrived while you were away, and scrolls to it if you were reading the latest.",
"markNewMessagesSearchUnread": "unread",
"inlineVisualsTitle": "Inline visuals",
"inlineVisualsCopy": "Let the agent show charts, diagrams and mockups inside its replies. Applies to newly started chats.",
"inlineVisualsToggleLabel": "Toggle inline visuals",
+5
View File
@@ -19413,6 +19413,8 @@
"toggleDetails": "Alternar detalles del turno"
},
"jumpToLatest": "Saltar a lo último",
"newRowsAnnouncement": "Llegaron mensajes nuevos mientras no estabas",
"newRowsMarker": "Nuevo",
"find": {
"label": "Buscar en el chat",
"noResults": "Sin resultados",
@@ -20395,6 +20397,9 @@
"scrollToLatestOnSendTitle": "Desplazar a lo último al enviar",
"scrollToLatestOnSendCopy": "Enviar con el chat desplazado hacia arriba salta al último mensaje y sigue la respuesta. Desactívalo para mantener tu posición.",
"scrollToLatestOnSendSearchPosition": "posición",
"markNewMessagesTitle": "Marcar los mensajes nuevos al volver a un chat",
"markNewMessagesCopy": "Al volver a un chat aparece una línea Nuevo encima de lo que llegó mientras no estabas, y el chat se desplaza hasta ella si estabas leyendo lo más reciente.",
"markNewMessagesSearchUnread": "no leído",
"followUpBehaviorCopy": "Los mensajes enviados mientras el agente trabaja esperan como tarjetas hasta que termina el turno, en lugar de entrar en el turno en curso. Cmd/Ctrl+Intro hace lo contrario para un mensaje y, si no hay texto escrito, dirige la primera tarjeta en espera al turno en curso. Los mensajes con imágenes también esperan como tarjetas.",
"inlineVisualsTitle": "Elementos visuales inline",
"inlineVisualsCopy": "Permite que el agente muestre gráficos, diagramas y maquetas dentro de sus respuestas. Se aplica a los chats nuevos.",
+5
View File
@@ -19652,6 +19652,8 @@
"toggleDetails": "Basculer les détails du tour"
},
"jumpToLatest": "Aller au dernier message",
"newRowsAnnouncement": "De nouveaux messages sont arrivés en votre absence",
"newRowsMarker": "Nouveau",
"find": {
"label": "Rechercher dans le chat",
"noResults": "Aucun résultat",
@@ -20743,6 +20745,9 @@
"scrollToLatestOnSendTitle": "Défiler jusqu’au dernier message à l’envoi",
"scrollToLatestOnSendCopy": "Envoyer après avoir remonté le fil fait défiler jusqu’au dernier message et suit la réponse. Désactivez cette option pour garder votre position.",
"scrollToLatestOnSendSearchPosition": "position",
"markNewMessagesTitle": "Signaler les nouveaux messages au retour dans un chat",
"markNewMessagesCopy": "En revenant dans un chat, une ligne Nouveau s'affiche au-dessus de ce qui est arrivé pendant votre absence, et le chat y défile si vous lisiez les derniers messages.",
"markNewMessagesSearchUnread": "non lu",
"followUpBehaviorCopy": "Les messages envoyés pendant que l’agent travaille attendent sous forme de cartes jusqu’à la fin du tour, au lieu d’entrer dans le tour en cours. Cmd/Ctrl+Entrée fait l’inverse pour un message et, si rien n’est saisi, dirige la première carte en attente vers le tour en cours. Les messages contenant des images attendent aussi sous forme de cartes.",
"inlineVisualsTitle": "Visuels intégrés",
"inlineVisualsCopy": "Laissez l'agent afficher des graphiques, des diagrammes et des maquettes dans ses réponses. S'applique aux nouveaux chats.",
+5
View File
@@ -18950,6 +18950,8 @@
"toggleDetails": "ターンの詳細を切り替えます"
},
"jumpToLatest": "最新にジャンプ",
"newRowsAnnouncement": "離れている間に新しいメッセージが届きました",
"newRowsMarker": "新着",
"find": {
"label": "チャット内を検索",
"noResults": "結果はありません",
@@ -19918,6 +19920,9 @@
"scrollToLatestOnSendTitle": "送信時に最新までスクロール",
"scrollToLatestOnSendCopy": "上にスクロールした状態で送信すると、最新のメッセージに移動して返信を追従します。オフにすると現在の位置を維持します。",
"scrollToLatestOnSendSearchPosition": "位置",
"markNewMessagesTitle": "チャットに戻ったときに新着メッセージを示す",
"markNewMessagesCopy": "チャットに戻ると、離れている間に届いたメッセージの上に「新着」の線を表示します。最新のメッセージを読んでいた場合は、そこまでスクロールします。",
"markNewMessagesSearchUnread": "未読",
"followUpBehaviorCopy": "Agent の作業中に送信したメッセージは、実行中のターンに送られず、ターンが終わるまでカードとして待機します。Cmd/Ctrl+Enter では 1 件だけその逆になり、何も入力されていない場合は最初の待機カードを実行中のターンに送ります。画像付きメッセージもカードとして待機します。",
"inlineVisualsTitle": "インライン表示",
"inlineVisualsCopy": "Agent が返信内でグラフ、図、モックアップを表示できるようにします。新しく開始したチャットに適用されます。",
+5
View File
@@ -18950,6 +18950,8 @@
"toggleDetails": "턴 세부정보 전환"
},
"jumpToLatest": "최신으로 이동",
"newRowsAnnouncement": "자리를 비운 동안 새 메시지가 도착했습니다",
"newRowsMarker": "새 메시지",
"find": {
"label": "채팅에서 찾기",
"noResults": "결과 없음",
@@ -19918,6 +19920,9 @@
"scrollToLatestOnSendTitle": "보낼 때 최신 메시지로 스크롤",
"scrollToLatestOnSendCopy": "위로 스크롤한 상태에서 보내면 최신 메시지로 이동하고 답장을 따라갑니다. 끄면 현재 위치가 유지됩니다.",
"scrollToLatestOnSendSearchPosition": "위치",
"markNewMessagesTitle": "채팅으로 돌아올 때 새 메시지 표시",
"markNewMessagesCopy": "채팅으로 돌아오면 자리를 비운 동안 도착한 내용 위에 '새 메시지' 선을 표시합니다. 최신 메시지를 보고 있었다면 그 위치로 스크롤합니다.",
"markNewMessagesSearchUnread": "읽지 않음",
"followUpBehaviorCopy": "Agent가 작업하는 동안 보낸 메시지는 진행 중인 턴에 들어가지 않고 턴이 끝날 때까지 카드로 대기합니다. Cmd/Ctrl+Enter를 누르면 메시지 하나에 대해 반대로 동작하며, 입력한 내용이 없으면 첫 대기 카드를 진행 중인 턴으로 보냅니다. 이미지가 포함된 메시지도 카드로 대기합니다.",
"inlineVisualsTitle": "인라인 시각 자료",
"inlineVisualsCopy": "에이전트가 답변 안에 차트, 다이어그램, 목업을 표시하도록 합니다. 새로 시작한 채팅에 적용됩니다.",
+5
View File
@@ -20834,6 +20834,8 @@
"pendingWork": "Aguarde a conclusão do trabalho e das mensagens pendentes antes de usar este comando.",
"notDoneGoalChangeIncomplete": "Não foi possível concluir a alteração do objetivo. Verifique o chat."
},
"newRowsAnnouncement": "Novas mensagens chegaram enquanto você estava ausente",
"newRowsMarker": "Novas",
"find": {
"label": "Localizar no chat",
"noResults": "Nenhum resultado",
@@ -21613,6 +21615,9 @@
"scrollToLatestOnSendTitle": "Rolar até o mais recente ao enviar",
"scrollToLatestOnSendCopy": "Enviar com o chat rolado para cima leva à mensagem mais recente e acompanha a resposta. Desative para manter sua posição.",
"scrollToLatestOnSendSearchPosition": "posição",
"markNewMessagesTitle": "Marcar mensagens novas ao voltar para um chat",
"markNewMessagesCopy": "Ao voltar para um chat, uma linha Novas aparece acima do que chegou enquanto você estava fora, e o chat rola até ela se você estava lendo as mais recentes.",
"markNewMessagesSearchUnread": "não lida",
"inlineVisualsTitle": "Visualizações nas respostas",
"inlineVisualsCopy": "Permitir que o agente mostre gráficos, diagramas e mockups nas respostas. Aplica-se a novos chats.",
"inlineVisualsToggleLabel": "Ativar ou desativar visualizações nas respostas",
+5
View File
@@ -20424,6 +20424,8 @@
"showAgent": "Показать {{value0}} в разговоре"
},
"jumpToLatest": "К последним сообщениям",
"newRowsAnnouncement": "Пока вас не было, появились новые сообщения",
"newRowsMarker": "Новое",
"find": {
"label": "Найти в чате",
"noResults": "Ничего не найдено",
@@ -21330,6 +21332,9 @@
"scrollToLatestOnSendTitle": "Прокручивать к последнему сообщению при отправке",
"scrollToLatestOnSendCopy": "Отправка при прокрутке вверх переносит к последнему сообщению и следит за ответом. Отключите, чтобы остаться на месте.",
"scrollToLatestOnSendSearchPosition": "позиция",
"markNewMessagesTitle": "Отмечать новые сообщения при возвращении в чат",
"markNewMessagesCopy": "При возвращении в чат над тем, что пришло в ваше отсутствие, появляется линия «Новое». Если вы читали последние сообщения, чат прокручивается к ней.",
"markNewMessagesSearchUnread": "непрочитанные",
"inlineVisualsTitle": "Визуализации в чате",
"inlineVisualsCopy": "Агент сможет показывать графики, схемы и макеты прямо в ответах. Применяется к новым чатам.",
"inlineVisualsToggleLabel": "Включить визуализации в чате",
+5
View File
@@ -19759,6 +19759,8 @@
"showAgent": "{{value0}} öğesini konuşmada göster"
},
"jumpToLatest": "En son öğeye git",
"newRowsAnnouncement": "Siz yokken yeni mesajlar geldi",
"newRowsMarker": "Yeni",
"find": {
"label": "Sohbette bul",
"noResults": "Sonuç yok",
@@ -20625,6 +20627,9 @@
"scrollToLatestOnSendTitle": "Gönderirken en son mesaja kaydır",
"scrollToLatestOnSendCopy": "Yukarı kaydırılmışken göndermek en son mesaja atlar ve yanıtı takip eder. Konumunuzu korumak için kapatın.",
"scrollToLatestOnSendSearchPosition": "konum",
"markNewMessagesTitle": "Bir sohbete dönünce yeni mesajları işaretle",
"markNewMessagesCopy": "Bir sohbete döndüğünüzde, siz yokken gelenlerin üstünde bir Yeni çizgisi gösterilir. En son mesajları okuyorduysanız sohbet oraya kaydırılır.",
"markNewMessagesSearchUnread": "okunmamış",
"inlineVisualsTitle": "Yanıtlarda görseller",
"inlineVisualsCopy": "Ajanın yanıtlarında grafikler, diyagramlar ve taslaklar göstermesine izin verin. Yeni başlatılan sohbetlere uygulanır.",
"inlineVisualsToggleLabel": "Yanıtlardaki görselleri aç/kapat",
@@ -19475,6 +19475,8 @@
"showAgent": "在對話中顯示 {{value0}}"
},
"jumpToLatest": "跳到最新訊息",
"newRowsAnnouncement": "你離開期間有新訊息",
"newRowsMarker": "新訊息",
"find": {
"label": "在聊天中查詢",
"noResults": "沒有結果",
@@ -20326,6 +20328,9 @@
"scrollToLatestOnSendTitle": "傳送時捲動到最新訊息",
"scrollToLatestOnSendCopy": "向上捲動時傳送訊息會跳到最新訊息並跟隨回覆。關閉後會保留目前位置。",
"scrollToLatestOnSendSearchPosition": "位置",
"markNewMessagesTitle": "返回聊天時標記新訊息",
"markNewMessagesCopy": "返回聊天時,在你離開期間收到的內容上方顯示「新訊息」分隔線;如果你之前在看最新訊息,會捲動到該處。",
"markNewMessagesSearchUnread": "未讀",
"inlineVisualsTitle": "內嵌視覺化",
"inlineVisualsCopy": "允許代理程式在其回覆中顯示圖表、示意圖和原型圖。適用於新啟動的聊天。",
"inlineVisualsToggleLabel": "切換內嵌視覺化",
+5
View File
@@ -18890,6 +18890,8 @@
"toggleDetails": "切换回合详情"
},
"jumpToLatest": "跳到最新消息",
"newRowsAnnouncement": "你离开期间有新消息",
"newRowsMarker": "新消息",
"find": {
"label": "在聊天中查找",
"noResults": "没有结果",
@@ -19918,6 +19920,9 @@
"scrollToLatestOnSendTitle": "发送时滚动到最新消息",
"scrollToLatestOnSendCopy": "向上滚动时发送消息会跳到最新消息并跟随回复。关闭后将保持当前位置。",
"scrollToLatestOnSendSearchPosition": "位置",
"markNewMessagesTitle": "返回聊天时标记新消息",
"markNewMessagesCopy": "返回聊天时,在你离开期间收到的内容上方显示“新消息”分隔线;如果你之前在看最新消息,会滚动到该处。",
"markNewMessagesSearchUnread": "未读",
"followUpBehaviorCopy": "智能体工作时发送的消息会作为卡片等待,直到本轮结束,而不是进入当前轮次。Cmd/Ctrl+Enter 对单条消息执行相反操作;输入框为空时,该快捷键会将第一张等待中的卡片引入当前轮次。带图片的消息也会作为卡片等待。",
"inlineVisualsTitle": "内联可视化",
"inlineVisualsCopy": "允许智能体在其回复中显示图表、示意图和原型图。适用于新启动的聊天。",
@@ -31,6 +31,18 @@ export type NativeChatGlobalSettings = {
nativeChatTurnDiffSummary?: boolean
/** Lines saying how CI went on a pull request the chat opened or pushed to. Absent means on. */
nativeChatCiResultLines?: boolean
/** A "New" line above what arrived while the reader was away. Absent follows the default below. */
nativeChatMarkNewMessages?: boolean
}
/** Not written into default settings, so flipping this reaches everyone who never chose. */
const NATIVE_CHAT_MARKS_NEW_MESSAGES_BY_DEFAULT = true
export function nativeChatMarksNewMessages(
settings: { readonly nativeChatMarkNewMessages?: unknown } | null | undefined
): boolean {
const value = settings?.nativeChatMarkNewMessages
return typeof value === 'boolean' ? value : NATIVE_CHAT_MARKS_NEW_MESSAGES_BY_DEFAULT
}
/** Only explicit OFF keeps a reader's place on send. */
@@ -15,7 +15,11 @@ export type OrchestrationCallerRefusal = {
export type CliStatusCaller = OrchestrationCallerSession | OrchestrationCallerRefusal
/** `null`: the caller is not an Orca session. */
export type OrchestrationCallerShowResult = { caller: OrchestrationCallerSession | null }
export type OrchestrationCallerShowResult = {
caller: OrchestrationCallerSession | null
/** True when this Orca verified the calling terminal agent's launch. Absent from older Orcas. */
terminal?: boolean
}
/** `orchestration.sessionAddress`: a session's Orca session ID, its `/clear` root's. */
export type OrchestrationSessionAddressResult = { orcaSessionId: string }

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