From 314506003a16297006225147fef8bdcec2186da8 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 7 Sep 2026 00:35:55 -0700 Subject: [PATCH 01/37] fix: retain MSYS shell descendants in their terminal job (#19068) * fix: retain MSYS shell descendants in their terminal job * test: complete MSYS regression CI registration and teardown contract * fix(windows): deny job breakaway for the whole Cygwin/MSYS shell family The per-PTY job probed only msys-2.0.dll, and only for bash.exe/sh.exe. Cygwin ships the same spawn.cc breakaway logic under cygwin1.dll, and an MSYS2 zsh escapes exactly like its bash does, so both kept the orphan bug. Probe the runtime DLL on the shell's own search path instead of matching shell names: that is the property that decides whether the runtime will ask for CREATE_BREAKAWAY_FROM_JOB, and it drops the name special-casing. * chore(patch): restore the conpty.cc index line The earlier hand-edit dropped it while every sibling section kept one. Recomputed against the real blobs: applying this patch to 7b286d3d yields exactly 4b06d185, so git apply -3 has its fallback back. --- .github/workflows/pr.yml | 1 + config/patches/node-pty@1.1.0.patch | 107 +++++++++++------- config/scripts/pr-code-change-scope.mjs | 1 + docs/reference/windows-process-enumeration.md | 14 +++ pnpm-lock.yaml | 6 +- .../windows/windows-msys-job.win32.test.ts | 65 +++++++++++ 6 files changed, 153 insertions(+), 41 deletions(-) create mode 100644 src/main/windows/windows-msys-job.win32.test.ts diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 9279f35b39f..268b6ad66e3 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -856,6 +856,7 @@ jobs: src/main/agent-hooks/windows-hook-payload-delivery.test.ts src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts src/main/windows/windows-pty-job.win32.test.ts + src/main/windows/windows-msys-job.win32.test.ts src/main/windows/windows-host-job.win32.test.ts src/main/windows/windows-process-tree-command-line-patch.test.ts src/main/windows/windows-process-table-native-addon.win32.test.ts diff --git a/config/patches/node-pty@1.1.0.patch b/config/patches/node-pty@1.1.0.patch index 8f5045b932a..961e750da6b 100644 --- a/config/patches/node-pty@1.1.0.patch +++ b/config/patches/node-pty@1.1.0.patch @@ -603,7 +603,7 @@ index 7b4b9e1f990fbf95b51528bb56dc9717f5b87532..2ae787c5bd4f3eba470584dc658a01a5 } #endif diff --git a/src/win/conpty.cc b/src/win/conpty.cc -index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c97209248e 100644 +index 7b286d3d644c26141df516929703aa6e129df4b2..4b06d18576c807c3d1181a7bd714140c6678cf86 100644 --- a/src/win/conpty.cc +++ b/src/win/conpty.cc @@ -18,6 +18,7 @@ @@ -614,7 +614,7 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 #include #include #include -@@ -44,12 +45,39 @@ struct pty_baton { +@@ -44,12 +45,40 @@ struct pty_baton { HANDLE hOut; HPCON hpc; @@ -630,6 +630,7 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 + // refused to create or assign one (an outer job without breakaway rights), + // in which case callers fall back to their pre-job behaviour. + HANDLE hJob = nullptr; ++ bool allowJobBreakaway = true; + + // Orca: teardown needs BOTH the shell's death and an explicit kill() before + // the baton can be freed, so each side records that it has run. Whichever @@ -655,7 +656,7 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 static volatile LONG ptyCounter; static pty_baton* get_pty_baton(int id) { -@@ -102,8 +130,31 @@ void SetupExitCallback(Napi::Env env, Napi::Function cb, pty_baton* baton) { +@@ -102,8 +131,31 @@ void SetupExitCallback(Napi::Env env, Napi::Function cb, pty_baton* baton) { // Get process exit code. GetExitCodeProcess(baton->hShell, (LPDWORD)(&exit_event->exit_code)); // Clean up handles @@ -689,7 +690,36 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 auto status = tsfn.BlockingCall(exit_event, callback); // In main thread switch (status) { -@@ -409,6 +460,15 @@ static Napi::Value PtyConnect(const Napi::CallbackInfo& info) { +@@ -242,6 +294,20 @@ + return HRESULT_FROM_WIN32(GetLastError()); + } + ++// Cygwin and MSYS request breakaway for every child whenever the job allows it, ++// so their shells need one that does not. The runtime DLL on the exe's search ++// path is the signal; Git for Windows ships bash.exe in bin\ beside usr\bin\. ++static bool usesCygwinRuntime(const std::wstring& shellpath) { ++ const size_t separator = shellpath.find_last_of(L"\\/"); ++ if (separator == std::wstring::npos) return false; ++ const std::wstring directory = shellpath.substr(0, separator + 1); ++ for (const wchar_t* dll : {L"msys-2.0.dll", L"cygwin1.dll"}) { ++ if (path_util::file_exists(directory + dll) || ++ path_util::file_exists(directory + L"..\\usr\\bin\\" + dll)) return true; ++ } ++ return false; ++} ++ + static Napi::Value PtyStartProcess(const Napi::CallbackInfo& info) { + Napi::Env env(info.Env()); + Napi::HandleScope scope(env); +@@ -303,6 +369,7 @@ + marshal.Set("pty", Napi::Number::New(env, ptyId)); + ptyHandles.emplace_back( + std::make_unique(ptyId, hIn, hOut, hpc)); ++ ptyHandles.back()->allowJobBreakaway = !usesCygwinRuntime(shellpath); + } else { + throw Napi::Error::New(env, "Cannot launch conpty"); + } +@@ -409,6 +476,15 @@ static Napi::Value PtyConnect(const Napi::CallbackInfo& info) { throw errorWithCode(info, "UpdateProcThreadAttribute failed"); } @@ -705,7 +735,7 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 PROCESS_INFORMATION piClient{}; fSuccess = !!CreateProcessW( nullptr, -@@ -416,7 +476,10 @@ static Napi::Value PtyConnect(const Napi::CallbackInfo& info) { +@@ -416,7 +492,10 @@ static Napi::Value PtyConnect(const Napi::CallbackInfo& info) { nullptr, // lpProcessAttributes nullptr, // lpThreadAttributes false, // bInheritHandles VERY IMPORTANT that this is false @@ -717,7 +747,7 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 envArg, // lpEnvironment mutableCwd.get(), // lpCurrentDirectory &siEx.StartupInfo, // lpStartupInfo -@@ -426,8 +489,47 @@ static Napi::Value PtyConnect(const Napi::CallbackInfo& info) { +@@ -426,8 +505,48 @@ static Napi::Value PtyConnect(const Napi::CallbackInfo& info) { throw errorWithCode(info, "Cannot create process"); } @@ -735,13 +765,14 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 + // EXPLICIT teardown exact, not to redefine what a clean exit means. + HANDLE hJob = CreateJobObjectW(nullptr, nullptr); + if (hJob != nullptr) { -+ // Why BREAKAWAY_OK and not a bare job: with no limits set, a child asking -+ // for CREATE_BREAKAWAY_FROM_JOB is refused with ERROR_ACCESS_DENIED. -+ // Installers, msiexec and some updater and service-control paths spawn that -+ // way deliberately, so a bare job breaks them ONLY inside an Orca terminal. -+ // With this flag a child has to ask, so ordinary descendants stay owned. ++ // Native shells retain explicit breakaway for installers and updaters. ++ // Cygwin/MSYS shells take it automatically for ordinary children whenever ++ // this flag is present, so they get strict per-PTY membership instead. ++ // Explicit breakaway requests inside such a pane are consequently denied; ++ // ordinary backgrounding and clean shell exit remain supported. + JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobLimits{}; -+ jobLimits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_BREAKAWAY_OK; ++ jobLimits.BasicLimitInformation.LimitFlags = ++ handle->allowJobBreakaway ? JOB_OBJECT_LIMIT_BREAKAWAY_OK : 0; + if (!SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, &jobLimits, sizeof(jobLimits)) || + !AssignProcessToJobObject(hJob, piClient.hProcess)) { + // Why tolerate failure: an outer job without JOB_OBJECT_LIMIT_BREAKAWAY_OK @@ -767,7 +798,7 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 if (useConptyDll && fLoadedDll) { PFNRELEASEPSEUDOCONSOLE const pfnReleasePseudoConsole = (PFNRELEASEPSEUDOCONSOLE)GetProcAddress( -@@ -440,6 +542,8 @@ static Napi::Value PtyConnect(const Napi::CallbackInfo& info) { +@@ -440,6 +559,8 @@ static Napi::Value PtyConnect(const Napi::CallbackInfo& info) { // Update handle handle->hShell = piClient.hProcess; @@ -776,11 +807,16 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 // Close the thread handle to avoid resource leak CloseHandle(piClient.hThread); -@@ -544,29 +648,215 @@ static Napi::Value PtyKill(const Napi::CallbackInfo& info) { +@@ -544,27 +665,213 @@ static Napi::Value PtyKill(const Napi::CallbackInfo& info) { int id = info[0].As().Int32Value(); const bool useConptyDll = info[1].As().Value(); - const pty_baton* handle = get_pty_baton(id); +- +- if (handle != nullptr) { +- HANDLE hLibrary = LoadConptyDll(info, useConptyDll); +- bool fLoadedDll = hLibrary != nullptr; +- if (fLoadedDll) + // Orca: resolve the DLL BEFORE touching any baton state, for the same reason + // PtyConnect does it before creating anything. LoadConptyDll throws when + // conpty.dll is missing, and a throw after consoleClosed was set would strand @@ -794,18 +830,7 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 + (HMODULE)hLibrary, + useConptyDll ? "ConptyClosePseudoConsole" : "ClosePseudoConsole"); + } - -- if (handle != nullptr) { -- HANDLE hLibrary = LoadConptyDll(info, useConptyDll); -- bool fLoadedDll = hLibrary != nullptr; -- if (fLoadedDll) -- { -- PFNCLOSEPSEUDOCONSOLE const pfnClosePseudoConsole = (PFNCLOSEPSEUDOCONSOLE)GetProcAddress( -- (HMODULE)hLibrary, -- useConptyDll ? "ConptyClosePseudoConsole" : "ClosePseudoConsole"); -- if (pfnClosePseudoConsole) -- { -- pfnClosePseudoConsole(handle->hpc); ++ + // Orca: the baton now outlives the shell, so this runs on a self-exited pty + // too -- that is the whole point. Take what we need under the lock: the + // watcher thread nulls hShell the moment the shell dies, and TerminateProcess @@ -841,18 +866,26 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 + const bool removed = remove_pty_baton(id); + assert(removed); + (void)removed; - } ++ } + // Else the shell is still running and the watcher frees the baton. - } -- if (useConptyDll) { -- TerminateProcess(handle->hShell, 1); ++ } + } + + // Why outside the lock: ClosePseudoConsole blocks until the conout side has + // drained, and the watcher must be able to take the lock while it does. + if (owed) { + if (pfnClosePseudoConsole) -+ { + { +- PFNCLOSEPSEUDOCONSOLE const pfnClosePseudoConsole = (PFNCLOSEPSEUDOCONSOLE)GetProcAddress( +- (HMODULE)hLibrary, +- useConptyDll ? "ConptyClosePseudoConsole" : "ClosePseudoConsole"); +- if (pfnClosePseudoConsole) +- { +- pfnClosePseudoConsole(handle->hpc); +- } +- } +- if (useConptyDll) { +- TerminateProcess(handle->hShell, 1); + pfnClosePseudoConsole(hpc); + } + if (hShellDup != nullptr) { @@ -862,8 +895,8 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 } return env.Undefined(); - } - ++} ++ +/** + * Orca: confirm a baton really is the pty the caller means. + * @@ -1001,12 +1034,10 @@ index 7b286d3d644c26141df516929703aa6e129df4b2..4aed260dd68e6a171dcfd349e9a7c5c9 + } + hHostJob = job; + return Napi::Boolean::New(env, true); -+} -+ + } + /** - * Init - */ -@@ -577,6 +867,9 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { +@@ -577,6 +884,9 @@ Napi::Object init(Napi::Env env, Napi::Object exports) { exports.Set("resize", Napi::Function::New(env, PtyResize)); exports.Set("clear", Napi::Function::New(env, PtyClear)); exports.Set("kill", Napi::Function::New(env, PtyKill)); diff --git a/config/scripts/pr-code-change-scope.mjs b/config/scripts/pr-code-change-scope.mjs index befcb06fe1f..96917d23ef1 100644 --- a/config/scripts/pr-code-change-scope.mjs +++ b/config/scripts/pr-code-change-scope.mjs @@ -224,6 +224,7 @@ const WINDOWS_PACKAGE_TESTS = [ 'src/main/agent-hooks/windows-hook-payload-delivery.test.ts', 'src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts', 'src/main/windows/windows-pty-job.win32.test.ts', + 'src/main/windows/windows-msys-job.win32.test.ts', 'src/main/windows/windows-host-job.win32.test.ts', 'src/main/windows/windows-process-tree-command-line-patch.test.ts', 'src/main/windows/windows-process-table-native-addon.win32.test.ts', diff --git a/docs/reference/windows-process-enumeration.md b/docs/reference/windows-process-enumeration.md index 0f7f17bd433..80cc7663f4c 100644 --- a/docs/reference/windows-process-enumeration.md +++ b/docs/reference/windows-process-enumeration.md @@ -575,6 +575,20 @@ running, so typing `exit` in a pane reaped a `start /b` server that used to survive. The job exists to make an _explicit_ teardown exact, not to redefine what a clean exit means. +Git Bash needs one additional restriction. The Cygwin runtime — and the MSYS2 +fork of it that Git for Windows ships — reads `JOB_OBJECT_LIMIT_BREAKAWAY_OK` +off its own job and then adds `CREATE_BREAKAWAY_FROM_JOB` to **every** child it +spawns when that flag is set (`spawn.cc`, there since 2011), so offering +breakaway hands the whole tree its escape. The per-PTY job therefore omits +`BREAKAWAY_OK` whenever `msys-2.0.dll` or `cygwin1.dll` sits on the shell's DLL +search path — beside the executable, or under `usr/bin` for Git's `bin` +launcher. Native shells keep explicit breakaway. Denying it costs Cygwin +nothing, because it *pre-checks* the limit rather than retrying, so no spawn +fails; but a *native* program that passes `CREATE_BREAKAWAY_FROM_JOB` itself +inside such a pane now gets `ERROR_ACCESS_DENIED`. `nohup` and `disown` are +unaffected — they are Cygwin signal/session concepts, unrelated to job +membership. The daemon's host job is unchanged. + Reaping a dead daemon's shells (#9195, #10415) is therefore a **second, nested job**, not this one. The terminal daemon assigns itself to a kill-on-close job at startup (`assignHostProcessToKillOnCloseJob`); children inherit membership, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 103ed90f4fe..e4a40c0fe47 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -116,7 +116,7 @@ patchedDependencies: '@xterm/addon-webgl@0.20.0-beta.299': 94687e89a0115e6e6aa102837f986debdc029c091527ee5eb4a4e17ceaf9473e '@xterm/xterm@6.1.0-beta.303': 98756bcedc402bcdb7c6ab7b015d2e59cd18e97b03a2c06a27e95bb3ba429d9d lint-staged@16.4.0: 7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673 - node-pty@1.1.0: 7cc9d45f3d2c38f142490d0805e75db55f0eef5174ad41c4b52abc5fbe079ad1 + node-pty@1.1.0: bac3a53fb15efc9b3b944fbe3c4718b5174a0b3bd6ead84e21975edad4bc6615 importers: @@ -160,7 +160,7 @@ importers: version: 3.3.1 node-pty: specifier: ^1.1.0 - version: 1.1.0(patch_hash=7cc9d45f3d2c38f142490d0805e75db55f0eef5174ad41c4b52abc5fbe079ad1) + version: 1.1.0(patch_hash=bac3a53fb15efc9b3b944fbe3c4718b5174a0b3bd6ead84e21975edad4bc6615) posthog-node: specifier: ^5.33.3 version: 5.33.3 @@ -12285,7 +12285,7 @@ snapshots: node-int64@0.4.0: {} - node-pty@1.1.0(patch_hash=7cc9d45f3d2c38f142490d0805e75db55f0eef5174ad41c4b52abc5fbe079ad1): + node-pty@1.1.0(patch_hash=bac3a53fb15efc9b3b944fbe3c4718b5174a0b3bd6ead84e21975edad4bc6615): dependencies: node-addon-api: 7.1.1 diff --git a/src/main/windows/windows-msys-job.win32.test.ts b/src/main/windows/windows-msys-job.win32.test.ts new file mode 100644 index 00000000000..e7e0bee950a --- /dev/null +++ b/src/main/windows/windows-msys-job.win32.test.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { removeTreeSync } from '../../shared/windows-transient-lock-removal' +import { resolveGitBashPath } from '../git-bash' +import { quotePosixShell } from '../../shared/wsl-login-shell-command' +import { listPtyJobProcessIds, terminatePtyJob } from './windows-pty-job' + +const describeOnWindows = process.platform === 'win32' ? describe : describe.skip + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'EPERM' + } +} + +describeOnWindows('MSYS terminal job ownership', () => { + it('retains and terminates a child across Git Bash shell replacement', async () => { + const shell = resolveGitBashPath() + expect(shell, 'Git for Windows must be installed on the native test runner').not.toBeNull() + const directory = mkdtempSync(join(tmpdir(), 'orca-msys-job-')) + const script = join(directory, 'owned-child.js') + writeFileSync( + script, + "console.log('MSYS_OWNED_CHILD=' + process.pid); setInterval(() => {}, 1000)\n" + ) + const pty = await import('node-pty') + const proc = pty.spawn(shell!, ['-c', 'exec "$BASH" --noprofile --norc -i'], { + cwd: tmpdir(), + cols: 120, + rows: 30, + useConptyDll: true + }) + let output = '' + let childPid: number | undefined + proc.onData((chunk) => { + output += chunk + const match = /MSYS_OWNED_CHILD=(\d+)/.exec(output) + if (match) { + childPid = Number(match[1]) + } + }) + try { + proc.write( + `${quotePosixShell(process.execPath.replace(/\\/g, '/'))} ${quotePosixShell(script.replace(/\\/g, '/'))}\r` + ) + await vi.waitFor(() => expect(childPid).toBeDefined(), { timeout: 15_000 }) + expect(isAlive(childPid!)).toBe(true) + expect(listPtyJobProcessIds(proc)).toContain(childPid) + expect(terminatePtyJob(proc)).toBe('terminated') + await vi.waitFor(() => expect(isAlive(childPid!)).toBe(false), { timeout: 5_000 }) + } finally { + // The failing baseline can leave this exact fixture child outside the job. + if (childPid && isAlive(childPid)) { + process.kill(childPid) + } + proc.kill() + removeTreeSync(directory) + } + }, 30_000) +}) From ffff6eaca203ab1547ab532990881c4d556fff47 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 7 Sep 2026 01:01:49 -0700 Subject: [PATCH 02/37] fix(test): admit the adoption-replay create fixture through the structured gate (#19246) Semantic conflict between two green PRs. #19176 added this replay test while `agentSession.*` still admitted a `runtime` client on its negotiated capability alone; #18700 then made `experimentalStructuredNativeChat` one rule for every caller. Neither branch saw the other, and main runs no post-merge test gate, so `agentSession.create` started refusing at the envelope level and the test's `ok: true` expectation broke. #18700's rule is the intended behaviour and `create` starts work, so it belongs behind the gate. The fixture is what is stale: it builds a real `OrcaRuntimeService` whose client settings are unset. Enable the setting the way #18700 already did for the sibling pre-commit fixture. The assertions about durable-identity replay are untouched and now actually run. --- .../methods/structured-agent-session-adoption-replay.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts index 42fdbc772a0..d83043edd5a 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts @@ -138,6 +138,11 @@ describe('committed adopting create RPC replay', () => { undefined, { prepareCodexStructuredLaunch: selectAccountHome } ) + // The structured surface is settings-gated for every caller, not just mobile; this test + // probes durable-identity replay, which only runs once the gate admits the call. + vi.spyOn(runtime, 'getClientSettings').mockReturnValue({ + experimentalStructuredNativeChat: true + } as ReturnType) vi.spyOn(runtime, 'getStructuredAgentSessionCreateSupport').mockResolvedValue({ supported: true }) From c3a70082c652b3e583fd85a16318de829ffc33c8 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 7 Sep 2026 01:22:08 -0700 Subject: [PATCH 03/37] Fix MiniMax credential-expiry reporting, region sync, and refresh (#19250) * Fix MiniMax credential-expiry reporting, region sync, and refresh Three defects from #14929: 1. The usage endpoint answers an expired cookie or key with HTTP 200 and base_resp.status_code 1004, never 401/403 (confirmed against both regional hosts). The stale-token branch was therefore unreachable, so expired credentials surfaced as 'usage-unavailable' with the raw upstream string, and stale policy kept showing old numbers as if the failure were transient. Classify 1004 as an expired credential. 2. minimaxEndpoint reached the SettingsUpdate schema and the web store but was never projected by RuntimeClientSettingsController.get(), so a paired client fell back to 'overseas' regardless of the host's region and rendered the wrong console link. Add it to the projection and the store contract. 3. Changing the region persisted without refreshing usage, leaving the previous host's snapshot in the status bar until the next poll. Invalidate and refetch when the endpoint, group id, or model list changes. The RPC-level tests mock the controller, so the projection had no real coverage; the new test fails against the pre-fix projection. * Localize the MiniMax credential-expiry copy Classifying 1004 as stale-token made the status bar show the raw English error verbatim: the new wording matches none of USAGE_AUTH_ERROR_PATTERNS, whereas the old upstream text ('...log in again') matched and was replaced with localized copy. That traded a localized-but-misleading message for an actionable English-only one, which is the wrong trade for the CN users this work targets. Tag the error with credentialSource so the renderer can pick the right localized string per credential kind, and add the three catalog entries. --- .../minimax/minimax-fetcher-data.ts | 7 +++-- .../minimax/minimax-fetcher-parse.ts | 22 ++++++++++--- .../minimax/minimax-fetcher.test.ts | 26 ++++++++++++++++ .../paired-settings.spec.ts | 20 ++++++++---- ...client-settings-minimax-projection.test.ts | 31 +++++++++++++++++++ src/main/runtime/runtime-client-settings.ts | 3 ++ src/main/runtime/runtime-store-contract.ts | 1 + .../startup/main-process-account-services.ts | 15 +++++++++ .../components/status-bar/usage-error-copy.ts | 16 ++++++++++ src/renderer/src/i18n/locales/en.json | 9 +++++- 10 files changed, 136 insertions(+), 14 deletions(-) create mode 100644 src/main/runtime/runtime-client-settings-minimax-projection.test.ts diff --git a/src/main/rate-limits/minimax/minimax-fetcher-data.ts b/src/main/rate-limits/minimax/minimax-fetcher-data.ts index 19e6d3f6768..25506bb891b 100644 --- a/src/main/rate-limits/minimax/minimax-fetcher-data.ts +++ b/src/main/rate-limits/minimax/minimax-fetcher-data.ts @@ -43,7 +43,10 @@ export function makeMiniMaxUnavailable(error: string): ProviderRateLimits { export function makeMiniMaxError( error: string, - failureKind: NonNullable['failureKind'] + failureKind: NonNullable['failureKind'], + // Why: the status bar localizes the expiry copy per credential kind; the raw + // `error` string stays English for logs. + credentialSource?: 'api-key' | 'session-cookie' ): ProviderRateLimits { return { provider: 'minimax', @@ -52,7 +55,7 @@ export function makeMiniMaxError( updatedAt: Date.now(), error, status: 'error', - usageMetadata: { failureKind, source: 'web' } + usageMetadata: { failureKind, source: 'web', ...(credentialSource ? { credentialSource } : {}) } } } diff --git a/src/main/rate-limits/minimax/minimax-fetcher-parse.ts b/src/main/rate-limits/minimax/minimax-fetcher-parse.ts index 8e776654b15..fdb4d728b0b 100644 --- a/src/main/rate-limits/minimax/minimax-fetcher-parse.ts +++ b/src/main/rate-limits/minimax/minimax-fetcher-parse.ts @@ -34,6 +34,19 @@ export type MiniMaxUsageResponse = { }[] } +// Why: MiniMax answers an expired cookie/key with HTTP 200 + base_resp.status_code 1004, +// so the credential-expiry signal has to be read from the payload, not the status line. +const MINIMAX_UNAUTHENTICATED_STATUS_CODE = 1004 + +function makeMiniMaxExpiredCredentialError(fetchResult: MiniMaxFetchResponse): ProviderRateLimits { + const usesApiKey = fetchResult.transport === 'api-key' + return makeMiniMaxError( + `MiniMax ${usesApiKey ? 'API key' : 'session cookie'} expired. Replace it in Settings.`, + 'stale-token', + usesApiKey ? 'api-key' : 'session-cookie' + ) +} + function handleMiniMaxHttpError(fetchResult: MiniMaxFetchResponse): ProviderRateLimits | null { const { response } = fetchResult if (response.status === 401 || response.status === 403) { @@ -43,11 +56,7 @@ function handleMiniMaxHttpError(fetchResult: MiniMaxFetchResponse): ProviderRate cookieNames: fetchResult.cookieNames, requestHeaderNames: fetchResult.requestHeaderNames }) - const credentialLabel = fetchResult.transport === 'api-key' ? 'API key' : 'session cookie' - return makeMiniMaxError( - `MiniMax ${credentialLabel} expired. Replace it in Settings.`, - 'stale-token' - ) + return makeMiniMaxExpiredCredentialError(fetchResult) } if (!response.ok) { logMiniMaxFetchFailure({ @@ -77,6 +86,9 @@ function handleMiniMaxPayloadError( cookieNames: fetchResult.cookieNames, requestHeaderNames: fetchResult.requestHeaderNames }) + if (statusCode === MINIMAX_UNAUTHENTICATED_STATUS_CODE) { + return makeMiniMaxExpiredCredentialError(fetchResult) + } const message = typeof payload.base_resp?.status_msg === 'string' ? payload.base_resp.status_msg diff --git a/src/main/rate-limits/minimax/minimax-fetcher.test.ts b/src/main/rate-limits/minimax/minimax-fetcher.test.ts index f3ca0709aba..d587c6b9256 100644 --- a/src/main/rate-limits/minimax/minimax-fetcher.test.ts +++ b/src/main/rate-limits/minimax/minimax-fetcher.test.ts @@ -356,6 +356,32 @@ describe('fetchMiniMaxRateLimits', () => { expect(result.error).toContain('unauth') }) + // Why: the live API answers an expired cookie/key with HTTP 200 + status_code 1004, + // never 401/403, so this is the only signal that reaches the stale-credential path. + it('classifies status_code 1004 on the cookie path as an expired session cookie', async () => { + netFetchMock.mockResolvedValueOnce( + makeResponse({ + base_resp: { status_code: 1004, status_msg: 'cookie is missing, log in again' } + }) + ) + const result = await fetchMiniMaxRateLimits({ cookie: FULL_COOKIE }) + expect(result.status).toBe('error') + expect(result.usageMetadata?.failureKind).toBe('stale-token') + expect(result.error).toMatch(/session cookie expired/i) + }) + + it('classifies status_code 1004 on the API key path as an expired API key', async () => { + netFetchMock.mockResolvedValueOnce( + makeResponse({ + base_resp: { status_code: 1004, status_msg: 'cookie is missing, log in again' } + }) + ) + const result = await fetchMiniMaxRateLimits({ apiKey: 'sk-expired', endpointMode: 'cn' }) + expect(result.status).toBe('error') + expect(result.usageMetadata?.failureKind).toBe('stale-token') + expect(result.error).toMatch(/API key expired/i) + }) + it('classifies malformed MiniMax JSON responses as parse failures', async () => { netFetchMock.mockResolvedValueOnce({ ok: true, diff --git a/src/main/runtime/orca-runtime-tests/paired-settings.spec.ts b/src/main/runtime/orca-runtime-tests/paired-settings.spec.ts index e5cb14671e3..a823e7d4591 100644 --- a/src/main/runtime/orca-runtime-tests/paired-settings.spec.ts +++ b/src/main/runtime/orca-runtime-tests/paired-settings.spec.ts @@ -30,6 +30,7 @@ describe('OrcaRuntimeService', () => { compactWorktreeCards: true, minimaxGroupId: 'group-42', minimaxUsageModels: 'general,abab6.5', + minimaxEndpoint: 'cn', terminalQuickCommands }) } as never) @@ -39,7 +40,9 @@ describe('OrcaRuntimeService', () => { experimentalNewWorktreeCardStyle: true, compactWorktreeCards: true, minimaxGroupId: 'group-42', - minimaxUsageModels: 'general,abab6.5' + minimaxUsageModels: 'general,abab6.5', + // Why: without this the paired client silently falls back to 'overseas' and shows the wrong region. + minimaxEndpoint: 'cn' }) expect(runtime.getClientSettings()).not.toHaveProperty('terminalQuickCommands') expect(runtime.getClientSettings().hostSettingOverrides).toEqual({ @@ -194,7 +197,8 @@ describe('OrcaRuntimeService', () => { experimentalNewWorktreeCardStyle: false, compactWorktreeCards: false, minimaxGroupId: '', - minimaxUsageModels: 'general' + minimaxUsageModels: 'general', + minimaxEndpoint: 'overseas' } const updateSettings = vi.fn((updates: Partial) => { settings = { ...settings, ...updates } @@ -211,20 +215,23 @@ describe('OrcaRuntimeService', () => { experimentalNewWorktreeCardStyle: true, compactWorktreeCards: true, minimaxGroupId: 'group-42', - minimaxUsageModels: 'general,abab6.5' + minimaxUsageModels: 'general,abab6.5', + minimaxEndpoint: 'cn' }) ).toMatchObject({ experimentalNewWorktreeCardStyle: true, compactWorktreeCards: true, minimaxGroupId: 'group-42', - minimaxUsageModels: 'general,abab6.5' + minimaxUsageModels: 'general,abab6.5', + minimaxEndpoint: 'cn' }) expect(updateSettings).toHaveBeenCalledWith( { experimentalNewWorktreeCardStyle: true, compactWorktreeCards: true, minimaxGroupId: 'group-42', - minimaxUsageModels: 'general,abab6.5' + minimaxUsageModels: 'general,abab6.5', + minimaxEndpoint: 'cn' }, { notifyListeners: true } ) @@ -232,7 +239,8 @@ describe('OrcaRuntimeService', () => { experimentalNewWorktreeCardStyle: true, compactWorktreeCards: true, minimaxGroupId: 'group-42', - minimaxUsageModels: 'general,abab6.5' + minimaxUsageModels: 'general,abab6.5', + minimaxEndpoint: 'cn' }) }) diff --git a/src/main/runtime/runtime-client-settings-minimax-projection.test.ts b/src/main/runtime/runtime-client-settings-minimax-projection.test.ts new file mode 100644 index 00000000000..1088ee47772 --- /dev/null +++ b/src/main/runtime/runtime-client-settings-minimax-projection.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { RuntimeClientSettingsController } from './runtime-client-settings' +import { createGlobalSettingsFixture } from '../../shared/global-settings-test-fixture' +import type { GlobalSettings } from '../../shared/global-settings-types' + +// Why: the paired client renders the region selector and console link from this projection. +// Omitting a field here silently falls the client back to its own default, and the RPC-level +// tests mock the controller, so only a real get() covers it. +function getProjected(overrides: Partial) { + const settings = createGlobalSettingsFixture({ workspaceDir: '/w', ...overrides }) + return new RuntimeClientSettingsController({ getSettings: () => settings } as never).get() +} + +describe('RuntimeClientSettingsController MiniMax projection', () => { + it('publishes the China endpoint to paired clients', () => { + expect(getProjected({ minimaxEndpoint: 'cn' }).minimaxEndpoint).toBe('cn') + }) + + it('publishes the overseas endpoint to paired clients', () => { + expect(getProjected({ minimaxEndpoint: 'overseas' }).minimaxEndpoint).toBe('overseas') + }) + + it('falls back to overseas when the host has no persisted endpoint', () => { + const settings = createGlobalSettingsFixture({ workspaceDir: '/w' }) + delete (settings as Partial).minimaxEndpoint + const projected = new RuntimeClientSettingsController({ + getSettings: () => settings + } as never).get() + expect(projected.minimaxEndpoint).toBe('overseas') + }) +}) diff --git a/src/main/runtime/runtime-client-settings.ts b/src/main/runtime/runtime-client-settings.ts index fc80c924156..900900700f3 100644 --- a/src/main/runtime/runtime-client-settings.ts +++ b/src/main/runtime/runtime-client-settings.ts @@ -40,6 +40,7 @@ export type RuntimeClientSettings = Pick< | 'compactWorktreeCards' | 'minimaxGroupId' | 'minimaxUsageModels' + | 'minimaxEndpoint' | 'prBotAuthorOverrides' | 'artifactSharingEnabled' | 'worktreeVisibilityDefaults' @@ -70,6 +71,7 @@ export type RuntimeClientSettingsUpdate = Pick< | 'compactWorktreeCards' | 'minimaxGroupId' | 'minimaxUsageModels' + | 'minimaxEndpoint' | 'prBotAuthorOverrides' | 'worktreeVisibilityDefaults' > @@ -110,6 +112,7 @@ export class RuntimeClientSettingsController { compactWorktreeCards: settings.compactWorktreeCards === true, minimaxGroupId: settings.minimaxGroupId ?? '', minimaxUsageModels: settings.minimaxUsageModels ?? 'general', + minimaxEndpoint: settings.minimaxEndpoint ?? 'overseas', prBotAuthorOverrides: settings.prBotAuthorOverrides ?? [], artifactSharingEnabled: isArtifactSharingEnabled(settings), worktreeVisibilityDefaults: settings.worktreeVisibilityDefaults ?? { external: 'hide' }, diff --git a/src/main/runtime/runtime-store-contract.ts b/src/main/runtime/runtime-store-contract.ts index 854d52bd0ba..f3f5d5a8f51 100644 --- a/src/main/runtime/runtime-store-contract.ts +++ b/src/main/runtime/runtime-store-contract.ts @@ -100,6 +100,7 @@ export type RuntimeStore = { compactWorktreeCards?: GlobalSettings['compactWorktreeCards'] minimaxGroupId?: GlobalSettings['minimaxGroupId'] minimaxUsageModels?: GlobalSettings['minimaxUsageModels'] + minimaxEndpoint?: GlobalSettings['minimaxEndpoint'] prBotAuthorOverrides?: GlobalSettings['prBotAuthorOverrides'] artifactSharingEnabled?: GlobalSettings['artifactSharingEnabled'] terminalQuickCommands?: GlobalSettings['terminalQuickCommands'] diff --git a/src/main/startup/main-process-account-services.ts b/src/main/startup/main-process-account-services.ts index ebfdd73f2f8..cf22c90b323 100644 --- a/src/main/startup/main-process-account-services.ts +++ b/src/main/startup/main-process-account-services.ts @@ -86,6 +86,21 @@ export function initializeMainProcessAccountServices(): void { void syncAccountRuntimeTargets(updates, settings).catch((error) => console.warn('[rate-limits] Failed to apply account runtime target:', error) ) + // Why: these three pick the MiniMax host and quota bucket, so a stale snapshot from the + // previous endpoint would otherwise sit in the status bar until the next poll. + if ( + 'minimaxEndpoint' in updates || + 'minimaxGroupId' in updates || + 'minimaxUsageModels' in updates + ) { + state.rateLimits?.invalidateMiniMaxCredentialState() + void state.rateLimits?.refresh().catch((error: unknown) => { + console.warn( + '[rate-limits] Failed to refresh MiniMax usage after a settings change:', + error + ) + }) + } }) state.rateLimits.setClaudeAuthPreparationResolver((target) => state.claudeRuntimeAuth!.prepareForRateLimitFetch(target) diff --git a/src/renderer/src/components/status-bar/usage-error-copy.ts b/src/renderer/src/components/status-bar/usage-error-copy.ts index 39032ab5e2c..dff1d178034 100644 --- a/src/renderer/src/components/status-bar/usage-error-copy.ts +++ b/src/renderer/src/components/status-bar/usage-error-copy.ts @@ -111,6 +111,11 @@ export function getProviderUsageStatusLabel(p: ProviderRateLimits): string { break } } + // Why: MiniMax reports credential expiry through the payload, not an HTTP status, + // so it needs its own copy rather than the generic refresh-failure label. + if (p.provider === 'minimax' && p.usageMetadata?.failureKind === 'stale-token') { + return translate('auto.components.status.bar.tooltip.minimax.expired.label', 'Sign-in expired') + } if (isUsageRateLimitError(p.error)) { return translate('auto.components.status.bar.tooltip.7ad719c4bf', 'Limited') } @@ -182,6 +187,17 @@ export function getProviderUsageErrorMessage(p: ProviderRateLimits): string { if (isUsageRateLimitError(p.error)) { return p.error } + if (p.provider === 'minimax' && p.usageMetadata?.failureKind === 'stale-token') { + return p.usageMetadata.credentialSource === 'api-key' + ? translate( + 'auto.components.status.bar.tooltip.minimax.expired.apiKey', + 'MiniMax API key expired. Replace it in Settings.' + ) + : translate( + 'auto.components.status.bar.tooltip.minimax.expired.cookie', + 'MiniMax session cookie expired. Replace it in Settings.' + ) + } if (isUsageAuthError(p.error)) { const name = getProviderDisplayName(p.provider) return translate( diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index cf00f09b861..b23161d3887 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -3903,7 +3903,14 @@ "e2c6a4f917": "Run Grok to refresh", "d1b7f509ac": "Run grok in a terminal on the computer running Orca and wait for it to start. If prompted, complete sign-in, then retry usage. You do not need to send a chat message.", "f90b3d7a16": "Run Kimi to refresh", - "a37e8c15d4": "Run kimi in a terminal on the computer running Orca and wait for it to start, then retry usage." + "a37e8c15d4": "Run kimi in a terminal on the computer running Orca and wait for it to start, then retry usage.", + "minimax": { + "expired": { + "label": "Sign-in expired", + "apiKey": "MiniMax API key expired. Replace it in Settings.", + "cookie": "MiniMax session cookie expired. Replace it in Settings." + } + } }, "SshTargetStatusRow": { "sshHost": "SSH Host" From a3e67365a344e92be13e0ac0e532c3b812e52d18 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 04:35:56 -0400 Subject: [PATCH 04/37] fix(orchestration): recover Codex idle after completion title race (#19243) * fix(orchestration): recover Codex idle after completion title race * test(native-chat): enable structured sessions in adoption replay fixture * test(orchestration): cover deferred pointer recovery after prolonged unknown status * fix(orchestration): fence completion recovery by process generation --- .../orca-runtime-apply-tracked-pty-title.ts | 3 + ...ntime-serialize-agent-prompt-submission.ts | 61 +++- ...chestration-codex-completion-title.test.ts | 265 +++++++++++++++++ ...tration-codex-real-pty.integration.test.ts | 272 ++++++++++++++++++ ...ation-mailbox-notification-test-harness.ts | 8 +- .../orchestration/mailbox-pointer-submit.ts | 12 + ...ured-agent-session-adoption-replay.test.ts | 5 +- src/shared/agent-title-status.ts | 6 +- src/shared/terminal-output-side-effects.ts | 6 +- 9 files changed, 619 insertions(+), 19 deletions(-) create mode 100644 src/main/runtime/orchestration-codex-completion-title.test.ts create mode 100644 src/main/runtime/orchestration-codex-real-pty.integration.test.ts diff --git a/src/main/runtime/orca-runtime-apply-tracked-pty-title.ts b/src/main/runtime/orca-runtime-apply-tracked-pty-title.ts index d8273c7eb9c..605eacdbe29 100644 --- a/src/main/runtime/orca-runtime-apply-tracked-pty-title.ts +++ b/src/main/runtime/orca-runtime-apply-tracked-pty-title.ts @@ -38,6 +38,9 @@ export class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWithGetUnper pty.lastOscTitleEpochMs = observedAtEpochMs pty.lastAgentStatus = agentStatus pty.lastAgentStatusObservedLive = true + if (prevStatus === 'working' && agentStatus === null) { + this.confirmPtyAgentExit(ptyId, true) + } if (prevStatus !== agentStatus) { pty.lastAgentStatusStartedAtEpochMs = observedAtEpochMs } diff --git a/src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts b/src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts index 2c3d8b3bc80..81696fe4739 100644 --- a/src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts +++ b/src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts @@ -69,32 +69,67 @@ export class OrcaRuntimeWithSerializeAgentPromptSubmission extends OrcaRuntimeWi return this.ptyForegroundAgent.read(ptyId, afterTitleObservation) } - protected confirmPtyAgentExit(ptyId: string): void { + protected confirmPtyAgentExit(ptyId: string, recoverCompletedHook = false): void { const pty = this.ptysById.get(ptyId) + const handle = this.handleByPtyId.get(ptyId) + if ( + recoverCompletedHook && + (!handle || this.getFreshExplicitAgentStatusForPty(handle, ptyId)?.status !== 'idle') + ) { + return + } + const incarnationId = pty?.incarnationId + const generation = recoverCompletedHook ? this.getPtyLifecycleGeneration(ptyId) : null const titleObservedAt = pty?.lastOscTitleAt ?? null const foregroundRead = this.readPtyForegroundProcessFromController(ptyId, titleObservedAt ?? 0) if (!pty?.connected || !foregroundRead) { - this.recordTerminalSideEffectFact(ptyId, { kind: 'agent-exited' }) + if (!recoverCompletedHook) { + this.recordTerminalSideEffectFact(ptyId, { kind: 'agent-exited' }) + } return } void foregroundRead.then((result) => { const current = this.ptysById.get(ptyId) - if (current !== pty || !current.connected) { + if ( + current !== pty || + !current.connected || + current.incarnationId !== incarnationId || + (recoverCompletedHook && this.getPtyLifecycleGeneration(ptyId) !== generation) + ) { return } if (current.lastOscTitleAt !== titleObservedAt && current.lastAgentStatus !== null) { return } + if ( + recoverCompletedHook && + (!current.lastAgentStatusObservedLive || + this.getFreshExplicitAgentStatusForPty(handle, ptyId)?.status !== 'idle') + ) { + return + } + if (recoverCompletedHook && current.lastOscTitleAt !== titleObservedAt) { + this.confirmPtyAgentExit(ptyId, true) + return + } if ( result.controller === this.ptyController && result.available && recognizeAgentProcess(result.process) !== null ) { + // Codex's final native spinner can arrive after its done hook, then clear to the cwd. + const confirmedStatus = + recoverCompletedHook && recognizeAgentProcess(result.process)?.agent === 'codex' + ? 'idle' + : undefined const restoredStatus = this.ptyTitleTrackersByPtyId .get(ptyId) - ?.tracker.restoreLastAgentExit() + ?.tracker.restoreLastAgentExit(confirmedStatus) if (restoredStatus !== null && restoredStatus !== undefined) { current.lastAgentStatus = restoredStatus + if (restoredStatus === 'idle') { + this.resolvePtyTuiIdleWaiters(current, ptyId) + } for (const leaf of this.getLeavesForPty(ptyId)) { if (leaf.lastAgentStatus !== null) { continue @@ -102,13 +137,16 @@ export class OrcaRuntimeWithSerializeAgentPromptSubmission extends OrcaRuntimeWi // Why: the foreground agent disproved the neutral title's exit signal; keep runtime delivery state aligned with the restored tracker. leaf.lastAgentStatus = restoredStatus if (restoredStatus === 'idle') { + this.resolveTuiIdleWaiters(leaf) this.deliverPendingMessagesForLeaf(leaf) } } } return } - this.recordTerminalSideEffectFact(ptyId, { kind: 'agent-exited' }) + if (!recoverCompletedHook) { + this.recordTerminalSideEffectFact(ptyId, { kind: 'agent-exited' }) + } }) } @@ -157,13 +195,8 @@ export class OrcaRuntimeWithSerializeAgentPromptSubmission extends OrcaRuntimeWi ): AgentPromptActivity { this.assertLiveTerminalHandleTargetsPty(handle, ptyId) const outputSequence = this.getPtyOutputSequence(ptyId) - const explicitCandidate = this.getFreshExplicitAgentStatusForHandle(handle) + const explicit = this.getFreshExplicitAgentStatusForPty(handle, ptyId) const explicitFloor = this.agentPromptExplicitStatusFloorByPtyId.get(ptyId) - const explicit = - explicitCandidate && - (explicitFloor === undefined || explicitCandidate.updatedAt > explicitFloor) - ? explicitCandidate - : null const lifecycle = this.agentPromptLifecycleByPtyId.get(ptyId) const ptyStatus = lifecycle || explicitFloor === undefined @@ -206,4 +239,10 @@ export class OrcaRuntimeWithSerializeAgentPromptSubmission extends OrcaRuntimeWi this.resolveAuthoritativeTerminalWaitPermission(terminal, explicitStatus, lifecycle) !== null ) } + + protected getFreshExplicitAgentStatusForPty(handle: string, ptyId: string) { + const explicit = this.getFreshExplicitAgentStatusForHandle(handle) + const floor = this.agentPromptExplicitStatusFloorByPtyId.get(ptyId) + return explicit && (floor === undefined || explicit.updatedAt > floor) ? explicit : null + } } diff --git a/src/main/runtime/orchestration-codex-completion-title.test.ts b/src/main/runtime/orchestration-codex-completion-title.test.ts new file mode 100644 index 00000000000..92f55d166ff --- /dev/null +++ b/src/main/runtime/orchestration-codex-completion-title.test.ts @@ -0,0 +1,265 @@ +import { rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + AGENT_STATUS_STALE_AFTER_MS, + type AgentStatusIpcPayload +} from '../../shared/agent-status-types' +import { settledWriteStub } from '../providers/settled-pty-write-stub' +import { MAILBOX_POINTER_WRITE_ATTEMPTED } from './orchestration/db/messages/mailbox-pointer-enter-state' +import { + createBoundRun, + createDatabase, + createRuntime, + insertDirectRunMessage, + LEAF_ID, + PANE_KEY, + PTY_ID, + TAB_ID, + TERMINAL_HANDLE, + temporaryDirectories, + WORKTREE_ID +} from './orchestration-mailbox-notification-test-harness' + +vi.mock('electron', () => ({ + app: { getPath: vi.fn(() => tmpdir()), isPackaged: false }, + BrowserWindow: { fromId: vi.fn(() => null) }, + ipcMain: { on: vi.fn(), removeListener: vi.fn() }, + webContents: { fromId: vi.fn(() => null) } +})) + +function completionFixture(delayMs = 0) { + const db = createDatabase('orca-codex-completion-title-') + const hook: AgentStatusIpcPayload = { + paneKey: PANE_KEY, + terminalHandle: TERMINAL_HANDLE, + agentType: 'codex', + state: 'done', + prompt: '', + connectionId: null, + receivedAt: Date.now(), + stateStartedAt: Date.now() + } + const { runtime } = createRuntime(db, { getAgentStatusSnapshot: () => [hook] }) + const write = vi.fn((_ptyId: string, _data: string) => true) + const getForegroundProcess = vi.fn(async (): Promise => { + if (delayMs) { + await new Promise((resolve) => setTimeout(resolve, delayMs)) + } + return 'codex' + }) + runtime.setPtyController({ + write, + writeWithSettlement: settledWriteStub(write), + kill: vi.fn(), + getForegroundProcess + }) + const run = createBoundRun(db, 'Completion title Run') + function completeWithNativeTitles(): void { + runtime.ingestSyntheticTitleFrame(PTY_ID, '\x1b]0;Codex ready\x07') + runtime.onPtyData(PTY_ID, '\x1b]0;⠋ mobile-rearch\x07', 1) + runtime.onPtyData(PTY_ID, '\x1b]0;mobile-rearch\x07', 2) + } + return { db, runtime, write, run, hook, getForegroundProcess, completeWithNativeTitles } +} + +describe('Codex completion title mailbox delivery', () => { + afterEach(() => { + vi.useRealTimers() + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } + }) + + it.each([ + { arrival: 'before', delay: 0 }, + { arrival: 'after', delay: 0 }, + { arrival: 'before', delay: 750 }, + { arrival: 'after', delay: 750 } + ])( + 'submits mail arriving $arrival completion with a $delay ms host probe', + async ({ arrival, delay }) => { + vi.useFakeTimers() + const { db, runtime, write, run, completeWithNativeTitles } = completionFixture(delay) + await runtime.listTerminals() + if (arrival === 'before') { + insertDirectRunMessage(db, run.id, 'Worker progress') + } + completeWithNativeTitles() + await vi.advanceTimersByTimeAsync(100) + if (arrival === 'after') { + insertDirectRunMessage(db, run.id, 'Worker progress') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + } + await vi.advanceTimersByTimeAsync(500) + if (delay) { + expect(write).not.toHaveBeenCalledWith(PTY_ID, '\r') + } + await vi.advanceTimersByTimeAsync(1000) + expect(write.mock.calls.map(([, data]) => data)).toEqual([ + expect.stringContaining('You have 1 orchestration message'), + '\r' + ]) + db.close() + } + ) + + it.each([ + { name: 'shell', process: 'zsh' }, + { name: 'unverifiable foreground', process: null }, + { name: 'different agent', process: 'claude' }, + { name: 'working hook', state: 'working' as const }, + { name: 'permission hook', state: 'blocked' as const }, + { name: 'restored hook', restoredUnconfirmed: true }, + { name: 'stale hook', age: AGENT_STATUS_STALE_AFTER_MS + 1 } + ])('does not recover idle from $name', async (scenario) => { + vi.useFakeTimers() + const { db, runtime, write, run, hook, getForegroundProcess, completeWithNativeTitles } = + completionFixture() + if (scenario.process !== undefined) { + getForegroundProcess.mockResolvedValue(scenario.process) + } + if (scenario.state !== undefined) { + hook.state = scenario.state + } + if ('restoredUnconfirmed' in scenario) { + hook.restoredUnconfirmed = true + } + if (scenario.age !== undefined) { + hook.receivedAt -= scenario.age + } + await runtime.listTerminals() + completeWithNativeTitles() + await vi.advanceTimersByTimeAsync(100) + insertDirectRunMessage(db, run.id, 'Worker progress') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + await vi.advanceTimersByTimeAsync(1000) + expect(write).not.toHaveBeenCalled() + db.close() + }) + + it('does not restore idle over a permission title received during the host probe', async () => { + vi.useFakeTimers() + const { db, runtime, write, run, completeWithNativeTitles } = completionFixture(750) + await runtime.listTerminals() + insertDirectRunMessage(db, run.id, 'Worker progress') + completeWithNativeTitles() + runtime.onPtyData(PTY_ID, '\x1b]0;Codex waiting for permission\x07', 3) + await vi.advanceTimersByTimeAsync(1500) + expect(write.mock.calls.map(([, data]) => data)).toEqual([ + expect.stringContaining('You have 1 orchestration message') + ]) + db.close() + }) + + it('keeps an unverified staged pointer pending and submits it once readiness returns', async () => { + vi.useFakeTimers() + const { db, runtime, write, run, getForegroundProcess, completeWithNativeTitles } = + completionFixture() + getForegroundProcess.mockResolvedValue(null) + await runtime.listTerminals() + const message = insertDirectRunMessage(db, run.id, 'Worker progress') + completeWithNativeTitles() + await vi.advanceTimersByTimeAsync(10 * 60_000) + expect(write.mock.calls.map(([, data]) => data)).toEqual([ + expect.stringContaining('You have 1 orchestration message') + ]) + expect(db.getMessageById(message.id)).toMatchObject({ + read: 0, + delivered_at: null, + pointer_enter_pending: MAILBOX_POINTER_WRITE_ATTEMPTED + }) + + runtime.ingestSyntheticTitleFrame(PTY_ID, '\x1b]0;Codex ready\x07') + await vi.advanceTimersByTimeAsync(1000) + expect(write.mock.calls.map(([, data]) => data)).toEqual([ + expect.stringContaining('You have 1 orchestration message'), + '\r' + ]) + expect(db.getMessageById(message.id)).toMatchObject({ pointer_enter_pending: 0 }) + db.close() + }) + + it('rechecks a repeated neutral title before resuming the staged Enter', async () => { + vi.useFakeTimers() + const { db, runtime, write, run, completeWithNativeTitles } = completionFixture(750) + await runtime.listTerminals() + insertDirectRunMessage(db, run.id, 'Worker progress') + completeWithNativeTitles() + await vi.advanceTimersByTimeAsync(100) + runtime.onPtyData(PTY_ID, '\x1b]0;mobile-rearch\x07', 3) + await vi.advanceTimersByTimeAsync(700) + expect(write).not.toHaveBeenCalledWith(PTY_ID, '\r') + await vi.advanceTimersByTimeAsync(1500) + expect(write.mock.calls.map(([, data]) => data)).toEqual([ + expect.stringContaining('You have 1 orchestration message'), + '\r' + ]) + db.close() + }) + + it('does not restore a completed hook after a new turn starts during the probe', async () => { + vi.useFakeTimers() + const { db, runtime, write, run, hook, completeWithNativeTitles } = completionFixture(750) + await runtime.listTerminals() + completeWithNativeTitles() + hook.state = 'working' + insertDirectRunMessage(db, run.id, 'Worker progress') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + await vi.advanceTimersByTimeAsync(1500) + expect(write).not.toHaveBeenCalled() + db.close() + }) + + it('does not restore completion into a replacement process using the same PTY id', async () => { + vi.useFakeTimers() + const { db, runtime, write, run, completeWithNativeTitles } = completionFixture(750) + await runtime.listTerminals() + completeWithNativeTitles() + runtime.registerPty(PTY_ID, WORKTREE_ID, null, { + tabId: TAB_ID, + leafId: LEAF_ID, + incarnationId: 'replacement-incarnation' + }) + insertDirectRunMessage(db, run.id, 'Worker progress') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + await vi.advanceTimersByTimeAsync(1500) + expect(write).not.toHaveBeenCalled() + db.close() + }) + + it('does not reuse a completion hook from before a provider generation reset', async () => { + vi.useFakeTimers() + const { db, runtime, write, run } = completionFixture() + await runtime.listTerminals() + runtime.ingestSyntheticTitleFrame(PTY_ID, '\x1b]0;Codex ready\x07') + await vi.advanceTimersByTimeAsync(10) + runtime.synchronizePtyOutputSequenceFromProvider(PTY_ID, { value: 0, generation: 'reset' }) + runtime.onPtyData(PTY_ID, '\x1b]0;⠋ mobile-rearch\x07', 1) + runtime.onPtyData(PTY_ID, '\x1b]0;mobile-rearch\x07', 2) + await vi.advanceTimersByTimeAsync(100) + insertDirectRunMessage(db, run.id, 'Worker progress') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + await vi.advanceTimersByTimeAsync(1000) + expect(write).not.toHaveBeenCalled() + db.close() + }) + + it('discards a foreground probe spanning a generation reset even with a newer done hook', async () => { + vi.useFakeTimers() + const { db, runtime, write, run, hook, completeWithNativeTitles } = completionFixture(750) + await runtime.listTerminals() + completeWithNativeTitles() + await vi.advanceTimersByTimeAsync(100) + runtime.synchronizePtyOutputSequenceFromProvider(PTY_ID, { value: 0, generation: 'reset' }) + await vi.advanceTimersByTimeAsync(1) + hook.receivedAt = Date.now() + hook.stateStartedAt = Date.now() + await vi.advanceTimersByTimeAsync(1000) + insertDirectRunMessage(db, run.id, 'Worker progress') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + await vi.advanceTimersByTimeAsync(1000) + expect(write).not.toHaveBeenCalled() + db.close() + }) +}) diff --git a/src/main/runtime/orchestration-codex-real-pty.integration.test.ts b/src/main/runtime/orchestration-codex-real-pty.integration.test.ts new file mode 100644 index 00000000000..28be6b513a7 --- /dev/null +++ b/src/main/runtime/orchestration-codex-real-pty.integration.test.ts @@ -0,0 +1,272 @@ +import { createServer } from 'node:http' +import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import * as pty from 'node-pty' +import { expect, it, vi } from 'vitest' +import { AgentHookServer } from '../agent-hooks/server' +import { getManagedScript } from '../codex/codex-hook-script' +import { getSyntheticAgentTerminalTitle } from '../../shared/synthetic-agent-title' +import { extractAllOscTitles } from '../../shared/osc-title-extraction' +import { extractOscTitleScanTail } from '../../shared/osc-title-scan-tail' +import { settledWriteStub } from '../providers/settled-pty-write-stub' +import { + createBoundRun, + createDatabase, + createRuntime, + insertDirectRunMessage, + LAUNCH_TOKEN, + PANE_KEY, + PTY_ID, + TAB_ID, + WORKTREE_ID, + temporaryDirectories +} from './orchestration-mailbox-notification-test-harness' + +vi.mock('electron', () => ({ + app: { getPath: vi.fn(() => tmpdir()), isPackaged: false }, + BrowserWindow: { fromId: vi.fn(() => null) }, + ipcMain: { on: vi.fn(), removeListener: vi.fn() }, + webContents: { fromId: vi.fn(() => null) } +})) + +const binary = process.env.ORCA_REPRO_CODEX_BINARY +const trials = (['before', 'after'] as const).flatMap((arrival) => + [1, 2, 3].map((trial) => ({ arrival, trial })) +) +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +it.skipIf(!binary || process.platform === 'win32').each(trials)( + 'submits mail arriving $arrival a real Codex completion (trial $trial)', + async ({ arrival }) => { + const directory = realpathSync(mkdtempSync(join(tmpdir(), 'orca-codex-mailbox-'))) + const workspace = join(directory, 'work') + mkdirSync(workspace) + const trace: { ms: number; kind: string; value: unknown }[] = [] + const start = performance.now() + const record = (kind: string, value: unknown) => { + trace.push({ ms: Math.round(performance.now() - start), kind, value }) + } + let raw = '' + let submittedMail = false + let requests = 0 + const model = createServer(async (req, res) => { + if (req.method !== 'POST') { + res.writeHead(404).end() + return + } + let body = '' + for await (const chunk of req) { + body += chunk + } + const notification = body.includes('You have 1 orchestration message') + if (notification) { + submittedMail = true + } + const id = `response-${++requests}` + record('model-request', { id, notification }) + res.writeHead(200, { 'Content-Type': 'text/event-stream' }) + await delay(400) + const events = [ + { type: 'response.created', response: { id } }, + { + type: 'response.output_item.done', + item: { + type: 'message', + role: 'assistant', + id: `msg-${id}`, + content: [{ type: 'output_text', text: 'Fixture finished.' }] + } + }, + { + type: 'response.completed', + response: { id, usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } } + } + ] + for (const event of events) { + res.write(`data: ${JSON.stringify(event)}\n\n`) + } + res.end() + }) + await new Promise((resolve) => model.listen(0, '127.0.0.1', resolve)) + const address = model.address() + if (!address || typeof address === 'string') { + throw new Error('Missing fixture port') + } + const hooks = new AgentHookServer() + await hooks.start() + const db = createDatabase('orca-codex-mailbox-db-') + const { runtime } = createRuntime(db, { + getAgentStatusSnapshot: () => hooks.getStatusSnapshot() + }) + const run = createBoundRun(db, 'Real Codex completion') + let queuedMail = false + let stops = 0 + hooks.setListener((event) => { + record('hook', { event: event.hookEventName, state: event.payload.state }) + if (event.hookEventName === 'UserPromptSubmit' && !queuedMail && arrival === 'before') { + queuedMail = true + insertDirectRunMessage(db, run.id, 'Worker progress') + } + if (event.hookEventName === 'Stop') { + stops++ + } + const title = getSyntheticAgentTerminalTitle(event.payload.agentType, event.payload.state) + if (title) { + record('hook-title', title) + runtime.ingestSyntheticTitleFrame(PTY_ID, `\x1b]0;${title}\x07`) + } + }) + const script = join(directory, 'orca-hook.sh') + writeFileSync(script, getManagedScript('posix')) + const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'` + writeFileSync( + join(directory, 'hooks.json'), + JSON.stringify({ + hooks: Object.fromEntries( + ['SessionStart', 'UserPromptSubmit', 'Stop'].map((event) => [ + event, + [ + { + hooks: [ + { + type: 'command', + // Hold real hook completion open across native animation ticks; no title bytes are invented. + command: `sh ${quote(script)}${event === 'Stop' ? '; sleep 0.2' : ''}` + } + ] + } + ] + ]) + ) + }) + ) + writeFileSync( + join(directory, 'config.toml'), + [ + 'model="gpt-5.6-terra"', + 'model_provider="fixture"', + 'check_for_update_on_startup=false', + '[model_providers.fixture]', + 'name="fixture"', + `base_url="http://127.0.0.1:${address.port}/v1"`, + 'wire_api="responses"', + 'requires_openai_auth=false', + '[tui]', + 'terminal_title=["spinner","project-name"]', + `[projects.${JSON.stringify(workspace)}]`, + 'trust_level="trusted"' + ].join('\n') + ) + const env = Object.fromEntries( + Object.entries(process.env).filter( + ([key, value]) => + value !== undefined && !key.startsWith('ORCA_') && !key.startsWith('CODEX_') + ) + ) as Record + const terminal = pty.spawn( + binary!, + ['--no-alt-screen', '--dangerously-bypass-hook-trust', 'Reply OK only'], + { + name: 'xterm-256color', + cols: 120, + rows: 40, + cwd: workspace, + env: { + ...env, + ...hooks.buildPtyEnv(), + CODEX_HOME: directory, + TERM: 'xterm-256color', + ORCA_BACKGROUND_LAUNCH: '1', + ORCA_PANE_KEY: PANE_KEY, + ORCA_TAB_ID: TAB_ID, + ORCA_WORKTREE_ID: WORKTREE_ID, + ORCA_AGENT_LAUNCH_TOKEN: LAUNCH_TOKEN + } + } + ) + let exited = false + const exit = new Promise((resolve) => + terminal.onExit(() => { + exited = true + resolve() + }) + ) + const writes: string[] = [] + const write = (_id: string, data: string) => { + record('input', data) + writes.push(data) + terminal.write(data) + return true + } + runtime.setPtyController({ + write, + writeWithSettlement: settledWriteStub(write), + kill: () => { + terminal.kill() + return true + }, + getForegroundProcess: async () => { + const name = terminal.process + record('foreground', name) + return name + } + }) + let seq = 0 + let osc = '' + terminal.onData((data) => { + raw += data + if (data.includes('\x1b[6n')) { + terminal.write('\x1b[1;1R') + } + osc += data + const titles = extractAllOscTitles(osc) + for (const title of titles) { + record('native-title', title) + } + const nativeIdle = titles.includes('work') + osc = extractOscTitleScanTail(osc) + runtime.onPtyData(PTY_ID, data, ++seq) + if (arrival === 'after' && stops > 0 && !queuedMail && nativeIdle) { + queuedMail = true + insertDirectRunMessage(db, run.id, 'Later worker progress') + runtime.notifyMessageArrived(`run:${run.id}`, 'status') + record('later-mail', 'arrived after the native idle title') + } + }) + try { + await runtime.listTerminals() + const deadline = Date.now() + 10_000 + while (!submittedMail && !exited && Date.now() < deadline) { + await delay(50) + } + record('result', { arrival, submittedMail, stops, writes }) + const stopIndex = trace.findIndex( + (event) => event.kind === 'hook' && (event.value as { event: string }).event === 'Stop' + ) + expect(stopIndex).toBeGreaterThan(-1) + const tail = trace.slice(stopIndex + 1).filter((event) => event.kind === 'native-title') + expect(tail.some((event) => /^[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏] work$/.test(String(event.value)))).toBe(true) + expect(tail.some((event) => event.value === 'work')).toBe(true) + expect(writes.filter((data) => data === '\r')).toHaveLength(1) + expect(submittedMail).toBe(true) + } finally { + if (!exited) { + terminal.kill('SIGKILL') + } + await Promise.race([exit, delay(2000)]) + hooks.stop() + model.closeAllConnections() + await new Promise((resolve) => model.close(() => resolve())) + record('artifact', directory) + writeFileSync(join(directory, 'trace.json'), JSON.stringify(trace, null, 2)) + writeFileSync(join(directory, 'terminal.bin'), raw) + console.log(`Real Codex evidence: ${directory}`) + db.close() + for (const path of temporaryDirectories.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } + } + }, + 20_000 +) diff --git a/src/main/runtime/orchestration-mailbox-notification-test-harness.ts b/src/main/runtime/orchestration-mailbox-notification-test-harness.ts index 1289c340aca..7bd3ae4665e 100644 --- a/src/main/runtime/orchestration-mailbox-notification-test-harness.ts +++ b/src/main/runtime/orchestration-mailbox-notification-test-harness.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, vi } from 'vitest' import { ORCHESTRATION_CONTRACT_VERSION } from '../../shared/protocol-version' +import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' import type Database from '../sqlite/sync-database' import { OrcaRuntimeService } from './orca-runtime' import { OrchestrationDb } from './orchestration/db' @@ -84,9 +85,14 @@ export type MailboxCheckOptions = { export function createRuntime( db: OrchestrationDb, - options: { connectionId?: string; isWsl?: boolean } = {} + options: { + connectionId?: string + isWsl?: boolean + getAgentStatusSnapshot?: () => AgentStatusIpcPayload[] + } = {} ): MailboxNotificationHarness { const runtime = new OrcaRuntimeService(null, undefined, { + getAgentStatusSnapshot: options.getAgentStatusSnapshot, attestAgentHookCompatibilityAuthority: ({ paneKey }) => paneKey === PANE_KEY || paneKey.startsWith(`${SECOND_TAB_ID}:`) ? { paneKey, source: 'current_hook' } diff --git a/src/main/runtime/orchestration/mailbox-pointer-submit.ts b/src/main/runtime/orchestration/mailbox-pointer-submit.ts index 4d54f8ad70c..0f078466ea0 100644 --- a/src/main/runtime/orchestration/mailbox-pointer-submit.ts +++ b/src/main/runtime/orchestration/mailbox-pointer-submit.ts @@ -53,6 +53,7 @@ export function submitOrchestrationMailboxPointer message.id) const reservationTarget = { @@ -87,6 +88,14 @@ export function submitOrchestrationMailboxPointer submitOrchestrationMailboxPointer(deps, input) + deferredUntilIdle = true } else if (!queueSafe) { releaseWithoutRedrive = true } else { @@ -127,6 +136,9 @@ export function submitOrchestrationMailboxPointer { + if (deferredUntilIdle) { + return + } let released = false let rollbackPersisted = true if (finalizeReservation) { diff --git a/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts index d83043edd5a..a2b049e4190 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts @@ -133,7 +133,10 @@ describe('committed adopting create RPC replay', () => { const selectAccountHome = vi.fn(() => selectedHome) const runtime = new OrcaRuntimeService( { - getSettings: () => ({ agentDefaultEnv: { codex: {} } }) + getSettings: () => ({ + experimentalStructuredNativeChat: true, + agentDefaultEnv: { codex: {} } + }) } as never, undefined, { prepareCodexStructuredLaunch: selectAccountHome } diff --git a/src/shared/agent-title-status.ts b/src/shared/agent-title-status.ts index fa1e35652e2..a74ae15d6bf 100644 --- a/src/shared/agent-title-status.ts +++ b/src/shared/agent-title-status.ts @@ -73,7 +73,7 @@ export function createAgentStatusTracker( ): { handleTitle: (title: string) => void seedTitle: (title: string) => void - restoreLastExit: () => AgentStatus | null + restoreLastExit: (confirmedStatus?: AgentStatus) => AgentStatus | null reset: () => void } { // Why: trackers restored mid-session need a last-known status without firing @@ -109,8 +109,8 @@ export function createAgentStatusTracker( lastStatus = detectAgentStatusFromTitle(title) restorableExitStatus = null }, - restoreLastExit(): AgentStatus | null { - const restoredStatus = lastStatus === null ? restorableExitStatus : null + restoreLastExit(confirmedStatus?: AgentStatus): AgentStatus | null { + const restoredStatus = confirmedStatus ?? (lastStatus === null ? restorableExitStatus : null) if (restoredStatus !== null) { lastStatus = restoredStatus } diff --git a/src/shared/terminal-output-side-effects.ts b/src/shared/terminal-output-side-effects.ts index d8b39e954e1..20128c63234 100644 --- a/src/shared/terminal-output-side-effects.ts +++ b/src/shared/terminal-output-side-effects.ts @@ -93,7 +93,7 @@ export type TerminalTitleTracker = { */ seedInitialTitle: (rawTitle: string) => void /** Restore the status consumed by the latest exit candidate when process evidence disproves it. */ - restoreLastAgentExit: () => AgentStatus | null + restoreLastAgentExit: (confirmedStatus?: AgentStatus) => AgentStatus | null /** Last title surfaced through onTitle, after normalization. */ getLastNormalizedTitle: () => string | null /** @@ -280,8 +280,8 @@ export function createTerminalTitleTracker( agentTracker?.seedTitle(rawTitle) } }, - restoreLastAgentExit(): AgentStatus | null { - return agentTracker?.restoreLastExit() ?? null + restoreLastAgentExit(confirmedStatus?: AgentStatus): AgentStatus | null { + return agentTracker?.restoreLastExit(confirmedStatus) ?? null }, getLastNormalizedTitle: () => lastEmittedTitle, setTransientFactScanningSuppressed(suppressed: boolean): void { From ecfcc0d833e2e53735caa90c73436b21d2d055ae Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 04:40:34 -0400 Subject: [PATCH 05/37] feat(relay): time successful client accepts and control round trips (#19232) * feat(relay): time successful client accepts and control round trips A 6s accept on a cross-region cell was invisible: only the abandoned path was timed. Record per-stage durations across acceptClient and acceptHostData (assignment/credential/activity/attach), emit one completed log line per accept, and aggregate p50/p95/max into the runtime metrics event. Sample control ping round trips from the pong echo so a host sitting on a distant cell is visible fleet-wide and per host, rate-limited to one log line an hour per session. * fix(relay): review round 1 on accept and control-RTT timing Omit the accept and RTT percentiles from windows with no samples: accepts are sparse, so a zero point every 30s would pin the p50 at 0 and collapse the p95. The *Delta counts still publish, and say when the omission is expected. Control-renewal output is unchanged. Add a `basis` stage for the splice lease and connection-basis writes that run between the host data leg and relay-hello, and start `attach` where the activity stage ended, so the stages now tile the whole accept and their sum equals totalMs. Clamp every stage at zero against a backwards clock step. Carry role/cellId/region on both new log lines, flatten the stage p95 field names so the log-metric extractors stay top-level, and record that only the RTT median reads as distance: the desktop echoes the pong on its main thread, so the p95 and max track desktop stalls. --- .../src/host-session-client-accept.test.ts | 178 +++++++++++++++++- cloud/apps/relay/src/host-session-registry.ts | 131 ++++++++++++- .../relay/src/relay-observability.test.ts | 72 ++++++- cloud/apps/relay/src/relay-observability.ts | 105 +++++++++-- cloud/infra/terraform/relay-observability.tf | 17 +- 5 files changed, 481 insertions(+), 22 deletions(-) diff --git a/cloud/apps/relay/src/host-session-client-accept.test.ts b/cloud/apps/relay/src/host-session-client-accept.test.ts index 83b6c21f997..5beef7723f5 100644 --- a/cloud/apps/relay/src/host-session-client-accept.test.ts +++ b/cloud/apps/relay/src/host-session-client-accept.test.ts @@ -1,5 +1,5 @@ import { EventEmitter } from 'node:events' -import { RELAY_CLOSE_CODE } from '@orca-cloud/relay-contract' +import { RELAY_CLOSE_CODE, RELAY_PROTOCOL_LIMITS } from '@orca-cloud/relay-contract' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type WebSocket from 'ws' import type { RelayAssignmentStore } from './assignment-store.js' @@ -102,7 +102,9 @@ function harness(options: { random?: () => number; now?: () => number } = {}) { const store = { resolveResume: vi.fn().mockResolvedValue({ userId: identity.sub }), reserveCredential: vi.fn().mockResolvedValue(reservation), - failReservation: vi.fn().mockResolvedValue(undefined) + failReservation: vi.fn().mockResolvedValue(undefined), + recordConnectionBasis: vi.fn().mockResolvedValue(undefined), + deactivateBasis: vi.fn().mockResolvedValue(undefined) } const observer = { recordAuth: vi.fn(), @@ -110,7 +112,9 @@ function harness(options: { random?: () => number; now?: () => number } = {}) { recordHttp: vi.fn(), recordReconnect: vi.fn(), recordSql: vi.fn(), - recordClientAcceptAbandoned: vi.fn() + recordClientAcceptAbandoned: vi.fn(), + recordClientAcceptCompleted: vi.fn(), + recordControlRtt: vi.fn() } satisfies RelayRuntimeObserver const registry = new HostSessionRegistry( config, @@ -325,6 +329,174 @@ describe('client accept abandoned mid-DB-phase', () => { }) }) +describe('successful client accept timing', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + }) + + it('times every serialized stage plus the attach window once relay-hello lands', async () => { + let now = 1_700_000_000_000 + const h = harness({ now: () => now }) + const control = await activeHost(h) + h.store.resolveResume.mockImplementationOnce(async () => { + now += 5 + return { userId: identity.sub } + }) + h.store.reserveCredential.mockImplementationOnce(async () => { + now += 7 + return reservation + }) + h.acquireActivity.mockImplementationOnce(async () => { + now += 11 + }) + h.store.recordConnectionBasis.mockImplementationOnce(async () => { + now += 3 + }) + const client = new FakeSocket() + const hostData = new FakeSocket() + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined) + try { + await h.registry.acceptClient(client as unknown as WebSocket, identity.relayHostId, 'cred') + const connOpen = JSON.parse( + String(control.send.mock.calls.find((call) => String(call[0]).includes('conn-open'))![0]) + ) as { connId: string; connTicket: string } + // The desktop's data leg is the attach window this is meant to expose. + now += 23 + const accepted = await h.registry.acceptHostData( + hostData as unknown as WebSocket, + connOpen.connId, + connOpen.connTicket, + 1 + ) + + expect(accepted).toBe(true) + expect(h.observer.recordClientAcceptCompleted).toHaveBeenCalledWith({ + totalMs: 49, + stageMs: { assignment: 5, credential: 7, activity: 11, attach: 23, basis: 3 } + }) + const line = log.mock.calls + .map((call) => String(call[0])) + .find((entry) => entry.includes('orca_relay_client_accept_completed')) + expect(line).toBeDefined() + const event = JSON.parse(line!) as { + role: string + cellId: string + region: string + credentialKind: string + stageMs: Record + totalMs: number + relayHostIdDigest: string + } + expect(event.credentialKind).toBe('resume') + // Joins the line back to the emitting process, like the runtime metrics event. + expect(event).toMatchObject({ role: 'cell', cellId: config.cellId, region: 'us-central1' }) + expect(Object.keys(event.stageMs).sort()).toEqual([ + 'activity', + 'assignment', + 'attach', + 'basis', + 'credential' + ]) + for (const stage of Object.values(event.stageMs)) expect(stage).toBeGreaterThanOrEqual(0) + // The stages tile the accept end to end: every millisecond is attributed. + const summed = Object.values(event.stageMs).reduce((total, stage) => total + stage, 0) + expect(summed).toBe(event.totalMs) + expect(event.relayHostIdDigest).toMatch(/^[0-9a-f]{12}$/) + expect(line).not.toContain(identity.relayHostId) + } finally { + log.mockRestore() + h.registry.drain(0) + vi.advanceTimersByTime(0) + } + }) +}) + +describe('control round-trip sampling', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + }) + + it('logs a host once at the fourth sample and not again within the hour', async () => { + let now = 1_700_000_000_000 + const h = harness({ now: () => now }) + const control = await activeHost(h) + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined) + const rttLines = (): string[] => + log.mock.calls + .map((call) => String(call[0])) + .filter((entry) => entry.includes('orca_relay_host_control_rtt')) + // One heartbeat, then the desktop's echo of that ping's own `t` 40 ms later. + const roundTrip = async (): Promise => { + now += RELAY_PROTOCOL_LIMITS.controlPingIntervalMs + await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) + const ping = JSON.parse( + String( + control.send.mock.calls + .filter((call) => String(call[0]).includes('"type":"ping"')) + .at(-1)![0] + ) + ) as { t: number } + now += 40 + control.emit('message', JSON.stringify({ type: 'pong', t: ping.t }), false) + } + try { + for (let round = 0; round < 3; round++) await roundTrip() + expect(h.observer.recordControlRtt).toHaveBeenCalledTimes(3) + expect(rttLines()).toHaveLength(0) + + await roundTrip() + expect(h.observer.recordControlRtt).toHaveBeenLastCalledWith(40) + expect(rttLines()).toHaveLength(1) + expect(JSON.parse(rttLines()[0]!)).toMatchObject({ + event: 'orca_relay_host_control_rtt', + role: 'cell', + cellId: config.cellId, + region: 'us-central1', + rttMsMedian: 40, + sampleCount: 4 + }) + expect(rttLines()[0]).not.toContain(identity.relayHostId) + + // Later samples keep feeding the fleet metric, but stay silent for an hour. + for (let round = 0; round < 8; round++) await roundTrip() + expect(h.observer.recordControlRtt).toHaveBeenCalledTimes(12) + expect(rttLines()).toHaveLength(1) + + const elapsedStart = now + while (now - elapsedStart < 60 * 60 * 1000) await roundTrip() + expect(rttLines()).toHaveLength(2) + } finally { + log.mockRestore() + h.registry.drain(0) + vi.advanceTimersByTime(0) + } + }) + + it('ignores a pong whose echoed timestamp is missing or implausible', async () => { + let now = 1_700_000_000_000 + const h = harness({ now: () => now }) + const control = await activeHost(h) + try { + control.emit('message', JSON.stringify({ type: 'pong' }), false) + control.emit('message', JSON.stringify({ type: 'pong', t: 'later' }), false) + control.emit('message', JSON.stringify({ type: 'pong', t: now + 5_000 }), false) + control.emit('message', JSON.stringify({ type: 'pong', t: now - 600_000 }), false) + expect(h.observer.recordControlRtt).not.toHaveBeenCalled() + // The silence watchdog still sees every one of them as proof of life. + now += 10 + control.emit('message', JSON.stringify({ type: 'pong', t: now - 10 }), false) + expect(h.observer.recordControlRtt).toHaveBeenCalledWith(10) + } finally { + h.registry.drain(0) + vi.advanceTimersByTime(0) + } + }) +}) + describe('control lease jitter', () => { beforeEach(() => vi.useFakeTimers()) afterEach(() => { diff --git a/cloud/apps/relay/src/host-session-registry.ts b/cloud/apps/relay/src/host-session-registry.ts index 1b7ed3df4af..9a3d27faf92 100644 --- a/cloud/apps/relay/src/host-session-registry.ts +++ b/cloud/apps/relay/src/host-session-registry.ts @@ -1,6 +1,7 @@ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto' import { ASSIGNMENT_LIMITS, + RELAY_DEFAULT_REGION, AuthRefreshSchema, buildHostChallengePlaintext, buildHostProofMacInput, @@ -15,7 +16,8 @@ import { InviteCreateSchema, RELAY_PROTOCOL_LIMITS, RELAY_CLOSE_CODE, - type RelayHostCloseReason + type RelayHostCloseReason, + type RelayRegion } from '@orca-cloud/relay-contract' import nacl from 'tweetnacl' import type WebSocket from 'ws' @@ -29,7 +31,12 @@ import { import { HostCloseReasonMemory } from './host-close-reason-memory.js' import { relayHostLogDigest } from './relay-host-log-digest.js' import type { RelayTokenClaims } from './relay-token-verifier.js' -import type { RelayClientAcceptStage, RelayRuntimeObserver } from './relay-observability.js' +import { + percentile, + type RelayClientAcceptStage, + type RelayClientAcceptTimedStage, + type RelayRuntimeObserver +} from './relay-observability.js' import type { PendingHostDataReservation } from './relay-connection-ledger.js' import { closeRelayWebSocket } from './relay-websocket-close.js' import { ProcessQueuedByteBudget, wireSplice } from './splice-forwarder.js' @@ -45,6 +52,20 @@ function printableCloseReason(reason: Buffer | string): string { type VerifyRelayToken = (token: string) => Promise type HostState = 'proving' | 'active' | 'orphaned' | 'drain-only' | 'closed' +// A host's distance to its cell moves on the scale of a rehome, not a heartbeat, +// so a short window is enough to ride out one stalled ping. +const CONTROL_RTT_WINDOW = 8 +const CONTROL_RTT_LOG_SAMPLE_THRESHOLD = 4 +const CONTROL_RTT_LOG_INTERVAL_MS = 60 * 60 * 1000 +// A pong claiming a multi-minute round trip is clock skew, not distance. +const CONTROL_RTT_MAX_PLAUSIBLE_MS = 120_000 + +// Wall clock can step backwards mid-accept; a negative latency would poison the +// percentiles it feeds. +function nonNegativeMs(elapsedMs: number): number { + return Math.max(0, elapsedMs) +} + const CONTROL_ACTIVITY_RENEWAL_INTERVAL_MS = RELAY_PROTOCOL_LIMITS.controlPingIntervalMs * 2 // Preserve the existing 75s renewal runway after doubling the successful-call interval. const CONTROL_ACTIVITY_LEASE_MS = @@ -68,6 +89,8 @@ export type HostSession = { orphanTimer: ReturnType | null heartbeatTimer: ReturnType | null lastPongAt: number + controlRttSamplesMs: number[] + controlRttLoggedAt: number | null activityRenewalDueAt: number activityRenewalAttempt: number activityRenewalCompletedAttempt: number @@ -95,6 +118,15 @@ type PendingConnection = { attachTimer: ReturnType credentialActivityId: string | null capacityReservation?: PendingHostDataReservation + timing: ClientAcceptTiming +} + +// Carries the phone-side accept clock across to the desktop's data leg, which +// lands in a separate call and is the only place the accept is known to succeed. +type ClientAcceptTiming = { + startedAt: number + connOpenAt: number + stageMs: Record } function decodeCanonicalBase64(value: string, bytes: number): Uint8Array | null { @@ -192,6 +224,17 @@ export class HostSessionRegistry { ) return true } + const stageMs: Record = { + assignment: 0, + credential: 0, + activity: 0 + } + let stageCursor = acceptStartedAt + const markStage = (stage: RelayClientAcceptStage): void => { + const at = this.now() + stageMs[stage] = at - stageCursor + stageCursor = at + } if (this.config.role === 'cell') { // Each lookup is its own pooled round trip; stop between them once the phone // has left instead of running the rest of the chain for nobody. @@ -212,6 +255,7 @@ export class HostSessionRegistry { } if (abandonedByClient('assignment')) return } + markStage('assignment') const reservation = await this.store.reserveCredential(hostId, credential) if (!reservation) { capacityReservation?.release() @@ -221,6 +265,7 @@ export class HostSessionRegistry { } this.observer.recordAuth(true) if (abandonedByClient('credential', () => this.failReservationBestEffort(reservation))) return + markStage('credential') const sessionKey = this.key(reservation.userId, hostId) const session = this.sessions.get(sessionKey) if ( @@ -275,6 +320,7 @@ export class HostSessionRegistry { ) { return } + markStage('activity') const attachTimer = setTimeout(() => { session.pendingConns.delete(connId) capacityReservation?.release() @@ -289,7 +335,10 @@ export class HostSessionRegistry { client: socket, attachTimer, credentialActivityId, - capacityReservation + capacityReservation, + // Attach starts where the activity stage ended, so the conn-open send is + // charged to it and no wall-clock gap goes unattributed. + timing: { startedAt: acceptStartedAt, connOpenAt: stageCursor, stageMs } } capacityReservation?.bind(connId) session.pendingConns.set(connId, pending) @@ -336,6 +385,7 @@ export class HostSessionRegistry { return false } this.observer.recordAuth(true) + const attachedAt = this.now() clearTimeout(pending.attachTimer) session.pendingConns.delete(connId) session.activeConnIds.add(connId) @@ -409,6 +459,7 @@ export class HostSessionRegistry { close() return false } + const helloAt = this.now() send(pending.client, 'relay-hello', { ok: true, credentialKind: pending.reservation.credentialKind, @@ -424,9 +475,80 @@ export class HostSessionRegistry { } : {}) }) + this.recordClientAcceptCompleted(session, pending, attachedAt, helloAt) return true } + // The stages tile the whole accept, so their sum is the total minus only the + // clamping above: `basis` is the splice lease and connection-basis writes that + // land between the host data leg and relay-hello. + private recordClientAcceptCompleted( + session: HostSession, + pending: PendingConnection, + attachedAt: number, + helloAt: number + ): void { + const stageMs: Record = { + assignment: nonNegativeMs(pending.timing.stageMs.assignment), + credential: nonNegativeMs(pending.timing.stageMs.credential), + activity: nonNegativeMs(pending.timing.stageMs.activity), + attach: nonNegativeMs(attachedAt - pending.timing.connOpenAt), + basis: nonNegativeMs(helloAt - attachedAt) + } + const totalMs = nonNegativeMs(helloAt - pending.timing.startedAt) + this.observer.recordClientAcceptCompleted?.({ totalMs, stageMs }) + console.log( + JSON.stringify({ + event: 'orca_relay_client_accept_completed', + ...this.logIdentity(), + credentialKind: pending.reservation.credentialKind, + stageMs, + totalMs, + relayHostIdDigest: relayHostLogDigest(session.relayHostId) + }) + ) + } + + // Matches the runtime metrics event so a log line and a metric point can be + // joined back to the process that emitted them. + private logIdentity(): { role: string; cellId: string; region: RelayRegion } { + return { + role: this.config.role, + cellId: this.config.cellId, + region: this.config.region ?? RELAY_DEFAULT_REGION + } + } + + // Every desktop build already echoes the ping's `t`; anything else is dropped + // rather than trusted, so no new wire field is required. + private recordControlRtt(session: HostSession, echoedPingAt: unknown): void { + if (typeof echoedPingAt !== 'number' || !Number.isFinite(echoedPingAt)) return + const now = this.now() + const rttMs = now - echoedPingAt + if (rttMs < 0 || rttMs > CONTROL_RTT_MAX_PLAUSIBLE_MS) return + this.observer.recordControlRtt?.(rttMs) + const samples = session.controlRttSamplesMs + samples.push(rttMs) + if (samples.length > CONTROL_RTT_WINDOW) samples.shift() + if (samples.length < CONTROL_RTT_LOG_SAMPLE_THRESHOLD) return + if ( + session.controlRttLoggedAt !== null && + now - session.controlRttLoggedAt < CONTROL_RTT_LOG_INTERVAL_MS + ) { + return + } + session.controlRttLoggedAt = now + console.log( + JSON.stringify({ + event: 'orca_relay_host_control_rtt', + ...this.logIdentity(), + relayHostIdDigest: relayHostLogDigest(session.relayHostId), + rttMsMedian: percentile(samples, 0.5), + sampleCount: samples.length + }) + ) + } + acceptControl( socket: WebSocket, identity: RelayTokenClaims, @@ -843,6 +965,8 @@ export class HostSessionRegistry { orphanTimer: null, heartbeatTimer: null, lastPongAt: this.now(), + controlRttSamplesMs: [], + controlRttLoggedAt: null, activityRenewalDueAt: this.now() + RELAY_PROTOCOL_LIMITS.controlPingIntervalMs, activityRenewalAttempt: 0, activityRenewalCompletedAttempt: 0, @@ -900,6 +1024,7 @@ export class HostSessionRegistry { const parsed = JSON.parse(raw.toString()) as Record if (parsed.type === 'pong') { session.lastPongAt = this.now() + this.recordControlRtt(session, parsed.t) return } if (parsed.type === 'auth-refresh') { diff --git a/cloud/apps/relay/src/relay-observability.test.ts b/cloud/apps/relay/src/relay-observability.test.ts index fc8a4fcb4af..249b7e0915c 100644 --- a/cloud/apps/relay/src/relay-observability.test.ts +++ b/cloud/apps/relay/src/relay-observability.test.ts @@ -22,6 +22,12 @@ const counts: RelayProcessCounts = { databasePoolWaitMsMax: 1_250 } +// An accept stage is named `credential`, so the leak guard has to see past the +// bucket name to the values it exists to police. +function scrubStageNames(entries: Array>): string { + return JSON.stringify(entries).replaceAll('"credential":', '"stage":') +} + describe('relay observability', () => { it('emits safe readiness dependency outcomes', () => { const entries: Array> = [] @@ -181,7 +187,7 @@ describe('relay observability', () => { controlActivityRecoveryFailuresDelta: 0, httpLatencyMsMax: 0 }) - expect(JSON.stringify(entries)).not.toMatch(/token|credential|userId|relayHostId/) + expect(scrubStageNames(entries)).not.toMatch(/token|credential|userId|relayHostId/) }) it('aggregates control and splice closes as bounded per-reason deltas', () => { @@ -215,6 +221,70 @@ describe('relay observability', () => { }) }) + it('summarises completed client accepts and control round trips per window', () => { + const entries: Array> = [] + const observability = new RelayObservability( + { role: 'cell', cellId: 'production-gce-c28', region: 'asia-east2' }, + (entry) => entries.push(entry) + ) + observability.recordClientAcceptCompleted({ + totalMs: 812.4567, + stageMs: { assignment: 120, credential: 90, activity: 40, attach: 500, basis: 62 } + }) + observability.recordClientAcceptCompleted({ + totalMs: 6_400, + stageMs: { assignment: 4_100, credential: 95, activity: 60, attach: 2_000, basis: 145 } + }) + observability.recordControlRtt(28) + observability.recordControlRtt(240) + observability.recordControlRtt(31) + observability.flush(counts) + observability.flush(counts) + + expect(entries[0]).toMatchObject({ + clientAcceptCompletedDelta: 2, + clientAcceptTotalMsP50: 812.457, + clientAcceptTotalMsP95: 6_400, + clientAcceptTotalMsMax: 6_400, + clientAcceptAssignmentMsP95: 4_100, + clientAcceptCredentialMsP95: 95, + clientAcceptActivityMsP95: 60, + clientAcceptAttachMsP95: 2_000, + clientAcceptBasisMsP95: 145, + controlRttSamplesDelta: 3, + controlRttMsP50: 31, + controlRttMsP95: 240, + controlRttMsMax: 240 + }) + // Only-add: the pre-existing fields still read the same after the extension. + expect(entries[0]).toMatchObject({ + event: 'orca_relay_runtime_metrics', + metricVersion: 2, + clientAcceptsAbandonedByStageDelta: {}, + clientAcceptAbandonedMsMax: 0 + }) + // An empty window publishes counts only: a zero percentile point is + // indistinguishable from a real zero once Cloud Logging aggregates it. + expect(entries[1]).toMatchObject({ clientAcceptCompletedDelta: 0, controlRttSamplesDelta: 0 }) + for (const omitted of [ + 'clientAcceptTotalMsP50', + 'clientAcceptTotalMsP95', + 'clientAcceptTotalMsMax', + 'clientAcceptAssignmentMsP95', + 'clientAcceptCredentialMsP95', + 'clientAcceptActivityMsP95', + 'clientAcceptAttachMsP95', + 'clientAcceptBasisMsP95', + 'controlRttMsP50', + 'controlRttMsP95', + 'controlRttMsMax' + ]) { + expect(entries[1]).not.toHaveProperty(omitted) + expect(entries[0]).toHaveProperty(omitted) + } + expect(scrubStageNames(entries)).not.toMatch(/token|credential|userId|relayHostId/) + }) + it('observes successful and failed database calls including transactions', async () => { const recordSql = vi.fn() const underlying: RelayDatabase = { diff --git a/cloud/apps/relay/src/relay-observability.ts b/cloud/apps/relay/src/relay-observability.ts index 59ff437e40b..c96ef36289c 100644 --- a/cloud/apps/relay/src/relay-observability.ts +++ b/cloud/apps/relay/src/relay-observability.ts @@ -65,11 +65,31 @@ export interface RelayRuntimeObserver { recordControlClose?(code: number): void recordSpliceClose?(trigger: string): void recordClientAcceptAbandoned?(stage: RelayClientAcceptStage, elapsedMs: number): void + recordClientAcceptCompleted?(sample: RelayClientAcceptSample): void + recordControlRtt?(rttMs: number): void } // Which serialized accept step the phone had already hung up behind. export type RelayClientAcceptStage = 'assignment' | 'credential' | 'activity' +// The attach window and the basis writes that follow it are only measurable once +// the host data leg lands, so they join the serialized pre-attach steps on +// completed accepts only. +export type RelayClientAcceptTimedStage = RelayClientAcceptStage | 'attach' | 'basis' + +export const RELAY_CLIENT_ACCEPT_TIMED_STAGES = [ + 'assignment', + 'credential', + 'activity', + 'attach', + 'basis' +] as const satisfies readonly RelayClientAcceptTimedStage[] + +export type RelayClientAcceptSample = { + totalMs: number + stageMs: Record +} + type RelayMetricDeltas = { forwardedBytes: number authSuccesses: number @@ -93,6 +113,9 @@ type RelayMetricDeltas = { spliceClosesByTrigger: Record clientAcceptsAbandonedByStage: Record clientAcceptAbandonedMsMax: number + clientAcceptTotalsMs: number[] + clientAcceptStageSamplesMs: Record + controlRttSamplesMs: number[] controlRenewalLatenciesMs: number[] controlRenewalsByOutcome: Record controlActivityRecoveries: number @@ -124,18 +147,41 @@ const emptyDeltas = (): RelayMetricDeltas => ({ spliceClosesByTrigger: {}, clientAcceptsAbandonedByStage: {}, clientAcceptAbandonedMsMax: 0, + clientAcceptTotalsMs: [], + clientAcceptStageSamplesMs: { + assignment: [], + credential: [], + activity: [], + attach: [], + basis: [] + }, + controlRttSamplesMs: [], controlRenewalLatenciesMs: [], controlRenewalsByOutcome: {}, controlActivityRecoveries: 0, controlActivityRecoveryFailures: 0 }) -function percentile(values: number[], percentileRank: number): number { +export function percentile(values: number[], percentileRank: number): number { if (values.length === 0) return 0 const sorted = [...values].sort((left, right) => left - right) return sorted[Math.ceil(percentileRank * sorted.length) - 1] ?? 0 } +function roundMs(value: number): number { + return Number(value.toFixed(3)) +} + +// Spreading a window into Math.max blows the stack once a busy cell samples +// enough of it, so the maximum is folded instead. +function latencySummary(samples: number[]): { p50: number; p95: number; max: number } { + return { + p50: roundMs(percentile(samples, 0.5)), + p95: roundMs(percentile(samples, 0.95)), + max: roundMs(samples.reduce((highest, sample) => Math.max(highest, sample), 0)) + } +} + export class RelayObservability implements RelayRuntimeObserver { private readonly eventLoop = monitorEventLoopDelay({ resolution: 20 }) private deltas = emptyDeltas() @@ -244,6 +290,17 @@ export class RelayObservability implements RelayRuntimeObserver { ) } + recordClientAcceptCompleted(sample: RelayClientAcceptSample): void { + this.deltas.clientAcceptTotalsMs.push(sample.totalMs) + for (const stage of RELAY_CLIENT_ACCEPT_TIMED_STAGES) { + this.deltas.clientAcceptStageSamplesMs[stage].push(sample.stageMs[stage]) + } + } + + recordControlRtt(rttMs: number): void { + this.deltas.controlRttSamplesMs.push(rttMs) + } + start(readCounts: () => RelayProcessCounts, intervalMs = 30_000): void { if (this.timer) return this.eventLoop.enable() @@ -277,6 +334,11 @@ export class RelayObservability implements RelayRuntimeObserver { controlActivityRecoveryFailures: deltas.controlActivityRecoveryFailures } this.deltas = emptyDeltas() + const acceptTotals = latencySummary(deltas.clientAcceptTotalsMs) + const acceptStageP95 = (stage: RelayClientAcceptTimedStage): number => + roundMs(percentile(deltas.clientAcceptStageSamplesMs[stage], 0.95)) + const controlRtt = latencySummary(deltas.controlRttSamplesMs) + const controlRenewal = latencySummary(deltas.controlRenewalLatenciesMs) const memory = process.memoryUsage() const p99 = this.eventLoop.count === 0 ? 0 : this.eventLoop.percentile(99) / 1_000_000 this.eventLoop.reset() @@ -306,10 +368,33 @@ export class RelayObservability implements RelayRuntimeObserver { controlClosesByCodeDelta: deltas.controlClosesByCode, spliceClosesByTriggerDelta: deltas.spliceClosesByTrigger, clientAcceptsAbandonedByStageDelta: deltas.clientAcceptsAbandonedByStage, - clientAcceptAbandonedMsMax: Number(deltas.clientAcceptAbandonedMsMax.toFixed(3)), + clientAcceptAbandonedMsMax: roundMs(deltas.clientAcceptAbandonedMsMax), + clientAcceptCompletedDelta: deltas.clientAcceptTotalsMs.length, + // Accepts are sparse: publishing a zero percentile for every empty window + // would pin the p50 at 0 forever and collapse the p95 at low accept rates. + ...(deltas.clientAcceptTotalsMs.length === 0 + ? {} + : { + clientAcceptTotalMsP50: acceptTotals.p50, + clientAcceptTotalMsP95: acceptTotals.p95, + clientAcceptTotalMsMax: acceptTotals.max, + clientAcceptAssignmentMsP95: acceptStageP95('assignment'), + clientAcceptCredentialMsP95: acceptStageP95('credential'), + clientAcceptActivityMsP95: acceptStageP95('activity'), + clientAcceptAttachMsP95: acceptStageP95('attach'), + clientAcceptBasisMsP95: acceptStageP95('basis') + }), + controlRttSamplesDelta: deltas.controlRttSamplesMs.length, + ...(deltas.controlRttSamplesMs.length === 0 + ? {} + : { + controlRttMsP50: controlRtt.p50, + controlRttMsP95: controlRtt.p95, + controlRttMsMax: controlRtt.max + }), sqlQueriesDelta: deltas.sqlQueries, sqlFailuresDelta: deltas.sqlFailures, - sqlLatencyMsMax: Number(deltas.sqlLatencyMsMax.toFixed(3)), + sqlLatencyMsMax: roundMs(deltas.sqlLatencyMsMax), controlRenewalsByOutcomeDelta: deltas.controlRenewalsByOutcome, controlRenewalsDelta: deltas.controlRenewalLatenciesMs.length, controlRenewalSuccessesDelta: deltas.controlRenewalsByOutcome.renewed ?? 0, @@ -317,16 +402,10 @@ export class RelayObservability implements RelayRuntimeObserver { deltas.controlRenewalsByOutcome.control_activity_not_found ?? 0, controlActivityRecoveriesDelta: deltas.controlActivityRecoveries, controlActivityRecoveryFailuresDelta: deltas.controlActivityRecoveryFailures, - controlRenewalLatencyMsP50: Number( - percentile(deltas.controlRenewalLatenciesMs, 0.5).toFixed(3) - ), - controlRenewalLatencyMsP95: Number( - percentile(deltas.controlRenewalLatenciesMs, 0.95).toFixed(3) - ), - controlRenewalLatencyMsMax: Number( - Math.max(0, ...deltas.controlRenewalLatenciesMs).toFixed(3) - ), - httpLatencyMsMax: Number(deltas.httpLatencyMsMax.toFixed(3)), + controlRenewalLatencyMsP50: controlRenewal.p50, + controlRenewalLatencyMsP95: controlRenewal.p95, + controlRenewalLatencyMsMax: controlRenewal.max, + httpLatencyMsMax: roundMs(deltas.httpLatencyMsMax), heapUsedBytes: memory.heapUsed, heapTotalBytes: memory.heapTotal, eventLoopDelayMsP99: Number(p99.toFixed(3)) diff --git a/cloud/infra/terraform/relay-observability.tf b/cloud/infra/terraform/relay-observability.tf index 6bc938100c6..0d4b181d338 100644 --- a/cloud/infra/terraform/relay-observability.tf +++ b/cloud/infra/terraform/relay-observability.tf @@ -65,6 +65,19 @@ locals { control_renewal_lease_misses = { field = "controlRenewalLeaseMissesDelta", description = "Control renewals that found their activity lease missing." } control_activity_recoveries = { field = "controlActivityRecoveriesDelta", description = "Control activity leases recovered after a renewal miss." } control_activity_recovery_failures = { field = "controlActivityRecoveryFailuresDelta", description = "Control activity lease recovery attempts that failed." } + control_rtt_ms_p50 = { field = "controlRttMsP50", description = "Control-socket ping round trip p50 in the interval. The desktop echoes the pong on its main thread, so only the median reads as distance; the p95 and max below are dominated by desktop stalls." } + control_rtt_ms_p95 = { field = "controlRttMsP95", description = "Control-socket ping round trip p95 in the interval; a desktop-stall signal, not a distance one." } + control_rtt_ms_max = { field = "controlRttMsMax", description = "Maximum control-socket ping round trip in the interval; a desktop-stall signal, not a distance one." } + control_rtt_samples = { field = "controlRttSamplesDelta", description = "Control-socket round-trip samples in the interval; the percentiles above are omitted when this is zero." } + client_accepts_completed = { field = "clientAcceptCompletedDelta", description = "Phone accepts that reached relay-hello in the interval; the percentiles below are omitted when this is zero." } + client_accept_total_ms_p50 = { field = "clientAcceptTotalMsP50", description = "Successful phone-accept duration p50, dial to relay-hello." } + client_accept_total_ms_p95 = { field = "clientAcceptTotalMsP95", description = "Successful phone-accept duration p95, dial to relay-hello." } + client_accept_total_ms_max = { field = "clientAcceptTotalMsMax", description = "Maximum successful phone-accept duration in the interval." } + client_accept_assignment_ms_p95 = { field = "clientAcceptAssignmentMsP95", description = "Accept stage p95: resume/invite lookup plus assignment resolve." } + client_accept_credential_ms_p95 = { field = "clientAcceptCredentialMsP95", description = "Accept stage p95: outer credential reservation." } + client_accept_activity_ms_p95 = { field = "clientAcceptActivityMsP95", description = "Accept stage p95: credential activity lease acquisition." } + client_accept_attach_ms_p95 = { field = "clientAcceptAttachMsP95", description = "Accept stage p95: conn-open sent until the desktop's data leg authenticated." } + client_accept_basis_ms_p95 = { field = "clientAcceptBasisMsP95", description = "Accept stage p95: splice lease and connection-basis writes between the data leg and relay-hello." } heap_used_bytes = { field = "heapUsedBytes", description = "Node.js heap bytes used by the relay process." } event_loop_ms_p99 = { field = "eventLoopDelayMsP99", description = "Node.js event-loop delay p99 in milliseconds." } forwarded_bytes = { field = "forwardedBytesDelta", description = "Ciphertext bytes admitted for forwarding." } @@ -211,14 +224,14 @@ resource "google_logging_metric" "relay_snapshot" { label_extractors = { role = "EXTRACT(jsonPayload.role)" cell_id = "EXTRACT(jsonPayload.cellId)" - # No region label: adding one replaces all 21 live metrics (label change = delete+create), + # No region label: adding one replaces all 42 live metrics (label change = delete+create), # which resets history and blanks the relay alert policies during the swap. } metric_descriptor { metric_kind = "DELTA" value_type = "DISTRIBUTION" - unit = contains(["sql_latency_ms", "control_renewal_latency_ms_p50", "control_renewal_latency_ms_p95", "control_renewal_latency_ms_max", "http_latency_ms", "event_loop_ms_p99", "db_oldest_wait_ms", "db_wait_ms_max"], each.key) ? "ms" : each.key == "queued_bytes" || each.key == "heap_used_bytes" || each.key == "forwarded_bytes" ? "By" : "1" + unit = contains(["sql_latency_ms", "control_rtt_ms_p50", "control_rtt_ms_p95", "control_rtt_ms_max", "client_accept_total_ms_p50", "client_accept_total_ms_p95", "client_accept_total_ms_max", "client_accept_assignment_ms_p95", "client_accept_credential_ms_p95", "client_accept_activity_ms_p95", "client_accept_attach_ms_p95", "client_accept_basis_ms_p95", "control_renewal_latency_ms_p50", "control_renewal_latency_ms_p95", "control_renewal_latency_ms_max", "http_latency_ms", "event_loop_ms_p99", "db_oldest_wait_ms", "db_wait_ms_max"], each.key) ? "ms" : each.key == "queued_bytes" || each.key == "heap_used_bytes" || each.key == "forwarded_bytes" ? "By" : "1" labels { key = "role" From f5be177e44776d9b8ba34f2bd42b508a898cfd38 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 04:40:37 -0400 Subject: [PATCH 06/37] fix(relay): rehome hosts to their preferred region in either direction (#19241) * fix(relay): rehome hosts to their preferred region in either direction The regional-rehome worker only moved hosts from a us-central1 cell to an asia-east2 one, so a host whose desktop later records us-central1 stays where it was put. Rehoming now compares the fresh preference against the region of the cell the host is on and moves it to a general cell in the preferred region either way, through the same drain, migrate, safety, and rate-limit machinery. - relay_region_rehome_attempts.preferred_region accepts both regions; existing databases are upgraded in place by an idempotent named-constraint swap that is safe when several directors start at once. - A target must carry the drain protocol too: moving a host onto a cell it can never be drained off again is the trap this change exists to undo. The fleet whose health gates a rehome is now every general drainable cell, which is exactly the set of legal sources and targets. - The trust probe accepts a source cell in any region. No wire change, and no behaviour change while the durable control is off. * fix(relay): bound bidirectional rehoming with a per-host cooldown Moving hosts in both directions removed the property that made the old one-way worker self-terminating: a desktop whose region probe flips would be dragged back and forth, one full drain and migrate per flip, because the preference age never expires while the host keeps reconnecting. - relay_region_rehome_control gains host_cooldown_ms, an operator input plumbed like preference_max_age_ms (workflow, ops script, admin route, durable row) and defaulted to seven days. A host with any attempt row inside the window, whichever way that move went, is not a candidate; the claim re-reads it under lock so an attempt landing between scan and claim cannot start a second move. Skips are named host_cooldown, and the lookup rides a new index on (user_id, relay_host_id, created_at). - The candidate scan now also requires the target cell to be enabled, so it mirrors the claim-time filter exactly and stops spending batch slots on candidates that are certain to be skipped. - Region CHECK lists are rendered from the shared region list instead of being written out four times. - The operations runbook states that cells without the drain protocol are neither sources, targets, nor members of the safety gate. * fix(relay): keep rehome reads and brakes working across the cooldown rollout The ops script validated hostCooldownMs on every inspected control, so against any director image predating the field inspect, pause, disable, and failed-enable recovery all threw client-side. The workflow always runs from main while the director image is operator-supplied, so that window opened at merge and reopened on every rollback: the operator lost read-only visibility and both emergency brakes while the worker could still be enabled. The field is now validated only when the director reports it, and every apply body that echoes an inspected control omits the key when that control lacks it, so a legacy director never sees an unknown key. The write path stays fail-closed the other way: enable refuses up front, before any mutation, when the director does not report a cooldown it could honour. Also replaces two bare 'us-central1' defaults with RELAY_DEFAULT_REGION. --- ...ud-operate-relay-production-rehome-job.yml | 4 + .../cloud-operate-relay-production-rehome.yml | 6 + cloud/apps/relay/src/app.ts | 8 +- .../src/assignment-inventory-snapshot.ts | 3 +- cloud/apps/relay/src/assignment-store.ts | 135 ++++++-- cloud/apps/relay/src/cell-heartbeat-client.ts | 3 +- .../src/database-postgres-timeout.test.ts | 58 +++- cloud/apps/relay/src/database.test.ts | 42 ++- cloud/apps/relay/src/database.ts | 41 ++- .../apps/relay/src/postgres-schema-startup.ts | 15 + .../relay/src/regional-host-drain-app.test.ts | 81 +++++ ...home-constraint-migration-postgres.test.ts | 195 +++++++++++ .../src/regional-rehome-postgres.test.ts | 201 +++++++++++- .../relay/src/regional-rehome-store.test.ts | 303 +++++++++++++++++- .../regional-rehome-target-selection.test.ts | 17 +- .../scripts/operate-relay-regional-rehome.mjs | 24 ++ .../operate-relay-regional-rehome.test.mjs | 105 ++++++ cloud/docs/orca-relay-operations.md | 12 + 18 files changed, 1189 insertions(+), 64 deletions(-) create mode 100644 cloud/apps/relay/src/regional-rehome-constraint-migration-postgres.test.ts diff --git a/.github/workflows/cloud-operate-relay-production-rehome-job.yml b/.github/workflows/cloud-operate-relay-production-rehome-job.yml index fdb1aca45e0..a34552b898f 100644 --- a/.github/workflows/cloud-operate-relay-production-rehome-job.yml +++ b/.github/workflows/cloud-operate-relay-production-rehome-job.yml @@ -14,6 +14,7 @@ on: not-before: { required: true, type: string } rate-per-minute: { required: true, type: string } preference-max-age-ms: { required: true, type: string } + host-cooldown-ms: { required: true, type: string } drain-grace-ms: { required: true, type: string } confirmation: { required: true, type: string } monitor-run-id: { required: true, type: string } @@ -54,6 +55,7 @@ jobs: NOT_BEFORE: ${{ inputs.not-before }} RATE_PER_MINUTE: ${{ inputs.rate-per-minute }} PREFERENCE_MAX_AGE_MS: ${{ inputs.preference-max-age-ms }} + HOST_COOLDOWN_MS: ${{ inputs.host-cooldown-ms }} DRAIN_GRACE_MS: ${{ inputs.drain-grace-ms }} CONFIRMATION: ${{ inputs.confirmation }} MONITOR_RUN_ID: ${{ inputs.monitor-run-id }} @@ -128,6 +130,7 @@ jobs: --expected-control-generation "${EXPECTED_CONTROL_GENERATION}" \ --not-before "${NOT_BEFORE}" --rate-per-minute "${RATE_PER_MINUTE}" \ --preference-max-age-ms "${PREFERENCE_MAX_AGE_MS}" \ + --host-cooldown-ms "${HOST_COOLDOWN_MS}" \ --drain-grace-ms "${DRAIN_GRACE_MS}" --confirmation "${CONFIRMATION}" \ | tee "${RUNNER_TEMP}/relay-rehome-control.json" @@ -299,6 +302,7 @@ jobs: --expected-control-generation "${EXPECTED_CONTROL_GENERATION}" \ --not-before "${NOT_BEFORE}" --rate-per-minute "${RATE_PER_MINUTE}" \ --preference-max-age-ms "${PREFERENCE_MAX_AGE_MS}" \ + --host-cooldown-ms "${HOST_COOLDOWN_MS}" \ --drain-grace-ms "${DRAIN_GRACE_MS}" --confirmation "${CONFIRMATION}" \ | tee "${RUNNER_TEMP}/relay-rehome-control.json" diff --git a/.github/workflows/cloud-operate-relay-production-rehome.yml b/.github/workflows/cloud-operate-relay-production-rehome.yml index 40bf5ebbd4f..0615b197c11 100644 --- a/.github/workflows/cloud-operate-relay-production-rehome.yml +++ b/.github/workflows/cloud-operate-relay-production-rehome.yml @@ -52,6 +52,11 @@ on: required: true default: '86400000' type: string + host-cooldown-ms: + description: Minimum gap between two rehomes of the same host + required: true + default: '604800000' + type: string drain-grace-ms: description: Per-host source drain grace required: true @@ -99,6 +104,7 @@ jobs: not-before: ${{ inputs.not-before }} rate-per-minute: ${{ inputs.rate-per-minute }} preference-max-age-ms: ${{ inputs.preference-max-age-ms }} + host-cooldown-ms: ${{ inputs.host-cooldown-ms }} drain-grace-ms: ${{ inputs.drain-grace-ms }} confirmation: ${{ inputs.confirmation }} monitor-run-id: ${{ inputs.monitor-run-id }} diff --git a/cloud/apps/relay/src/app.ts b/cloud/apps/relay/src/app.ts index 3df01d9e9ce..c45e31c4a01 100644 --- a/cloud/apps/relay/src/app.ts +++ b/cloud/apps/relay/src/app.ts @@ -606,8 +606,9 @@ export function createRelayApp( const source = await operations.assignments.cellDeploymentStatus( body.data.sourceCellId ) + // Any cell that can be drained can be a rehome source, in either + // direction, so the probe is gated on the protocol and not on a region. if ( - source.region !== RELAY_DEFAULT_REGION || !source.runtime || source.runtime.cellIncarnation !== body.data.sourceCellIncarnation || !source.runtime.ready || @@ -1412,6 +1413,11 @@ const RegionalRehomeControlSchema = z.discriminatedUnion('action', [ .int() .min(60_000) .max(30 * 24 * 60 * 60_000), + hostCooldownMs: z + .number() + .int() + .min(60_000) + .max(30 * 24 * 60 * 60_000), drainGraceMs: z.number().int().min(60_000).max(60 * 60_000), confirmation: z.enum([ 'ENABLE_REGIONAL_REHOMING', diff --git a/cloud/apps/relay/src/assignment-inventory-snapshot.ts b/cloud/apps/relay/src/assignment-inventory-snapshot.ts index 0675bd49b94..652fbdf2184 100644 --- a/cloud/apps/relay/src/assignment-inventory-snapshot.ts +++ b/cloud/apps/relay/src/assignment-inventory-snapshot.ts @@ -1,3 +1,4 @@ +import { RELAY_DEFAULT_REGION } from '@orca-cloud/relay-contract' import type { RelayDatabase, SqlRow } from './database.js' export type CellInventorySnapshotRow = { @@ -92,7 +93,7 @@ export async function readAssignmentInventorySnapshot( return { cells: cellRows.map((row) => ({ cellId: asText(row, 'cell_id'), - region: optionalText(row, 'region') ?? 'us-central1', + region: optionalText(row, 'region') ?? RELAY_DEFAULT_REGION, admissionState: optionalText(row, 'admission_state') ?? 'unset', enabled: asInteger(row, 'enabled') === 1, capacityRequests: asInteger(row, 'capacity_requests'), diff --git a/cloud/apps/relay/src/assignment-store.ts b/cloud/apps/relay/src/assignment-store.ts index 226df9b3984..9ead45df22e 100644 --- a/cloud/apps/relay/src/assignment-store.ts +++ b/cloud/apps/relay/src/assignment-store.ts @@ -30,6 +30,9 @@ import { ASSIGNMENT_CONNECTION_HEADROOM_QUERY } from './assignment-connection-headroom-query.js' import { AssignmentIdentityQueue } from './assignment-identity-queue.js' +import { + REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS +} from './database.js' import type { RelayCellConfig } from './config.js' import type { RelayDatabase, @@ -121,7 +124,7 @@ export type RelayAssignmentMigration = AssignmentIdentity & { export type RegionalRehomeAttempt = AssignmentIdentity & { attemptId: string - preferredRegion: 'asia-east2' + preferredRegion: RelayRegion sourceCellId: string sourceCellUrl: string sourceCellIncarnation: string @@ -151,6 +154,7 @@ export type RegionalRehomeControl = { notBefore: number ratePerMinute: number preferenceMaxAgeMs: number + hostCooldownMs: number drainGraceMs: number } @@ -4921,6 +4925,7 @@ export class RelayAssignmentStore { notBefore: number ratePerMinute: number preferenceMaxAgeMs: number + hostCooldownMs: number drainGraceMs: number }): Promise { if (!Number.isSafeInteger(input.expectedGeneration) || input.expectedGeneration < 0) { @@ -4939,6 +4944,13 @@ export class RelayAssignmentStore { ) { throw new Error('invalid_regional_rehome_preference_age') } + if ( + !Number.isSafeInteger(input.hostCooldownMs) || + input.hostCooldownMs < 60_000 || + input.hostCooldownMs > 30 * 24 * 60 * 60_000 + ) { + throw new Error('invalid_regional_rehome_host_cooldown') + } if ( !Number.isSafeInteger(input.drainGraceMs) || input.drainGraceMs < 60_000 || @@ -4967,14 +4979,15 @@ export class RelayAssignmentStore { await transaction.query( `UPDATE relay_region_rehome_control SET generation = generation + 1, enabled = ?, not_before = ?, - rate_per_minute = ?, preference_max_age_ms = ?, drain_grace_ms = ?, - updated_at = ? + rate_per_minute = ?, preference_max_age_ms = ?, host_cooldown_ms = ?, + drain_grace_ms = ?, updated_at = ? WHERE control_id = 'global'`, [ input.enabled ? 1 : 0, input.notBefore, input.ratePerMinute, input.preferenceMaxAgeMs, + input.hostCooldownMs, input.drainGraceMs, now ] @@ -5006,10 +5019,17 @@ export class RelayAssignmentStore { await database.query( `INSERT INTO relay_region_rehome_control (control_id, generation, enabled, observation_started_at, not_before, - rate_per_minute, preference_max_age_ms, drain_grace_ms, updated_at) - VALUES ('global', 0, 0, ?, 0, 10, ?, ?, ?) + rate_per_minute, preference_max_age_ms, host_cooldown_ms, drain_grace_ms, + updated_at) + VALUES ('global', 0, 0, ?, 0, 10, ?, ?, ?, ?) ON CONFLICT (control_id) DO NOTHING`, - [now, 24 * 60 * 60_000, 60 * 60_000, now] + [ + now, + 24 * 60 * 60_000, + REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS, + 60 * 60_000, + now + ] ) } @@ -5017,6 +5037,9 @@ export class RelayAssignmentStore { return await this.readRegionalRehomeFleetSafety(this.database, this.now()) } + // The rehome fleet is every general cell that can be drained: those are the + // sources and, because a host must be movable back out again, the only legal + // targets. The region join stays so a cell with no region row is excluded. private async readRegionalRehomeFleetSafety( database: RelayDatabase, now: number @@ -5037,10 +5060,7 @@ export class RelayAssignmentStore { ON safety.cell_id = runtime.cell_id AND safety.cell_incarnation = runtime.cell_incarnation WHERE cell.enabled = 1 AND admission.admission_state = 'general' - AND ( - region.region = 'asia-east2' OR - (region.region = 'us-central1' AND capability.regional_rehome_protocol >= 1) - )` + AND capability.regional_rehome_protocol >= 1` ) const valid = rows.filter( (row) => @@ -5119,6 +5139,10 @@ export class RelayAssignmentStore { } const intervalMs = Math.ceil(60_000 / integer(control, 'rate_per_minute')) const preferenceCutoff = now - integer(control, 'preference_max_age_ms') + // A host that was rehomed recently is left alone whichever way its + // preference now points: a flapping region probe must not walk one host + // back and forth across an ocean. + const cooldownCutoff = now - integer(control, 'host_cooldown_ms') await transaction.query( `INSERT INTO relay_region_rehome_worker_state (worker_id, next_dispatch_at, paused_until, consecutive_failures, updated_at) @@ -5284,9 +5308,8 @@ export class RelayAssignmentStore { JOIN relay_cell_capabilities capability ON capability.cell_id = runtime.cell_id AND capability.cell_incarnation = runtime.cell_incarnation - WHERE preference.preferred_region = 'asia-east2' + WHERE preference.preferred_region <> region.region AND preference.observed_at >= ? - AND region.region = 'us-central1' AND admission.admission_state = 'general' AND runtime.ready = 1 AND runtime.last_heartbeat_at > ? AND capability.regional_rehome_protocol >= 1 @@ -5306,9 +5329,38 @@ export class RelayAssignmentStore { AND migration.relay_host_id = assignment.relay_host_id AND migration.completed_at IS NULL AND migration.aborted_at IS NULL ) + AND NOT EXISTS ( + SELECT 1 FROM relay_region_rehome_attempts recent + WHERE recent.user_id = preference.user_id + AND recent.relay_host_id = preference.relay_host_id + AND recent.created_at > ? + ) + AND EXISTS ( + SELECT 1 FROM relay_cell_regions target_region + JOIN relay_cells target_cell ON target_cell.cell_id = target_region.cell_id + JOIN relay_cell_admission target_admission + ON target_admission.cell_id = target_region.cell_id + JOIN relay_cell_runtime target_runtime + ON target_runtime.cell_id = target_region.cell_id + JOIN relay_cell_capabilities target_capability + ON target_capability.cell_id = target_runtime.cell_id + AND target_capability.cell_incarnation = target_runtime.cell_incarnation + WHERE target_region.region = preference.preferred_region + AND target_cell.enabled = 1 + AND target_admission.admission_state = 'general' + AND target_runtime.ready = 1 + AND target_runtime.last_heartbeat_at > ? + AND target_capability.regional_rehome_protocol >= 1 + ) ORDER BY preference.observed_at, preference.user_id, preference.relay_host_id LIMIT 10`, - [preferenceCutoff, now - this.heartbeatTtlMs, now] + [ + preferenceCutoff, + now - this.heartbeatTtlMs, + now, + cooldownCutoff, + now - this.heartbeatTtlMs + ] ) candidatesTotal = candidates.length for (const candidate of candidates) { @@ -5320,6 +5372,7 @@ export class RelayAssignmentStore { sourceCellId: text(candidate, 'source_cell_id'), assignmentEpoch: integer(candidate, 'assignment_epoch'), preferenceCutoff, + cooldownCutoff, drainGraceMs: integer(control, 'drain_grace_ms'), processSafety: effectiveProcessSafety, worker, @@ -5374,6 +5427,7 @@ export class RelayAssignmentStore { sourceCellId: string assignmentEpoch: number preferenceCutoff: number + cooldownCutoff: number drainGraceMs: number processSafety: RegionalRehomeSafetySnapshot worker: SqlRow @@ -5397,14 +5451,11 @@ export class RelayAssignmentStore { [input.identity.userId, input.identity.relayHostId] ) )[0] - if ( - !preference || - text(preference, 'preferred_region') !== 'asia-east2' || - integer(preference, 'observed_at') < input.preferenceCutoff - ) { + if (!preference || integer(preference, 'observed_at') < input.preferenceCutoff) { input.skips.push({ reason: 'candidate_stale' }) return null } + const preferredRegion = relayRegion(preference, 'preferred_region') const activeMigration = await transaction.queryLocked( `SELECT assignment_epoch FROM relay_assignment_migrations WHERE user_id = ? AND relay_host_id = ? @@ -5415,6 +5466,18 @@ export class RelayAssignmentStore { input.skips.push({ reason: 'candidate_stale' }) return null } + // Re-read under the claim: an attempt committed between the scan and here + // would otherwise start a second move for the same host. + const recentAttempt = await transaction.query( + `SELECT 1 FROM relay_region_rehome_attempts + WHERE user_id = ? AND relay_host_id = ? AND created_at > ? + LIMIT 1`, + [input.identity.userId, input.identity.relayHostId, input.cooldownCutoff] + ) + if (recentAttempt.length > 0) { + input.skips.push({ reason: 'host_cooldown' }) + return null + } const activityLeases = await this.lockAssignmentActivities(transaction, input.identity) assertAssignmentActivityCounts(assignment, activityLeases, 0) const cells = await this.lockCellInventory(transaction, 'nowait') @@ -5469,11 +5532,17 @@ export class RelayAssignmentStore { ) return null } + // The preference read under lock can now agree with the cell the host is + // already on: nothing to move, in either direction. + if (regions.get(input.sourceCellId) === preferredRegion) { + input.skips.push({ reason: 'candidate_stale' }) + return null + } if ( !source || integer(source, 'enabled') !== 1 || admission.get(input.sourceCellId) !== 'general' || - regions.get(input.sourceCellId) !== RELAY_DEFAULT_REGION || + regions.get(input.sourceCellId) === undefined || !sourceRuntime || integer(sourceRuntime, 'ready') !== 1 || integer(sourceRuntime, 'last_heartbeat_at') <= input.now - this.heartbeatTtlMs || @@ -5502,17 +5571,25 @@ export class RelayAssignmentStore { return null } const connectionHeadroom = await this.connectionHeadroomByCell(transaction) + // A target must be drainable too, or the host lands somewhere it can never + // be rehomed out of again -- the trap this bidirectional move exists to undo. const eligibleTargets = cells.filter((row) => { const cellId = text(row, 'cell_id') const runtime = runtimes.find((candidate) => text(candidate, 'cell_id') === cellId) + const capability = capabilities.find( + (candidate) => text(candidate, 'cell_id') === cellId + ) return ( cellId !== input.sourceCellId && integer(row, 'enabled') === 1 && admission.get(cellId) === 'general' && - regions.get(cellId) === 'asia-east2' && + regions.get(cellId) === preferredRegion && runtime !== undefined && integer(runtime, 'ready') === 1 && - integer(runtime, 'last_heartbeat_at') > input.now - this.heartbeatTtlMs + integer(runtime, 'last_heartbeat_at') > input.now - this.heartbeatTtlMs && + capability !== undefined && + text(capability, 'cell_incarnation') === text(runtime, 'cell_incarnation') && + integer(capability, 'regional_rehome_protocol') >= 1 ) }) const targetIsClean = (row: SqlRow): boolean => { @@ -5668,12 +5745,13 @@ export class RelayAssignmentStore { drain_grace_ms, send_attempts, last_send_attempt_at, drain_receipt_at, drain_outcome, completed_at, aborted_at, created_at, updated_at) - VALUES (?, ?, ?, 'asia-east2', ?, ?, ?, ?, ?, ?, ?, 0, NULL, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL, NULL, NULL, NULL, NULL, ?, ?)`, [ attemptId, input.identity.userId, input.identity.relayHostId, + preferredRegion, input.sourceCellId, text(sourceRuntime, 'cell_incarnation'), targetCellId, @@ -5688,7 +5766,7 @@ export class RelayAssignmentStore { return { ...input.identity, attemptId, - preferredRegion: 'asia-east2', + preferredRegion, sourceCellId: input.sourceCellId, sourceCellUrl: text(source, 'cell_url'), sourceCellIncarnation: text(sourceRuntime, 'cell_incarnation'), @@ -8101,7 +8179,7 @@ function regionalRehomeAttempt(row: SqlRow): RegionalRehomeAttempt { attemptId: text(row, 'attempt_id'), userId: text(row, 'user_id'), relayHostId: text(row, 'relay_host_id'), - preferredRegion: 'asia-east2', + preferredRegion: relayRegion(row, 'preferred_region'), sourceCellId: text(row, 'source_cell_id'), sourceCellUrl: text(row, 'source_cell_url'), sourceCellIncarnation: text(row, 'source_cell_incarnation'), @@ -8122,6 +8200,7 @@ function regionalRehomeControl(row: SqlRow): RegionalRehomeControl { notBefore: integer(row, 'not_before'), ratePerMinute: integer(row, 'rate_per_minute'), preferenceMaxAgeMs: integer(row, 'preference_max_age_ms'), + hostCooldownMs: integer(row, 'host_cooldown_ms'), drainGraceMs: integer(row, 'drain_grace_ms') } } @@ -8161,10 +8240,9 @@ function regionalRehomeFleetSafetyFromInventory(input: { return ( integer(row, 'enabled') === 1 && input.admission.get(cellId) === 'general' && - (input.regions.get(cellId) === 'asia-east2' || - (input.regions.get(cellId) === RELAY_DEFAULT_REGION && - capability !== undefined && - integer(capability, 'regional_rehome_protocol') >= 1)) + input.regions.get(cellId) !== undefined && + capability !== undefined && + integer(capability, 'regional_rehome_protocol') >= 1 ) }) const valid = required.flatMap((row) => { @@ -8231,6 +8309,7 @@ function regionalRehomeFleetSafetyFailure( type RegionalRehomeCandidateSkip = { reason: | 'candidate_stale' + | 'host_cooldown' | 'source_ineligible' | 'source_unclean' | 'source_control_inactive' diff --git a/cloud/apps/relay/src/cell-heartbeat-client.ts b/cloud/apps/relay/src/cell-heartbeat-client.ts index 3bbcd08ecd6..5c990310413 100644 --- a/cloud/apps/relay/src/cell-heartbeat-client.ts +++ b/cloud/apps/relay/src/cell-heartbeat-client.ts @@ -1,4 +1,5 @@ import { randomUUID } from 'node:crypto' +import { RELAY_DEFAULT_REGION } from '@orca-cloud/relay-contract' import type { RelayConfig } from './config.js' import { googleMetadataIdentityToken } from './google-metadata-identity-token.js' import type { RegionalRehomeSafetySnapshot } from './relay-observability.js' @@ -57,7 +58,7 @@ export function startCellHeartbeat( v: 1, cellId: config.cellId, cellUrl: config.cellUrl, - region: config.region ?? 'us-central1', + region: config.region ?? RELAY_DEFAULT_REGION, cellIncarnation, startedAt, ready, diff --git a/cloud/apps/relay/src/database-postgres-timeout.test.ts b/cloud/apps/relay/src/database-postgres-timeout.test.ts index c9021a9ef18..f678fecc4bb 100644 --- a/cloud/apps/relay/src/database-postgres-timeout.test.ts +++ b/cloud/apps/relay/src/database-postgres-timeout.test.ts @@ -34,7 +34,11 @@ vi.mock('pg', () => ({ } })) -import { openRelayDatabase, relayPostgresStatementTimeoutMs } from './database.js' +import { + openRelayDatabase, + POSTGRES_SCHEMA_MIGRATIONS, + relayPostgresStatementTimeoutMs +} from './database.js' import { applyPostgresSchema } from './postgres-schema-startup.js' const SCHEMA_POOL = { @@ -118,7 +122,9 @@ describe('PostgreSQL relay deadlines', () => { // Statements can open with a leading `--` rationale comment. const body = (statement: string): string => statement.replace(/^(?:\s*--[^\n]*\n)*\s*/, '') - expect(ddl.every((statement) => /^CREATE\b/i.test(body(statement)))).toBe(true) + expect( + ddl.every((statement) => /^(?:CREATE|ALTER TABLE)\b/i.test(body(statement))) + ).toBe(true) // The backfill is DML, so it stays on the deadline-bearing serving pool. expect(ddl.some((statement) => statement.includes('INSERT INTO'))).toBe(false) await database.close() @@ -263,6 +269,54 @@ describe('PostgreSQL schema startup', () => { expect(query).toHaveBeenCalledTimes(2) }) + it('treats an existing constraint as an applied ADD CONSTRAINT', async () => { + // Postgres has no `ADD CONSTRAINT IF NOT EXISTS`, and a retry would only + // repeat 42710, so a re-run and a concurrent startup both move on. + const error = Object.assign(new Error('already exists'), { code: '42710' }) + const query = vi + .fn<(statement: string) => Promise>() + .mockRejectedValueOnce(error) + .mockResolvedValue(undefined) + const pause = vi.fn(async () => undefined) + + await applyPostgresSchema( + ['ALTER TABLE test ADD CONSTRAINT test_check CHECK (id > 0)', 'CREATE TABLE test2'], + query, + { wait: pause } + ) + + expect(pause).not.toHaveBeenCalled() + expect(query).toHaveBeenCalledTimes(2) + expect(query).toHaveBeenLastCalledWith('CREATE TABLE test2') + }) + + it('recognises every shipped ADD CONSTRAINT migration as re-runnable', async () => { + // Guards the statement text against the pattern that classifies it. + const shipped = POSTGRES_SCHEMA_MIGRATIONS.filter((statement) => + statement.includes('ADD CONSTRAINT') + ) + expect(shipped.length).toBeGreaterThan(0) + const error = Object.assign(new Error('already exists'), { code: '42710' }) + const query = vi.fn<(statement: string) => Promise>().mockRejectedValue(error) + + await applyPostgresSchema(shipped, query, { wait: async () => undefined }) + + expect(query).toHaveBeenCalledTimes(shipped.length) + }) + + it('still fails an ADD CONSTRAINT that violates existing rows', async () => { + const error = Object.assign(new Error('check violation'), { code: '23514' }) + const query = vi.fn<(statement: string) => Promise>().mockRejectedValue(error) + + await expect( + applyPostgresSchema( + ['ALTER TABLE test ADD CONSTRAINT test_check CHECK (id > 0)'], + query, + { wait: async () => undefined } + ) + ).rejects.toBe(error) + }) + it.each([ ['42710', 'CREATE INDEX IF NOT EXISTS test_index ON test(id)'], ['42710', 'CREATE TABLE test'], diff --git a/cloud/apps/relay/src/database.test.ts b/cloud/apps/relay/src/database.test.ts index 32e50a7bc6a..56122def4be 100644 --- a/cloud/apps/relay/src/database.test.ts +++ b/cloud/apps/relay/src/database.test.ts @@ -2,7 +2,12 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { openInMemoryRelayDatabase, openRelayDatabase } from './database.js' +import { + openInMemoryRelayDatabase, + openRelayDatabase, + POSTGRES_SCHEMA_MIGRATIONS, + REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS +} from './database.js' const temporaryDirectories: string[] = [] @@ -142,6 +147,41 @@ describe('relay database', () => { await second.close() }) + it('renders every region check from the shared region list', async () => { + // Derived, not hand-written: a third region must not leave one column + // rejecting a value the rest of the relay already accepts. + const database = await openInMemoryRelayDatabase() + const checked = await database.query( + `SELECT name, sql FROM sqlite_master + WHERE type = 'table' + AND name IN ('relay_assignment_region_preferences', 'relay_cell_regions', + 'relay_region_rehome_attempts') + ORDER BY name` + ) + const list = `IN ('us-central1', 'asia-east2')` + expect(checked.map((row) => row.name)).toEqual([ + 'relay_assignment_region_preferences', + 'relay_cell_regions', + 'relay_region_rehome_attempts' + ]) + expect(checked.every((row) => String(row.sql).includes(list))).toBe(true) + expect( + POSTGRES_SCHEMA_MIGRATIONS.some((statement) => statement.includes(list)) + ).toBe(true) + await database.close() + }) + + it('indexes rehome attempts by host recency for the per-host cooldown', async () => { + const database = await openInMemoryRelayDatabase() + const rows = await database.query( + `SELECT sql FROM sqlite_master + WHERE type = 'index' AND name = 'relay_region_rehome_attempts_host_recency'` + ) + expect(rows[0]?.sql).toContain('(user_id, relay_host_id, created_at)') + expect(REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS).toBe(7 * 24 * 60 * 60_000) + await database.close() + }) + it('indexes region preference expiry by observation time', async () => { const database = await openInMemoryRelayDatabase() const rows = await database.query( diff --git a/cloud/apps/relay/src/database.ts b/cloud/apps/relay/src/database.ts index 2558831ca64..d51f4e7a423 100644 --- a/cloud/apps/relay/src/database.ts +++ b/cloud/apps/relay/src/database.ts @@ -3,6 +3,7 @@ import { performance } from 'node:perf_hooks' import { join } from 'node:path' import { DatabaseSync } from 'node:sqlite' import pg from 'pg' +import { RELAY_REGIONS } from '@orca-cloud/relay-contract' import { emptyPostgresPoolPressureCounts, PostgresPoolPressure, @@ -24,6 +25,14 @@ function setLocalLockTimeout(milliseconds: number): string { return `SET LOCAL lock_timeout = '${milliseconds}ms'` } +// Region CHECK lists come from the contract so a new region cannot leave a +// column rejecting values the rest of the relay already accepts. +const REGION_LIST = RELAY_REGIONS.map((region) => `'${region}'`).join(', ') + +// A host that was just moved is not a candidate again for this long, so a +// desktop whose region probe flips cannot walk itself back and forth. +export const REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS = 7 * 24 * 60 * 60_000 + export type SqlRow = Record export type RelayLockOptions = { failIfUnavailable?: boolean @@ -181,7 +190,7 @@ CREATE TABLE IF NOT EXISTS relay_assignment_region_preferences ( user_id TEXT NOT NULL, relay_host_id TEXT NOT NULL, preferred_region TEXT NOT NULL - CHECK (preferred_region IN ('us-central1', 'asia-east2')), + CHECK (preferred_region IN (${REGION_LIST})), observed_at BIGINT NOT NULL, PRIMARY KEY (user_id, relay_host_id) ); @@ -204,6 +213,8 @@ CREATE TABLE IF NOT EXISTS relay_region_rehome_control ( not_before BIGINT NOT NULL, rate_per_minute BIGINT NOT NULL, preference_max_age_ms BIGINT NOT NULL, + host_cooldown_ms BIGINT NOT NULL + DEFAULT ${REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS}, drain_grace_ms BIGINT NOT NULL, updated_at BIGINT NOT NULL ); @@ -212,7 +223,9 @@ CREATE TABLE IF NOT EXISTS relay_region_rehome_attempts ( attempt_id TEXT PRIMARY KEY, user_id TEXT NOT NULL, relay_host_id TEXT NOT NULL, - preferred_region TEXT NOT NULL CHECK (preferred_region = 'asia-east2'), + preferred_region TEXT NOT NULL + CONSTRAINT relay_region_rehome_attempts_preferred_region_valid + CHECK (preferred_region IN (${REGION_LIST})), source_cell_id TEXT NOT NULL, source_cell_incarnation TEXT NOT NULL, target_cell_id TEXT NOT NULL, @@ -234,6 +247,8 @@ CREATE TABLE IF NOT EXISTS relay_region_rehome_attempts ( ); CREATE INDEX IF NOT EXISTS relay_region_rehome_attempts_pending ON relay_region_rehome_attempts(drain_receipt_at, last_send_attempt_at, completed_at, aborted_at); +CREATE INDEX IF NOT EXISTS relay_region_rehome_attempts_host_recency + ON relay_region_rehome_attempts(user_id, relay_host_id, created_at); CREATE TABLE IF NOT EXISTS relay_cells ( cell_id TEXT PRIMARY KEY, @@ -248,7 +263,7 @@ CREATE TABLE IF NOT EXISTS relay_cells ( CREATE TABLE IF NOT EXISTS relay_cell_regions ( cell_id TEXT PRIMARY KEY, - region TEXT NOT NULL CHECK (region IN ('us-central1', 'asia-east2')) + region TEXT NOT NULL CHECK (region IN (${REGION_LIST})) ); CREATE TABLE IF NOT EXISTS relay_cell_admission ( @@ -580,6 +595,21 @@ CREATE TABLE IF NOT EXISTS relay_audit_events ( CREATE INDEX IF NOT EXISTS relay_audit_events_at ON relay_audit_events(at); ` +// Rehoming is bidirectional, but tables created before that carry the +// original single-region column check. The old constraint is the one Postgres +// auto-named; the replacement is named, so both statements are no-ops on a +// database the current schema created and neither can drop the other. +export const POSTGRES_SCHEMA_MIGRATIONS = [ + `ALTER TABLE relay_region_rehome_attempts + DROP CONSTRAINT IF EXISTS relay_region_rehome_attempts_preferred_region_check`, + `ALTER TABLE relay_region_rehome_attempts + ADD CONSTRAINT relay_region_rehome_attempts_preferred_region_valid + CHECK (preferred_region IN (${REGION_LIST}))`, + `ALTER TABLE relay_region_rehome_control + ADD COLUMN IF NOT EXISTS host_cooldown_ms BIGINT NOT NULL + DEFAULT ${REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS}` +] + function postgresSql(sql: string): string { let index = 0 return sql.replace(/\?/g, () => `$${++index}`) @@ -1009,7 +1039,10 @@ async function applySchemaOnUntimedPool( const database = new PostgresDatabase(pool) try { await applyPostgresSchema( - SCHEMA.split(';').filter((statement) => statement.trim()), + [ + ...SCHEMA.split(';').filter((statement) => statement.trim()), + ...POSTGRES_SCHEMA_MIGRATIONS + ], async (statement) => await database.query(statement) ) } finally { diff --git a/cloud/apps/relay/src/postgres-schema-startup.ts b/cloud/apps/relay/src/postgres-schema-startup.ts index ba9efc6a792..22a75cd9465 100644 --- a/cloud/apps/relay/src/postgres-schema-startup.ts +++ b/cloud/apps/relay/src/postgres-schema-startup.ts @@ -49,6 +49,20 @@ function concurrentCreateCollision( return false } +const ALTER_TABLE_ADD_CONSTRAINT = + /^\s*ALTER\s+TABLE\s+\S+\s+ADD\s+CONSTRAINT\b/i + +// Postgres has no `ADD CONSTRAINT IF NOT EXISTS`, so a re-run and a concurrent +// startup both land on 42710 once the constraint exists. Unlike a CREATE race +// this is terminal, not transient: retrying only repeats it, so the statement +// counts as applied. +function constraintAlreadyApplied(error: unknown, statement: string): boolean { + return ( + ALTER_TABLE_ADD_CONSTRAINT.test(statement) && + (error as { code?: unknown }).code === '42710' + ) +} + function retryableSchemaError(error: unknown, statement: string): boolean { const value = error as { code?: unknown; constraint?: unknown } return ( @@ -73,6 +87,7 @@ export async function applyPostgresSchema( await query(statement) break } catch (error) { + if (constraintAlreadyApplied(error, statement)) break const code = String((error as { code?: unknown }).code) const remainingMs = deadlineAt - now() const retryable = retryableSchemaError(error, statement) diff --git a/cloud/apps/relay/src/regional-host-drain-app.test.ts b/cloud/apps/relay/src/regional-host-drain-app.test.ts index 1cd34902520..e2a33a07bb0 100644 --- a/cloud/apps/relay/src/regional-host-drain-app.test.ts +++ b/cloud/apps/relay/src/regional-host-drain-app.test.ts @@ -315,6 +315,7 @@ describe('regional rehome director controls', () => { notBefore: 100, ratePerMinute: 10, preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: 7 * 24 * 60 * 60_000, drainGraceMs: 60_000, confirmation: 'ENABLE_REGIONAL_REHOMING' } @@ -343,6 +344,14 @@ describe('regional rehome director controls', () => { 'deploy-token', { ...apply, confirmation: 'DISABLE_REGIONAL_REHOMING' } )).status).toBe(400) + // The per-host cooldown is part of the durable shape an operator must state. + const { hostCooldownMs: _omitted, ...withoutCooldown } = apply + expect((await postPath( + app, + '/v1/admin/regional-rehome-control', + 'deploy-token', + withoutCooldown + )).status).toBe(400) }) it('probes dedicated trust twice and returns only aggregate proof', async () => { @@ -411,6 +420,78 @@ describe('regional rehome director controls', () => { expect(JSON.stringify(responseBody)).not.toContain('rehome-token') }) + it('probes a source cell in any region, not only the default one', async () => { + // Rehoming moves hosts in both directions, so an asia-east2 cell is a + // source too and its trust has to be provable the same way. + const cellDeploymentStatus = vi.fn().mockResolvedValue({ + cellId: 'production-gce-c27', + cellUrl: 'https://c27.relay.example.test', + region: 'asia-east2', + runtime: { + cellIncarnation, + ready: true, + heartbeatFresh: true, + regionalRehomeProtocol: 1 + } + }) + const app = createRelayApp(config({ role: 'director', cellId: 'director' }), { + store: {} as never, + assignments: { cellDeploymentStatus } as never, + drain: vi.fn(), + regionalRehomeIdentityToken: vi.fn(async () => 'rehome-token'), + regionalRehomeFetch: (async () => + Response.json({ + v: 1, + outcome: 'host-not-connected', + sharedRuntimeIdentityRejected: true + })) as typeof fetch, + ready: vi.fn(async () => true) + }) + + const response = await postPath( + app, + '/v1/admin/regional-rehome-trust-probe', + 'deploy-token', + { v: 1, sourceCellId: 'production-gce-c27', sourceCellIncarnation: cellIncarnation } + ) + + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ proven: true }) + }) + + it('still refuses a trust probe against a cell without the drain protocol', async () => { + const cellDeploymentStatus = vi.fn().mockResolvedValue({ + cellId: 'production-gce-c27', + cellUrl: 'https://c27.relay.example.test', + region: 'asia-east2', + runtime: { + cellIncarnation, + ready: true, + heartbeatFresh: true, + regionalRehomeProtocol: 0 + } + }) + const sourceFetch = vi.fn() + const app = createRelayApp(config({ role: 'director', cellId: 'director' }), { + store: {} as never, + assignments: { cellDeploymentStatus } as never, + drain: vi.fn(), + regionalRehomeIdentityToken: vi.fn(async () => 'rehome-token'), + regionalRehomeFetch: sourceFetch, + ready: vi.fn(async () => true) + }) + + const response = await postPath( + app, + '/v1/admin/regional-rehome-trust-probe', + 'deploy-token', + { v: 1, sourceCellId: 'production-gce-c27', sourceCellIncarnation: cellIncarnation } + ) + + expect(response.status).toBe(409) + expect(sourceFetch).not.toHaveBeenCalled() + }) + it('restricts trust probes to deploy authorization and strict input', async () => { const app = createRelayApp(config({ role: 'director', cellId: 'director' }), { store: {} as never, diff --git a/cloud/apps/relay/src/regional-rehome-constraint-migration-postgres.test.ts b/cloud/apps/relay/src/regional-rehome-constraint-migration-postgres.test.ts new file mode 100644 index 00000000000..4e9ccda5e13 --- /dev/null +++ b/cloud/apps/relay/src/regional-rehome-constraint-migration-postgres.test.ts @@ -0,0 +1,195 @@ +import pg from 'pg' +import { afterAll, beforeEach, describe, expect, it } from 'vitest' +import { + openRelayDatabase, + REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS, + type RelayDatabase +} from './database.js' + +const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL +const describePostgres = databaseUrl ? describe : describe.skip +const schema = 'relay_rehome_constraint_migration_test' + +// The shape shipped before rehoming became bidirectional: a single-region +// column check that Postgres auto-names. +const LEGACY_ATTEMPTS_TABLE = ` +CREATE TABLE relay_region_rehome_attempts ( + attempt_id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + relay_host_id TEXT NOT NULL, + preferred_region TEXT NOT NULL CHECK (preferred_region = 'asia-east2'), + source_cell_id TEXT NOT NULL, + source_cell_incarnation TEXT NOT NULL, + target_cell_id TEXT NOT NULL, + target_cell_incarnation TEXT NOT NULL, + previous_epoch BIGINT NOT NULL, + assignment_epoch BIGINT NOT NULL, + drain_grace_ms BIGINT NOT NULL, + send_attempts BIGINT NOT NULL, + last_send_attempt_at BIGINT, + drain_receipt_at BIGINT, + drain_outcome TEXT CHECK ( + drain_outcome IN ('accepted', 'already-accepted', 'host-not-connected') + ), + completed_at BIGINT, + aborted_at BIGINT, + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + UNIQUE (user_id, relay_host_id, assignment_epoch) +)` + +// The control row as it shipped before the per-host cooldown existed. +const LEGACY_CONTROL_TABLE = ` +CREATE TABLE relay_region_rehome_control ( + control_id TEXT PRIMARY KEY, + generation BIGINT NOT NULL, + enabled BIGINT NOT NULL, + observation_started_at BIGINT NOT NULL, + not_before BIGINT NOT NULL, + rate_per_minute BIGINT NOT NULL, + preference_max_age_ms BIGINT NOT NULL, + drain_grace_ms BIGINT NOT NULL, + updated_at BIGINT NOT NULL +)` + +const attemptValues = (attemptId: string, preferredRegion: string): unknown[] => [ + attemptId, + 'user-1', + 'abcdefghijklmnop', + preferredRegion, + 'cell-source', + '11111111-1111-4111-8111-111111111111', + 'cell-target', + '22222222-2222-4222-8222-222222222222', + 1, + Number(attemptId.at(-1)), + 0, + 0, + 1_000_000, + 1_000_000 +] + +const INSERT_ATTEMPT = `INSERT INTO relay_region_rehome_attempts + (attempt_id, user_id, relay_host_id, preferred_region, source_cell_id, + source_cell_incarnation, target_cell_id, target_cell_incarnation, + previous_epoch, assignment_epoch, drain_grace_ms, send_attempts, + created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)` + +describePostgres('PostgreSQL regional rehome constraint migration', () => { + let scopedUrl = '' + + async function withClient( + operation: (client: pg.Client) => Promise + ): Promise { + const client = new pg.Client({ connectionString: databaseUrl }) + await client.connect() + try { + await operation(client) + } finally { + await client.end() + } + } + + beforeEach(async () => { + await withClient(async (client) => { + await client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`) + await client.query(`CREATE SCHEMA ${schema}`) + await client.query(`SET search_path = ${schema}`) + await client.query(LEGACY_ATTEMPTS_TABLE) + await client.query(LEGACY_CONTROL_TABLE) + await client.query( + `INSERT INTO relay_region_rehome_control + (control_id, generation, enabled, observation_started_at, not_before, + rate_per_minute, preference_max_age_ms, drain_grace_ms, updated_at) + VALUES ('global', 3, 0, 1, 0, 10, 86400000, 60000, 1)` + ) + // Production data the replacement constraint has to validate. + await client.query(INSERT_ATTEMPT, attemptValues('attempt-1', 'asia-east2')) + }) + const url = new URL(databaseUrl!) + url.searchParams.set('options', `-c search_path=${schema}`) + scopedUrl = url.toString() + }) + + afterAll(async () => { + await withClient(async (client) => { + await client.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`) + }) + }) + + it('upgrades a legacy single-region constraint in place', async () => { + const database = await openRelayDatabase({ databaseUrl: scopedUrl, dataDir: '' }) + try { + await withClient(async (client) => { + await client.query(`SET search_path = ${schema}`) + await client.query(INSERT_ATTEMPT, attemptValues('attempt-2', 'us-central1')) + await expect( + client.query(INSERT_ATTEMPT, attemptValues('attempt-3', 'europe-west1')) + ).rejects.toMatchObject({ code: '23514' }) + const constraints = await client.query( + `SELECT conname FROM pg_constraint + WHERE conrelid = 'relay_region_rehome_attempts'::regclass + AND conname LIKE '%preferred_region%' + ORDER BY conname` + ) + expect(constraints.rows).toEqual([ + { conname: 'relay_region_rehome_attempts_preferred_region_valid' } + ]) + // The existing control row keeps its tuning and gains the cooldown. + const control = await client.query( + `SELECT generation, preference_max_age_ms, host_cooldown_ms + FROM relay_region_rehome_control WHERE control_id = 'global'` + ) + expect(control.rows).toEqual([ + { + generation: '3', + preference_max_age_ms: '86400000', + host_cooldown_ms: String(REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS) + } + ]) + }) + } finally { + await database.close() + } + }) + + it('upgrades once across concurrent startups', async () => { + const results = await Promise.allSettled( + Array.from( + { length: 5 }, + async (): Promise => + await openRelayDatabase({ databaseUrl: scopedUrl, dataDir: '' }) + ) + ) + const databases = results.flatMap((result) => + result.status === 'fulfilled' ? [result.value] : [] + ) + await Promise.all(databases.map(async (database) => await database.close())) + + expect( + results.flatMap((result) => + result.status === 'rejected' + ? [ + { + code: (result.reason as { code?: unknown }).code, + message: String(result.reason) + } + ] + : [] + ) + ).toEqual([]) + await withClient(async (client) => { + await client.query(`SET search_path = ${schema}`) + await client.query(INSERT_ATTEMPT, attemptValues('attempt-4', 'us-central1')) + const constraints = await client.query( + `SELECT conname FROM pg_constraint + WHERE conrelid = 'relay_region_rehome_attempts'::regclass + AND conname LIKE '%preferred_region%'` + ) + expect(constraints.rows).toEqual([ + { conname: 'relay_region_rehome_attempts_preferred_region_valid' } + ]) + }) + }, 60_000) +}) diff --git a/cloud/apps/relay/src/regional-rehome-postgres.test.ts b/cloud/apps/relay/src/regional-rehome-postgres.test.ts index d36e26ecd68..44f3b3434af 100644 --- a/cloud/apps/relay/src/regional-rehome-postgres.test.ts +++ b/cloud/apps/relay/src/regional-rehome-postgres.test.ts @@ -81,6 +81,153 @@ describePostgres('PostgreSQL regional rehoming', () => { expect(await context.store.claimRegionalRehome()).not.toBeNull() }) + it('moves a us-central1 host onto a cell in its preferred asia-east2 region', async () => { + const context = await fixture() + + const attempt = await context.store.claimRegionalRehome() + expect(attempt).toMatchObject({ + preferredRegion: 'asia-east2', + sourceCellId: context.source.id, + targetCellId: context.target.id + }) + expect(await primary.query( + `SELECT preferred_region, source_cell_id, target_cell_id + FROM relay_region_rehome_attempts WHERE user_id = ?`, + [context.identity.userId] + )).toEqual([{ + preferred_region: 'asia-east2', + source_cell_id: context.source.id, + target_cell_id: context.target.id + }]) + }) + + it('moves an asia-east2 host back onto a cell in its preferred us-central1 region', async () => { + const context = await fixture({ + sourceRegion: 'asia-east2', + targetRegion: 'us-central1' + }) + + const attempt = await context.store.claimRegionalRehome() + expect(attempt).toMatchObject({ + preferredRegion: 'us-central1', + sourceCellId: context.source.id, + targetCellId: context.target.id + }) + // The durable attempt row must accept the reverse direction too. + expect(await primary.query( + `SELECT preferred_region, source_cell_id, target_cell_id + FROM relay_region_rehome_attempts WHERE user_id = ?`, + [context.identity.userId] + )).toEqual([{ + preferred_region: 'us-central1', + source_cell_id: context.source.id, + target_cell_id: context.target.id + }]) + expect(await primary.query( + `SELECT cell_id FROM relay_assignments WHERE user_id = ?`, + [context.identity.userId] + )).toEqual([{ cell_id: context.target.id }]) + }) + + it('leaves a host whose preference already matches its own region', async () => { + const context = await fixture({ preferredRegion: 'us-central1' }) + + await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ + generation: 1, + enabled: true + }) + expect(await attemptAndMigrationCounts(context.identity)).toEqual({ + attempts: 0, + migrations: 0 + }) + }) + + it('leaves a host whose preference is older than the configured max age', async () => { + const context = await fixture() + await primary.query( + `UPDATE relay_assignment_region_preferences SET observed_at = ? + WHERE user_id = ? AND relay_host_id = ?`, + [ + context.now() - 24 * 60 * 60_000 - 1, + context.identity.userId, + context.identity.relayHostId + ] + ) + + await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ + generation: 1, + enabled: true + }) + expect(await attemptAndMigrationCounts(context.identity)).toEqual({ + attempts: 0, + migrations: 0 + }) + }) + + it('leaves a host inside its per-host rehome cooldown, in either direction', async () => { + const context = await fixture({ hostCooldownMs: 3 * 24 * 60 * 60_000 }) + // A move this host already made, whichever way it went. + await primary.query( + `INSERT INTO relay_region_rehome_attempts + (attempt_id, user_id, relay_host_id, preferred_region, source_cell_id, + source_cell_incarnation, target_cell_id, target_cell_incarnation, + previous_epoch, assignment_epoch, drain_grace_ms, send_attempts, + completed_at, created_at, updated_at) + VALUES (?, ?, ?, 'us-central1', ?, ?, ?, ?, 0, 1, 0, 0, ?, ?, ?)`, + [ + `pg-rehome-cooldown-${context.identity.relayHostId}`, + context.identity.userId, + context.identity.relayHostId, + context.target.id, + '22222222-2222-4222-8222-222222222222', + context.source.id, + '11111111-1111-4111-8111-111111111111', + context.now(), + context.now() - 3 * 24 * 60 * 60_000 + 1, + context.now() + ] + ) + + await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ + generation: 1, + enabled: true, + hostCooldownMs: 3 * 24 * 60 * 60_000 + }) + expect(await attemptAndMigrationCounts(context.identity)).toEqual({ + attempts: 1, + migrations: 0 + }) + + // One millisecond past the window the same host is a candidate again. + await primary.query( + `UPDATE relay_region_rehome_attempts SET created_at = ? WHERE user_id = ?`, + [context.now() - 3 * 24 * 60 * 60_000, context.identity.userId] + ) + await expect(context.store.claimRegionalRehome()).resolves.toMatchObject({ + sourceCellId: context.source.id, + targetCellId: context.target.id + }) + }) + + it('leaves a host whose preferred region holds no drainable cell', async () => { + // A cell that cannot be drained cannot be a target: the host would land + // where no later rehome could move it out again. + const context = await fixture({ targetProtocol: 0 }) + + await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ + generation: 1, + enabled: true + }) + expect(await attemptAndMigrationCounts(context.identity)).toEqual({ + attempts: 0, + migrations: 0 + }) + }) + it('skips an unclean cell without latching the control off', async () => { const context = await fixture() await primary.query( @@ -281,7 +428,7 @@ describePostgres('PostgreSQL regional rehoming', () => { context.store, context.target, '22222222-2222-4222-8222-222222222222', - 0, + 1, 900_000, 2 ) @@ -322,7 +469,7 @@ describePostgres('PostgreSQL regional rehoming', () => { context.store, context.target, '44444444-4444-4444-8444-444444444444', - 0, + 1, context.now() ) @@ -341,7 +488,7 @@ describePostgres('PostgreSQL regional rehoming', () => { context.store, context.target, '22222222-2222-4222-8222-222222222222', - 0, + 1, 900_000, 2 ) @@ -414,6 +561,26 @@ describePostgres('PostgreSQL regional rehoming', () => { }) }) + async function attemptAndMigrationCounts(identity: { + userId: string + relayHostId: string + }): Promise<{ attempts: number; migrations: number }> { + const attempts = await primary.query( + `SELECT COUNT(*) AS count FROM relay_region_rehome_attempts + WHERE user_id = ? AND relay_host_id = ?`, + [identity.userId, identity.relayHostId] + ) + const migrations = await primary.query( + `SELECT COUNT(*) AS count FROM relay_assignment_migrations + WHERE user_id = ? AND relay_host_id = ?`, + [identity.userId, identity.relayHostId] + ) + return { + attempts: Number(attempts[0]!.count), + migrations: Number(migrations[0]!.count) + } + } + async function controlAccounting(identity: { userId: string relayHostId: string @@ -436,12 +603,15 @@ describePostgres('PostgreSQL regional rehoming', () => { } } - async function fixture() { + async function fixture(options: FixtureOptions = {}) { sequence++ let now = 1_000_000 const suffix = String(sequence) - const source = cell(suffix, 'source', 'us-central1') - const target = cell(suffix, 'target', 'asia-east2') + const sourceRegion = options.sourceRegion ?? 'us-central1' + const targetRegion = options.targetRegion ?? 'asia-east2' + const preferredRegion = options.preferredRegion ?? targetRegion + const source = cell(suffix, 'source', sourceRegion) + const target = cell(suffix, 'target', targetRegion) const store = new RelayAssignmentStore(primary, () => now, storeOptions) const competingStore = new RelayAssignmentStore(secondary, () => now, storeOptions) await store.inspectRegionalRehomeControl() @@ -452,6 +622,7 @@ describePostgres('PostgreSQL regional rehoming', () => { notBefore: now, ratePerMinute: 10, preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: options.hostCooldownMs ?? 7 * 24 * 60 * 60_000, drainGraceMs: 60_000 }) await store.reconcileCells([source, target]) @@ -466,21 +637,22 @@ describePostgres('PostgreSQL regional rehoming', () => { store, target, '22222222-2222-4222-8222-222222222222', - 0, + options.targetProtocol ?? 1, 900_000 ) const identity = { userId: `pg-rehome-user-${suffix}`, relayHostId: `rehomehost${suffix.padStart(6, '0')}` } - const assignment = await store.assign(identity, undefined, 'us-central1') + const assignment = await store.assign(identity, undefined, sourceRegion) const sourceControl = await store.activateControl(identity, { cellId: source.id, assignmentEpoch: assignment.assignmentEpoch, generation: 1 }) - await store.assign(identity, 'asia-east2') + await store.assign(identity, preferredRegion) return { + preferredRegion, store, competingStore, identity, @@ -500,7 +672,16 @@ const storeOptions = { heartbeatTtlMs: 45_000 } -function cell(suffix: string, role: string, region: 'us-central1' | 'asia-east2') { +type Region = 'us-central1' | 'asia-east2' +type FixtureOptions = { + sourceRegion?: Region + targetRegion?: Region + preferredRegion?: Region + targetProtocol?: number + hostCooldownMs?: number +} + +function cell(suffix: string, role: string, region: Region) { return { id: `pg-rehome-cell-${suffix}-${role}`, url: `https://pg-rehome-${suffix}-${role}.example.test`, diff --git a/cloud/apps/relay/src/regional-rehome-store.test.ts b/cloud/apps/relay/src/regional-rehome-store.test.ts index 26f711189ee..2c1c8132266 100644 --- a/cloud/apps/relay/src/regional-rehome-store.test.ts +++ b/cloud/apps/relay/src/regional-rehome-store.test.ts @@ -81,6 +81,7 @@ describe('regional rehome assignment state', () => { notBefore: context.now(), ratePerMinute: 10, preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: 7 * 24 * 60 * 60_000, drainGraceMs: 60_000 })).rejects.toThrow('regional_rehome_generation_mismatch') await expect(context.store.applyRegionalRehomeControl({ @@ -89,6 +90,7 @@ describe('regional rehome assignment state', () => { notBefore: context.now(), ratePerMinute: 10, preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: 7 * 24 * 60 * 60_000, drainGraceMs: 60_000 })).resolves.toMatchObject({ generation: 3, enabled: true }) await context.database.close() @@ -207,7 +209,7 @@ describe('regional rehome assignment state', () => { databasePoolWaitersMax: 0, databasePoolWaitMsMax: 0 }) - await heartbeat(context.store, target, targetIncarnation, 0, 2, { + await heartbeat(context.store, target, targetIncarnation, 1, 2, { observedAt: context.now(), sqlFailures: 1, reconnects: 3, @@ -226,6 +228,23 @@ describe('regional rehome assignment state', () => { await context.database.close() }) + it('counts only drainable cells as the rehome fleet, in every region', async () => { + // The fleet whose health gates a rehome is exactly the cells that can be a + // source or a target, and both roles require the drain protocol. + const context = await setup({ targetProtocol: 0 }) + + expect(await context.store.regionalRehomeFleetSafety()).toMatchObject({ + requiredCells: 1, + missingCells: 0 + }) + await heartbeat(context.store, target, targetIncarnation, 1, 2) + expect(await context.store.regionalRehomeFleetSafety()).toMatchObject({ + requiredCells: 2, + missingCells: 0 + }) + await context.database.close() + }) + it('claims through the measured healthy baseline of pool micro-waits and churn', async () => { const context = await setup() const baseline = { @@ -238,7 +257,7 @@ describe('regional rehome assignment state', () => { databasePoolWaitMsMax: 1 } await heartbeat(context.store, source, sourceIncarnation, 1, 2, baseline) - await heartbeat(context.store, target, targetIncarnation, 0, 2, baseline) + await heartbeat(context.store, target, targetIncarnation, 1, 2, baseline) await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' @@ -324,6 +343,204 @@ describe('regional rehome assignment state', () => { await context.database.close() }) + it('moves a live host on an asia-east2 cell back to its preferred us-central1 cell', async () => { + const context = await setup() + const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } + await activateReversePreferredSource(context, identity) + + const attempt = await context.store.claimRegionalRehome() + expect(attempt).toMatchObject({ + userId: identity.userId, + relayHostId: identity.relayHostId, + preferredRegion: 'us-central1', + sourceCellId: target.id, + sourceCellIncarnation: targetIncarnation, + targetCellId: source.id, + targetCellIncarnation: sourceIncarnation, + previousEpoch: 1, + assignmentEpoch: 2, + sendAttempts: 1 + }) + expect( + await context.database.query( + `SELECT preferred_region, source_cell_id, target_cell_id + FROM relay_region_rehome_attempts` + ) + ).toEqual([{ + preferred_region: 'us-central1', + source_cell_id: target.id, + target_cell_id: source.id + }]) + expect(await context.store.resolve(identity)).toMatchObject({ cellId: source.id }) + await context.database.close() + }) + + it('drops a candidate at scan time when no cell in the preferred region is usable', async () => { + const context = await setup() + await activatePreferredSource(context, { + userId: 'user-1', + relayHostId: 'abcdefghijklmnop' + }) + // A disabled cell is not a target, and the scan must say so: leaving it to + // the claim would burn a slot of the candidate batch on a certain skip. + await context.database.query(`UPDATE relay_cells SET enabled = 0 WHERE cell_id = ?`, [ + target.id + ]) + + const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') + try { + expect(await context.store.claimRegionalRehome()).toBeNull() + } finally { + warnings.restore() + } + expect(warnings.entries).toEqual([]) + expect( + await context.database.query( + `SELECT next_dispatch_at FROM relay_region_rehome_worker_state` + ) + ).toEqual([{ next_dispatch_at: 0 }]) + expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) + await context.database.close() + }) + + it('names the skip when the last target is lost between scan and claim', async () => { + const database = await openInMemoryRelayDatabase() + const context = await setup({ + database, + wrap: (delegate) => + hookAfterCandidateScan(delegate, async (transaction) => { + await transaction.query(`UPDATE relay_cells SET enabled = 0 WHERE cell_id = ?`, [ + target.id + ]) + }) + }) + await activatePreferredSource(context, { + userId: 'user-1', + relayHostId: 'abcdefghijklmnop' + }) + + const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') + try { + expect(await context.store.claimRegionalRehome()).toBeNull() + } finally { + warnings.restore() + } + expect(warnings.entries).toMatchObject([ + { skips: [{ reason: 'no_eligible_target', candidates: 1 }] } + ]) + expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ + generation: 1, + enabled: true + }) + expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) + await database.close() + }) + + it('leaves a host alone until its cooldown expires, then moves it back', async () => { + const context = await setup({ hostCooldownMs: 3 * 24 * 60 * 60_000 }) + const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } + const targetControl = await completeRehomeToTarget(context, identity) + // Past the dispatch interval the earlier claim charged, so the next tick + // really does scan and the cooldown is the only thing holding this host. + context.advance(10_000) + // The desktop's region probe now says us-central1 again. + await context.store.assign(identity, 'us-central1') + + const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') + try { + expect(await context.store.claimRegionalRehome()).toBeNull() + } finally { + warnings.restore() + } + expect(warnings.entries).toEqual([]) + expect(await context.store.resolve(identity)).toMatchObject({ cellId: target.id }) + + context.advance(3 * 24 * 60 * 60_000) + await freshHeartbeats(context) + await context.store.renewControlActivity(identity, { + activityId: targetControl, + cellId: target.id, + expiresAt: context.now() + 90_000 + }) + await context.store.assign(identity, 'us-central1') + + const attempt = await context.store.claimRegionalRehome() + expect(attempt).toMatchObject({ + preferredRegion: 'us-central1', + sourceCellId: target.id, + targetCellId: source.id + }) + await context.database.close() + }) + + it('rejects a host whose attempt lands between the scan and the claim', async () => { + const database = await openInMemoryRelayDatabase() + const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } + const context = await setup({ + database, + wrap: (delegate) => + hookAfterCandidateScan(delegate, async (transaction) => { + await transaction.query( + `INSERT INTO relay_region_rehome_attempts + (attempt_id, user_id, relay_host_id, preferred_region, source_cell_id, + source_cell_incarnation, target_cell_id, target_cell_incarnation, + previous_epoch, assignment_epoch, drain_grace_ms, send_attempts, + created_at, updated_at) + VALUES ('raced', ?, ?, 'asia-east2', ?, ?, ?, ?, 0, 1, 0, 0, ?, ?)`, + [ + identity.userId, + identity.relayHostId, + source.id, + sourceIncarnation, + target.id, + targetIncarnation, + context.now(), + context.now() + ] + ) + }) + }) + await activatePreferredSource(context, identity) + + const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') + try { + expect(await context.store.claimRegionalRehome()).toBeNull() + } finally { + warnings.restore() + } + expect(warnings.entries).toMatchObject([ + { skips: [{ reason: 'host_cooldown', candidates: 1 }] } + ]) + expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) + await database.close() + }) + + it('does not scan a candidate whose preferred region has no drainable cell', async () => { + // A cell without the drain protocol cannot be a target: the host would land + // where no later rehome could move it out again. The candidate query drops + // it, so the tick stays idle instead of paying for an inventory scan. + const context = await setup({ targetProtocol: 0 }) + await activatePreferredSource(context, { + userId: 'user-1', + relayHostId: 'abcdefghijklmnop' + }) + + const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') + try { + expect(await context.store.claimRegionalRehome()).toBeNull() + } finally { + warnings.restore() + } + expect(warnings.entries).toEqual([]) + expect( + await context.database.query( + `SELECT next_dispatch_at FROM relay_region_rehome_worker_state` + ) + ).toEqual([{ next_dispatch_at: 0 }]) + expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) + await context.database.close() + }) + it('skips an unclean cell without latching the control off', async () => { const context = await setup() await activatePreferredSource(context, { @@ -457,7 +674,7 @@ describe('regional rehome assignment state', () => { databasePoolWaitersMax: 0, databasePoolWaitMsMax: 0 }) - await heartbeat(context.store, target, targetIncarnation, 0, 2, { + await heartbeat(context.store, target, targetIncarnation, 1, 2, { observedAt: context.now(), sqlFailures: 0, reconnects: 0, @@ -477,6 +694,7 @@ describe('regional rehome assignment state', () => { notBefore: context.now(), ratePerMinute: 10, preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: 7 * 24 * 60 * 60_000, drainGraceMs: 60_000 }) const retry = await context.store.claimRegionalRehome() @@ -547,7 +765,7 @@ describe('regional rehome assignment state', () => { await activatePreferredSource(context, identity) await context.store.claimRegionalRehome() context.advance(6 * 60_000) - await heartbeat(context.store, target, targetIncarnation, 0, 2) + await heartbeat(context.store, target, targetIncarnation, 1, 2) expect(await context.store.refreshRegionalRehomeLeases()).toBe(0) expect(await context.store.abortExpiredEvacuations()).toBe(0) @@ -1549,10 +1767,16 @@ function collectDisableWarnings() { } async function setup( - options: { sourceProtocol?: number; wrap?: (database: RelayDatabase) => RelayDatabase } = {} + options: { + sourceProtocol?: number + targetProtocol?: number + hostCooldownMs?: number + database?: RelayDatabase + wrap?: (database: RelayDatabase) => RelayDatabase + } = {} ) { let clock = 1_000_000 - const database = await openInMemoryRelayDatabase() + const database = options.database ?? (await openInMemoryRelayDatabase()) const store = new RelayAssignmentStore(options.wrap?.(database) ?? database, () => clock, { requireLiveCells: true, heartbeatTtlMs: 45_000 @@ -1565,11 +1789,12 @@ async function setup( notBefore: clock, ratePerMinute: 10, preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: options.hostCooldownMs ?? 7 * 24 * 60 * 60_000, drainGraceMs: 60 * 60_000 }) await store.reconcileCells([source, target]) await heartbeat(store, source, sourceIncarnation, options.sourceProtocol ?? 1) - await heartbeat(store, target, targetIncarnation, 0) + await heartbeat(store, target, targetIncarnation, options.targetProtocol ?? 1) return { database, store, @@ -1671,7 +1896,7 @@ async function freshHeartbeats(context: Context): Promise { } // The clock doubles as a strictly-increasing connection inclusion watermark. await heartbeat(context.store, source, sourceIncarnation, 1, context.now(), safety) - await heartbeat(context.store, target, targetIncarnation, 0, context.now(), safety) + await heartbeat(context.store, target, targetIncarnation, 1, context.now(), safety) } async function activatePreferredSource( @@ -1688,6 +1913,68 @@ async function activatePreferredSource( return control } +// Runs a hook inside the claim transaction, right after the candidate scan, so +// a scan-versus-claim race is deterministic instead of timing-dependent. +function hookAfterCandidateScan( + database: RelayDatabase, + hook: (transaction: RelayDatabase) => Promise +): RelayDatabase { + let fired = false + const decorate = (delegate: RelayDatabase): RelayDatabase => ({ + query: async (sql, params) => { + const rows = await delegate.query(sql, params) + if (!fired && sql.includes('FROM relay_assignment_region_preferences preference')) { + fired = true + await hook(delegate) + } + return rows + }, + queryLocked: async (sql, params, lockOptions) => + await delegate.queryLocked(sql, params, lockOptions), + transaction: async (operation, transactionOptions) => + await delegate.transaction( + async (transaction) => await operation(decorate(transaction)), + transactionOptions + ), + close: async () => undefined + }) + return decorate(database) +} + +async function completeRehomeToTarget( + context: Context, + identity: { userId: string; relayHostId: string } +): Promise { + const sourceControl = await activatePreferredSource(context, identity) + const attempt = await context.store.claimRegionalRehome() + const targetControl = await context.store.activateControl(identity, { + cellId: target.id, + assignmentEpoch: attempt!.assignmentEpoch, + generation: 1 + }) + await context.store.markMigrationTargetRegistered(identity, { + cellId: target.id, + assignmentEpoch: attempt!.assignmentEpoch + }) + await context.store.releaseActivity(identity, sourceControl) + await context.store.completeReadyRegionalRehomes() + return targetControl +} + +async function activateReversePreferredSource( + context: Context, + identity: { userId: string; relayHostId: string } +): Promise { + const assignment = await context.store.assign(identity, undefined, 'asia-east2') + const control = await context.store.activateControl(identity, { + cellId: target.id, + assignmentEpoch: assignment.assignmentEpoch, + generation: 1 + }) + await context.store.assign(identity, 'us-central1') + return control +} + async function activateSource( context: Context, identity: { userId: string; relayHostId: string } diff --git a/cloud/apps/relay/src/regional-rehome-target-selection.test.ts b/cloud/apps/relay/src/regional-rehome-target-selection.test.ts index e2190168735..493eaa50a61 100644 --- a/cloud/apps/relay/src/regional-rehome-target-selection.test.ts +++ b/cloud/apps/relay/src/regional-rehome-target-selection.test.ts @@ -36,6 +36,7 @@ async function setup() { notBefore: clock, ratePerMinute: 10, preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: 7 * 24 * 60 * 60_000, drainGraceMs: 60 * 60_000 }) await store.reconcileCells([source, noHeadroom, unclean, highLoad, lowLoad]) @@ -100,22 +101,22 @@ describe('regional rehome target selection', () => { sqlFailures: 0 }) // Lowest load but the connection hard cap is exhausted. - await context.beat(noHeadroom, 2, 0, { + await context.beat(noHeadroom, 2, 1, { observedRequests: 0, enforcedConnections: 999, sqlFailures: 0 }) - await context.beat(unclean, 3, 0, { + await context.beat(unclean, 3, 1, { observedRequests: 0, enforcedConnections: 0, sqlFailures: UNCLEAN }) - await context.beat(highLoad, 4, 0, { + await context.beat(highLoad, 4, 1, { observedRequests: 50, enforcedConnections: 0, sqlFailures: 0 }) - await context.beat(lowLoad, 5, 0, { + await context.beat(lowLoad, 5, 1, { observedRequests: 10, enforcedConnections: 0, sqlFailures: 0 @@ -134,22 +135,22 @@ describe('regional rehome target selection', () => { enforcedConnections: 0, sqlFailures: 0 }) - await context.beat(noHeadroom, 2, 0, { + await context.beat(noHeadroom, 2, 1, { observedRequests: 0, enforcedConnections: 999, sqlFailures: 0 }) - await context.beat(unclean, 3, 0, { + await context.beat(unclean, 3, 1, { observedRequests: 0, enforcedConnections: 0, sqlFailures: UNCLEAN }) - await context.beat(highLoad, 4, 0, { + await context.beat(highLoad, 4, 1, { observedRequests: 50, enforcedConnections: 0, sqlFailures: 0 }) - await context.beat(lowLoad, 5, 0, { + await context.beat(lowLoad, 5, 1, { observedRequests: 10, enforcedConnections: 0, sqlFailures: UNCLEAN diff --git a/cloud/dev/scripts/operate-relay-regional-rehome.mjs b/cloud/dev/scripts/operate-relay-regional-rehome.mjs index 3887408520f..94b21220fc0 100644 --- a/cloud/dev/scripts/operate-relay-regional-rehome.mjs +++ b/cloud/dev/scripts/operate-relay-regional-rehome.mjs @@ -45,6 +45,7 @@ export function parseRegionalRehomeArguments(argv, environment = process.env) { 'not-before', 'rate-per-minute', 'preference-max-age-ms', + 'host-cooldown-ms', 'drain-grace-ms', 'confirmation' ] @@ -117,6 +118,11 @@ export function parseRegionalRehomeArguments(argv, environment = process.env) { '--preference-max-age-ms', { minimum: 60_000, maximum: 30 * 24 * 60 * 60_000 } ), + hostCooldownMs: integer( + values['host-cooldown-ms'], + '--host-cooldown-ms', + { minimum: 60_000, maximum: 30 * 24 * 60 * 60_000 } + ), drainGraceMs: integer(values['drain-grace-ms'], '--drain-grace-ms', { minimum: 60_000, maximum: 60 * 60_000 @@ -147,6 +153,11 @@ function assertControl(control, expected) { !Number.isSafeInteger(control.notBefore) || !Number.isSafeInteger(control.ratePerMinute) || !Number.isSafeInteger(control.preferenceMaxAgeMs) || + // A director predating the per-host cooldown does not report it. Reading + // the control and both emergency brakes must keep working against that + // image; only enable requires the field. + (control.hostCooldownMs !== undefined && + !Number.isSafeInteger(control.hostCooldownMs)) || !Number.isSafeInteger(control.drainGraceMs) ) throw new Error('director returned an invalid regional rehome control') if (expected.enabled !== undefined && control.enabled !== expected.enabled) { @@ -155,6 +166,12 @@ function assertControl(control, expected) { return control } +// Echo the cooldown only when the director already reports it: a legacy +// director rejects the unknown key outright and would refuse every brake. +function cooldownField(before, value) { + return before.hostCooldownMs === undefined ? {} : { hostCooldownMs: value } +} + async function verifiedDisabledControl(post, generation) { return assertControl((await post('/v1/admin/regional-rehome-control', { v: 1, @@ -171,6 +188,7 @@ async function applyDisabledControl(post, before) { notBefore: before.notBefore, ratePerMinute: before.ratePerMinute, preferenceMaxAgeMs: before.preferenceMaxAgeMs, + ...cooldownField(before, before.hostCooldownMs), drainGraceMs: before.drainGraceMs, confirmation: 'DISABLE_REGIONAL_REHOMING' })).control, { generation: before.generation + 1, enabled: false }) @@ -270,6 +288,11 @@ export async function operateRegionalRehome(config, dependencies = {}) { throw new Error('regional rehome is already paused') } const enabled = config.mode === 'enable' + if (enabled && before.hostCooldownMs === undefined) { + throw new Error( + 'director does not report a per-host rehome cooldown; deploy a director that supports it before enabling' + ) + } const applied = await post('/v1/admin/regional-rehome-control', { v: 1, action: 'apply', @@ -278,6 +301,7 @@ export async function operateRegionalRehome(config, dependencies = {}) { notBefore: config.notBefore, ratePerMinute: config.ratePerMinute, preferenceMaxAgeMs: config.preferenceMaxAgeMs, + ...cooldownField(before, config.hostCooldownMs), drainGraceMs: config.drainGraceMs, confirmation: enabled ? 'ENABLE_REGIONAL_REHOMING' diff --git a/cloud/dev/scripts/operate-relay-regional-rehome.test.mjs b/cloud/dev/scripts/operate-relay-regional-rehome.test.mjs index bfea6769ec4..51c132aa7c4 100644 --- a/cloud/dev/scripts/operate-relay-regional-rehome.test.mjs +++ b/cloud/dev/scripts/operate-relay-regional-rehome.test.mjs @@ -26,6 +26,7 @@ function argumentsFor(mode, confirmation) { '--not-before', '2000000000000', '--rate-per-minute', '10', '--preference-max-age-ms', '86400000', + '--host-cooldown-ms', '604800000', '--drain-grace-ms', '60000', '--confirmation', confirmation ]) @@ -40,10 +41,29 @@ function control(generation, enabled) { notBefore: 2_000_000_000_000, ratePerMinute: 10, preferenceMaxAgeMs: 86_400_000, + hostCooldownMs: 604_800_000, drainGraceMs: 60_000 } } +// The control a director predating the per-host cooldown reports. +function legacyControl(generation, enabled) { + const { hostCooldownMs: _absent, ...rest } = control(generation, enabled) + return rest +} + +function legacyDirector(controls) { + const requests = [] + const post = async (path, body) => { + requests.push({ path, body }) + if (path === '/v1/admin/admission-selector/status') { + return { selector: { generation: 11, membership } } + } + return { v: 1, control: controls.shift() } + } + return { requests, post } +} + test('parses exact selector and typed control confirmation', () => { const parsed = parseRegionalRehomeArguments( argumentsFor('enable', 'ENABLE_REGIONAL_REHOMING'), @@ -52,6 +72,17 @@ test('parses exact selector and typed control confirmation', () => { assert.equal(parsed.expectedSelectorGeneration, 11) assert.equal(parsed.expectedControlGeneration, 4) assert.equal(parsed.ratePerMinute, 10) + assert.equal(parsed.hostCooldownMs, 604_800_000) + assert.throws( + () => parseRegionalRehomeArguments( + argumentsFor('enable', 'ENABLE_REGIONAL_REHOMING').filter( + (value, index, all) => + value !== '--host-cooldown-ms' && all[index - 1] !== '--host-cooldown-ms' + ), + { ORCA_RELAY_ADMIN_ID_TOKEN: 'token' } + ), + /complete durable control shape/ + ) assert.throws( () => parseRegionalRehomeArguments( argumentsFor('pause', 'DISABLE_REGIONAL_REHOMING'), @@ -79,6 +110,7 @@ test('binds enable to exact selector and durable control generations', async () notBefore: 0, ratePerMinute: 10, preferenceMaxAgeMs: 86_400_000, + hostCooldownMs: 604_800_000, drainGraceMs: 60_000, ...control })) @@ -96,6 +128,7 @@ test('binds enable to exact selector and durable control generations', async () } }) assert.equal(result.control.generation, 5) + assert.equal(result.control.hostCooldownMs, 604_800_000) assert.deepEqual(requests[2].body, { v: 1, action: 'apply', @@ -104,11 +137,82 @@ test('binds enable to exact selector and durable control generations', async () notBefore: 2_000_000_000_000, ratePerMinute: 10, preferenceMaxAgeMs: 86_400_000, + hostCooldownMs: 604_800_000, drainGraceMs: 60_000, confirmation: 'ENABLE_REGIONAL_REHOMING' }) }) +test('inspects a director that predates the per-host cooldown', async () => { + const director = legacyDirector([legacyControl(4, true)]) + const config = parseRegionalRehomeArguments( + argumentsFor('inspect'), + { ORCA_RELAY_ADMIN_ID_TOKEN: 'token' } + ) + + const result = await operateRegionalRehome(config, { post: director.post }) + + assert.equal(result.control.generation, 4) + assert.equal(result.control.hostCooldownMs, undefined) +}) + +for (const [mode, confirmation, enabledBefore] of [ + ['pause', 'PAUSE_REGIONAL_REHOMING', true], + ['disable', 'DISABLE_REGIONAL_REHOMING', false] +]) { + test(`${mode} still brakes a director that predates the cooldown`, async () => { + const director = legacyDirector([ + legacyControl(4, enabledBefore), + legacyControl(5, false), + legacyControl(5, false) + ]) + const config = parseRegionalRehomeArguments( + argumentsFor(mode, confirmation), + { ORCA_RELAY_ADMIN_ID_TOKEN: 'token' } + ) + + const result = await operateRegionalRehome(config, { post: director.post }) + + assert.equal(result.control.generation, 5) + // The unknown key would be refused by that director's strict schema. + assert.equal('hostCooldownMs' in director.requests[2].body, false) + assert.equal(director.requests[2].body.confirmation, 'DISABLE_REGIONAL_REHOMING') + }) +} + +test('failed-enable recovery brakes a director that predates the cooldown', async () => { + const requests = [] + let current = legacyControl(7, true) + const result = await recoverRegionalRehomeEnable({ + mode: 'recover-enable', + expectedControlGeneration: 4 + }, async (_path, body) => { + requests.push(body) + if (body.action === 'inspect') return { control: current } + current = legacyControl(8, false) + return { control: current } + }) + + assert.equal(result.control.generation, 8) + assert.equal('hostCooldownMs' in requests[1], false) +}) + +test('refuses to enable a director that does not report the cooldown', async () => { + const director = legacyDirector([legacyControl(4, false)]) + const config = parseRegionalRehomeArguments( + argumentsFor('enable', 'ENABLE_REGIONAL_REHOMING'), + { ORCA_RELAY_ADMIN_ID_TOKEN: 'token' } + ) + + await assert.rejects( + operateRegionalRehome(config, { post: director.post }), + /per-host rehome cooldown/ + ) + // Read-only: selector status and the control inspect, and nothing else. + assert.equal(director.requests.length, 2) + assert.equal(director.requests.every(({ body }) => body.action !== 'apply'), true) +}) + test('fails closed on selector drift before reading or mutating control', async () => { let calls = 0 const config = parseRegionalRehomeArguments( @@ -150,6 +254,7 @@ test('failed-enable recovery CAS-disables an advanced enabled generation', async notBefore: 2_000_000_000_000, ratePerMinute: 10, preferenceMaxAgeMs: 86_400_000, + hostCooldownMs: 604_800_000, drainGraceMs: 60_000, confirmation: 'DISABLE_REGIONAL_REHOMING' }) diff --git a/cloud/docs/orca-relay-operations.md b/cloud/docs/orca-relay-operations.md index 0f8eb7a50fb..cd989b58e94 100644 --- a/cloud/docs/orca-relay-operations.md +++ b/cloud/docs/orca-relay-operations.md @@ -464,6 +464,18 @@ Once a target control is registered, do not force the pre-registration rollback. After a deployment traffic shift, preserve the old revision/tag until metrics and live reconnect checks pass. If the new revision is unhealthy, shift traffic back only while old controls are still valid, then issue a strictly newer director migration rather than reusing a prior epoch. +## Regional rehoming + +Rehoming moves a host to a general cell in the region its desktop last reported, in either +direction. Both roles need the drain protocol: a cell without it can be neither a source nor a +target, and it is not part of the fleet whose telemetry gates the worker. Until the asia-east2 +cells run `regionalRehomeProtocol` 1 they are none of the three, so no host is moved into or out +of Asia and an Asia cell in distress does not pause the worker. + +`host-cooldown-ms` is the minimum gap between two rehomes of one host. It bounds the damage from +a desktop whose region probe flips: without it the host would be dragged back across the ocean on +every flip, since the preference age never expires while the host keeps reconnecting. + ## Game-day matrix Run and record each scenario in staging before launch: From 23df74d85a0b566f4663f34339532789b6ac8287 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 04:40:40 -0400 Subject: [PATCH 07/37] perf(mobile): cut the relay reconnect critical path and admit dead sockets faster (#19236) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * perf(mobile): cut the relay reconnect critical path and admit dead sockets faster Phone medians put E2EE authentication at ~424ms but `connected` at ~630ms, because the session serialized two RPC round trips behind it: the resume confirm (`pairing.getEndpoints`) and the capability advisory. Both now ride the authenticated socket concurrently and off the critical path, so the session publishes `connected` as soon as E2EE authenticates. Peer identity is already proven by then — the confirm carries credential/lease bookkeeping and the cell assignment check, and it still fails the session on a bad answer or a foreign relayHostId, only later. `persistResumeConfirmation` awaits the new `whenResumeConfirmed()` instead of assuming the answer is present at `connected`. Foreground liveness on a retained relay: `notifyForeground('app-resume')` now probes past the 10s voluntary minimum on urgent bounds (2s, one miss), so a socket that died while the process was suspended is admitted in ~2s instead of ~8s. Focus and network nudges keep the old minimum and bounds. Relay sessions also gain a 25s idle sweep, gated on foreground so a backgrounded app spends no probes. Recovery is no longer blocked by the direct return probe. The probe's 12s dial is a pure observation on its own socket, so it takes the supervisor's operation mutex only for the cutover; a relay recovery landing during a foreground return now starts immediately instead of waiting the budget out. Requests that do land during the cutover are queued in a new RelayRecoveryIntentQueue and replayed on release — an owning forced replacement keeps its intent, everything else replays as a plain recovery. Tests updated deliberately, for the new ordering: - 'sends no periodic traffic while an authenticated relay is idle' asserted the absence of any relay idle probe, which is exactly the gap D3 closes. Replaced by a sweep test plus a backgrounded no-probe test. - 'rate-limits foreground sequences without suppressing a retry' asserted that app-resume was suppressed inside the 10s minimum. An app resume is now the one nudge that must never be rate-limited. - the session helpers waited for the confirm answer before `connected`; they now authenticate, read both concurrent frames, and settle them. * fix(mobile): book backoff when a relay resume confirm fails after the cutover Review round 1 on 352bfd2300. P1: publishing `connected` at E2EE authentication made `migrateTo` resolve before the resume confirm answered, so a confirm that failed afterwards — a `relayHostId` mismatch from a rehomed desktop is the live case — was still reported as an `established` dial. registerFailure was skipped, no cooldown was booked, recordMigration()/setActiveSession() ran for a dying session, and the queued-recovery replay redialled immediately: a tight loop with a connected→disconnected blip per pass. The establisher now awaits whenResumeConfirmed() after the cutover and, if the session is no longer connected, reports a failed dial (or an aborted one when direct won or the supervisor went inactive) exactly as a rejected migrateTo used to. The UI still connects early; only the supervisor's bookkeeping waits. The state check, rather than getFailure(), is the oracle: a live session can carry a latched failure without having failed yet, and "is this session still alive once the confirm settled" is precisely the question migrateTo used to answer. P2: the resume probe profile goes to two 2s misses instead of one. The first frame after a resume rides a cold radio and a possibly distant cell, so one slow answer is not proof of a dead link; the verdict still lands at 4s rather than the previous 8s. Nits: the direct probe's two early returns no longer close the candidate the finally also closes (the second shape pre-existed); RelayRecoveryIntentQueue is cleared in the supervisor's stop(). Mutex-hold note: persistResumeConfirmation, and now the establisher's own await, are bounded by the confirm's request timeout. That would have been the session's 30s default, so the confirm is pinned to RELAY_CONFIRM_TIMEOUT_MS (12s) — the same bound migrateTo's waitForAuthenticated applied before. Test: a supervisor-level case where every dial authenticates then fails the confirm must book 250/500/1000ms backoff with no immediate redial, and must never record a migration. It fails on the pre-fix establisher. --- .../transport/mobile-direct-return-probe.ts | 22 ++- .../transport/mobile-endpoint-lifecycle.ts | 3 +- .../mobile-endpoint-supervisor-contract.ts | 4 +- ...e-endpoint-supervisor-direct-probe.test.ts | 106 ++++++++++ .../mobile-endpoint-supervisor-test-fakes.ts | 1 + .../mobile-endpoint-supervisor.test.ts | 3 + .../transport/mobile-endpoint-supervisor.ts | 31 +-- .../mobile-relay-credential-rotation.ts | 4 + .../mobile-relay-rpc-session-liveness.test.ts | 103 ++++++++-- .../mobile-relay-rpc-session.test.ts | 183 ++++++++++++++---- .../src/transport/mobile-relay-rpc-session.ts | 68 +++++-- .../mobile-relay-runtime-failover.test.ts | 4 + .../mobile-relay-session-establisher.ts | 14 +- .../transport/relay-recovery-intent-queue.ts | 45 +++++ .../rpc-session-liveness-watchdog.ts | 63 ++++-- 15 files changed, 536 insertions(+), 118 deletions(-) create mode 100644 mobile/src/transport/relay-recovery-intent-queue.ts diff --git a/mobile/src/transport/mobile-direct-return-probe.ts b/mobile/src/transport/mobile-direct-return-probe.ts index 3ae31edd07f..ac84f35ae86 100644 --- a/mobile/src/transport/mobile-direct-return-probe.ts +++ b/mobile/src/transport/mobile-direct-return-probe.ts @@ -26,6 +26,7 @@ export class DirectReturnProbe { host: () => HostProfile canSchedule: () => boolean canAttempt: () => boolean + // Takes the supervisor's operation mutex, now held for the cutover only. beginOperation: () => void migrate: ( client: RpcClient, @@ -70,9 +71,12 @@ export class DirectReturnProbe { } const controller = new AbortController() this.activeProbe = controller - this.hooks.beginOperation() + let owned = false let successful: Awaited> = null try { + // Why: the dial is a pure observation on its own socket — holding the + // supervisor's mutex across its 12s budget stalled every relay recovery + // that landed during a foreground return. Only the cutover needs the mutex. successful = await openAuthenticatedDirectEndpoint( this.hooks.host(), this.deps.openDirect, @@ -86,10 +90,18 @@ export class DirectReturnProbe { this.hooks.hysteresis.recordDirectFailure(this.deps.now()) return } + // Both early returns leave the candidate to the finally, which owns it until + // migration takes over — closing here too would double-close it. if (!this.hooks.hysteresis.recordDirectSuccess(this.deps.now())) { - successful.client.close() return } + if (!this.hooks.canAttempt()) { + // A relay dial owns the mutex; the streak survives, so the next probe + // promotes direct instead of this one. + return + } + this.hooks.beginOperation() + owned = true const candidate = successful // Migration owns the candidate, including closing it if cutover is canceled. successful = null @@ -109,9 +121,11 @@ export class DirectReturnProbe { } finally { this.activeProbe = null successful?.client.close() - // Why: a relay drop or backoff timer can arrive while the probe owns the + // Why: a relay drop or backoff timer can arrive while the cutover owns the // operation mutex; afterProbe releases it and replays deferred recovery. - this.hooks.afterProbe() + if (owned) { + this.hooks.afterProbe() + } this.schedule() } } diff --git a/mobile/src/transport/mobile-endpoint-lifecycle.ts b/mobile/src/transport/mobile-endpoint-lifecycle.ts index 7ec5f28b945..1542de9da7d 100644 --- a/mobile/src/transport/mobile-endpoint-lifecycle.ts +++ b/mobile/src/transport/mobile-endpoint-lifecycle.ts @@ -86,7 +86,7 @@ function createSupervisor( ): MobileEndpointSupervisor { return new MobileEndpointSupervisor(logical, host, { openDirect: (endpoint) => connect(endpoint, host.deviceToken, host.publicKeyB64, { onLog }), - openRelay: (relay, credential, confirmReqId, onHostCloseReason) => + openRelay: (relay, credential, confirmReqId, onHostCloseReason, isForeground) => connectMobileRelayRpcSession({ relay, resumeToken: credential.token, @@ -94,6 +94,7 @@ function createSupervisor( resumeConfirmReqId: confirmReqId, deviceToken: host.deviceToken, desktopPublicKeyB64: host.publicKeyB64, + isForeground, onHostCloseReason, onLog }), diff --git a/mobile/src/transport/mobile-endpoint-supervisor-contract.ts b/mobile/src/transport/mobile-endpoint-supervisor-contract.ts index 2a784fd8895..29ec807e649 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor-contract.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor-contract.ts @@ -12,7 +12,9 @@ export type MobileEndpointSupervisorDependencies = { relay: MobileRelayEndpoint, credential: { token: string; version: number }, confirmReqId: string, - onHostCloseReason?: (reason: RelayHostCloseReason) => void + onHostCloseReason?: (reason: RelayHostCloseReason) => void, + // Gates the session's idle liveness sweep; a backgrounded app spends no probes. + isForeground?: () => boolean ) => MobileRelayRpcSession resolveRelay: typeof resolveMobileRelayEndpoint readBundle: (hostId: string) => Promise diff --git a/mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts b/mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts index 3ee52fc7ddf..0e8f32ee5e3 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts @@ -1,5 +1,6 @@ import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' import { MobileEndpointSupervisor } from './mobile-endpoint-supervisor' +import { MobileEndpointHysteresis } from './mobile-endpoint-hysteresis' import { dependencies, FakeLogicalClient, @@ -8,6 +9,17 @@ import { host } from './mobile-endpoint-supervisor-test-fakes' +// A cell that authenticates and then answers the confirm for a different relay host +// — what a rehomed desktop produces. The session fails after the logical cutover. +function confirmRejectingRelaySession(logical: FakeLogicalClient): FakeRelaySession { + const session = new FakeRelaySession('connected', new Error('relay resume confirmation missing')) + session.whenResumeConfirmed = async () => { + session.publishState('disconnected') + logical.publishState('disconnected') + } + return session +} + vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' })) vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) })) @@ -48,4 +60,98 @@ describe('mobile endpoint supervisor direct probe', () => { expect(logical.getActivePath()).toBe('relay') supervisor.stop() }) + + it('recovers the relay at once while the probe is still dialing direct', async () => { + const logical = new FakeLogicalClient('connected', 'relay') + // A black-holed LAN endpoint: the dial sits unanswered for its whole 12s budget. + const direct = new FakeSession('connecting') + const openRelay = vi.fn(() => new FakeRelaySession('connected')) + const deps = dependencies({ openDirect: vi.fn(() => direct), openRelay }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + await supervisor.start() + + await vi.advanceTimersByTimeAsync(15_000) + expect(deps.openDirect).toHaveBeenCalledOnce() + logical.publishState('disconnected') + await vi.advanceTimersByTimeAsync(0) + + // Why: the dial is a pure observation, so it no longer owns the operation + // mutex — recovery does not wait out the probe's budget. + expect(openRelay).toHaveBeenCalledOnce() + expect(logical.getState()).toBe('connected') + expect(logical.getActivePath()).toBe('relay') + supervisor.stop() + }) + + it('backs off a dial whose resume confirm fails after the cutover', async () => { + const recordMigration = vi.spyOn(MobileEndpointHysteresis.prototype, 'recordMigration') + const logical = new FakeLogicalClient('disconnected', 'lan') + const openRelay = vi.fn(() => confirmRejectingRelaySession(logical)) + const deps = dependencies({ openRelay, randomBytes: () => new Uint8Array([128, 0]) }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + + await supervisor.start() + // Two sockets per pass: a confirm mismatch reads as a stale cell assignment, so + // the existing director fallback re-resolves and dials the authoritative target. + expect(openRelay).toHaveBeenCalledTimes(2) + expect(logical.migrateTo).toHaveBeenCalledTimes(2) + + // Why: `connected` is published at authentication, so the cutover happens before + // the confirm answers. A confirm that then fails must still book the shared + // cooldown — reporting it as an established dial redials in a tight loop. + await vi.advanceTimersByTimeAsync(0) + expect(openRelay).toHaveBeenCalledTimes(2) + + // 250ms, then 500ms, then 1000ms: the streak grows instead of resetting, which + // it could not do if setActiveSession had run for this dying session. + await vi.advanceTimersByTimeAsync(249) + expect(openRelay).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(openRelay).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(250) + expect(openRelay).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(250) + expect(openRelay).toHaveBeenCalledTimes(6) + await vi.advanceTimersByTimeAsync(999) + expect(openRelay).toHaveBeenCalledTimes(6) + await vi.advanceTimersByTimeAsync(1) + expect(openRelay).toHaveBeenCalledTimes(8) + + // No session whose confirm failed is ever booked as a migration. + expect(recordMigration).not.toHaveBeenCalled() + supervisor.stop() + }) + + it('replays a relay recovery that landed while the direct cutover owned the mutex', async () => { + const logical = new FakeLogicalClient('connected', 'relay') + const openRelay = vi.fn(() => new FakeRelaySession('connected')) + const deps = dependencies({ openDirect: vi.fn(() => new FakeSession('connected')), openRelay }) + const supervisor = new MobileEndpointSupervisor(logical, host, deps) + await supervisor.start() + + let release!: () => void + const cutover = new Promise((resolve) => { + release = resolve + }) + // The candidate loses the cutover, so the logical client stays on the relay path. + logical.migrateTo.mockImplementationOnce(async (candidate) => { + await cutover + candidate.close() + }) + // Three authenticated probes plus the observation and dwell windows. + await vi.advanceTimersByTimeAsync(60_000) + expect(logical.migrateTo).toHaveBeenCalledOnce() + + logical.publishState('disconnected') + await vi.advanceTimersByTimeAsync(0) + expect(openRelay).not.toHaveBeenCalled() + + release() + await vi.advanceTimersByTimeAsync(0) + + // The queued request is replayed by afterProbe, never dropped. + expect(openRelay).toHaveBeenCalledOnce() + expect(logical.getState()).toBe('connected') + supervisor.stop() + }) }) diff --git a/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts b/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts index 80f4438c160..cc4d91ea9da 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts @@ -65,6 +65,7 @@ export class FakeRelaySession extends FakeSession implements MobileRelayRpcSessi renewed: this.renewed, resumeExpiresAt: this.resumeExpiry }) + whenResumeConfirmed = () => Promise.resolve() getFailure = () => this.failure } diff --git a/mobile/src/transport/mobile-endpoint-supervisor.test.ts b/mobile/src/transport/mobile-endpoint-supervisor.test.ts index 10ef892a479..028387d8232 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor.test.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor.test.ts @@ -189,6 +189,7 @@ describe('mobile endpoint supervisor', () => { resolved, expect.any(Object), expect.any(String), + expect.any(Function), expect.any(Function) ) expect(deps.saveHost).toHaveBeenCalledWith( @@ -562,6 +563,7 @@ describe('mobile endpoint supervisor', () => { relay, expect.objectContaining({ version: 3 }), expect.any(String), + expect.any(Function), expect.any(Function) ) supervisor.stop() @@ -610,6 +612,7 @@ describe('mobile endpoint supervisor', () => { relay, expect.objectContaining({ version: 3 }), expect.any(String), + expect.any(Function), expect.any(Function) ) supervisor.stop() diff --git a/mobile/src/transport/mobile-endpoint-supervisor.ts b/mobile/src/transport/mobile-endpoint-supervisor.ts index 9ba12f35112..372fd7372a2 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor.ts @@ -16,6 +16,7 @@ import { } from './mobile-relay-credential-rotation' import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle' import { MobileEndpointNudgeRouter } from './mobile-endpoint-nudge-router' +import { RelayRecoveryIntentQueue } from './relay-recovery-intent-queue' import { MobileRelayDirectGraceTimer } from './mobile-relay-direct-grace-timer' import { MobileRelaySessionEstablisher } from './mobile-relay-session-establisher' import * as recoveryPresentation from './mobile-relay-recovery-presentation' @@ -38,7 +39,7 @@ export class MobileEndpointSupervisor { private bundle: MobileRelayCredentialBundle | null = null private stopped = false private operationInFlight = false - private pendingReplace = false + private readonly pending = new RelayRecoveryIntentQueue() private readonly nudgeRouter: MobileEndpointNudgeRouter private credentialRotationInFlight = false private relayRotationPending = false @@ -128,11 +129,8 @@ export class MobileEndpointSupervisor { }, afterProbe: () => { this.operationInFlight = false - if ( - this.pendingReplace || - this.relayRotationPending || - this.logical.getState() !== 'connected' - ) { + const queued = this.pending.takeRecovery() || this.pending.hasReplacement() + if (queued || this.relayRotationPending || this.logical.getState() !== 'connected') { void this.recoverRelay(this.relayRotationPending) } } @@ -195,6 +193,7 @@ export class MobileEndpointSupervisor { stop(): void { this.stopped = true + this.pending.clear() this.directProbe.stop() this.unsubscribeState?.() this.unsubscribeState = null @@ -215,13 +214,14 @@ export class MobileEndpointSupervisor { return } if (this.operationInFlight) { - // Why: a 12s direct probe can own the mutex when a network handoff lands; - // afterProbe replays the queued replacement so the signal is never lost. - this.pendingReplace ||= forceReplacement && ownsRecovery + // Why: a direct cutover or a slow post-migration write can own the mutex when + // a handoff lands. Every request is queued — an owning replacement keeps its + // force/owns intent, anything else replays as a plain recovery — so the + // holder's release replays it instead of dropping it. + this.pending.queue(forceReplacement, ownsRecovery) return } - if (this.pendingReplace) { - this.pendingReplace = false + if (this.pending.takeReplacement()) { forceReplacement = true ownsRecovery = true } @@ -236,7 +236,7 @@ export class MobileEndpointSupervisor { if (ownsRecovery) { // Why: never tear down a session no dial has disproven — the intent stays // queued so the armed retry runs forced once the cooldown lapses. - this.pendingReplace = true + this.pending.holdReplacement() } this.logRelay('recovery deferred by cooldown or gate') return @@ -260,7 +260,7 @@ export class MobileEndpointSupervisor { if (ownsRecovery) { // Why: no dial happened — keep the session and the intent; the reprobe // runs forced and replaces make-before-break once a credential exists. - this.pendingReplace = true + this.pending.holdReplacement() } return } @@ -273,7 +273,7 @@ export class MobileEndpointSupervisor { const dialed = await this.sessionEstablisher.dialEligible(selection.credentials) if (dialed.outcome === 'established') { // Why: a fresh socket satisfies any replacement intent queued mid-dial. - this.pendingReplace = false + this.pending.clearReplacement() retryAfterOperation = this.logical.getState() !== 'connected' return } @@ -293,11 +293,12 @@ export class MobileEndpointSupervisor { } } finally { this.operationInFlight = false + const queued = this.pending.takeRecovery() if (forceReplacement && this.relayRotationPending && this.isActive()) { this.leaseRotation.armRetry(this.relayReconnect.retryDelayMs(5000)) } // Why: the active relay can drop while migration follow-up still owns the mutex. - if (retryAfterOperation && this.isActive()) { + if ((retryAfterOperation || queued) && this.isActive()) { void this.recoverRelay() } } diff --git a/mobile/src/transport/mobile-relay-credential-rotation.ts b/mobile/src/transport/mobile-relay-credential-rotation.ts index 9b8a038e8e4..ef2630c8a67 100644 --- a/mobile/src/transport/mobile-relay-credential-rotation.ts +++ b/mobile/src/transport/mobile-relay-credential-rotation.ts @@ -142,11 +142,15 @@ export async function persistResumeConfirmation(args: { session: { getResumeConfirmation(): DeviceResumeConfirmed | null getResumeExpiresAt(): number | null + whenResumeConfirmed(): Promise } bundle: MobileRelayCredentialBundle usedCredentialVersion: number writeBundle: (bundle: MobileRelayCredentialBundle) => Promise }): Promise<{ bundle: MobileRelayCredentialBundle; leaseExpiry: number | null }> { + // Why: 'connected' is published at E2EE authentication now, so the confirm round + // trip can still be in flight here — its answer is what makes the bundle durable. + await args.session.whenResumeConfirmed() const confirmation = args.session.getResumeConfirmation() let bundle = args.bundle if (confirmation) { diff --git a/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts b/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts index b811721e562..fb8d2b5ffea 100644 --- a/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts +++ b/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts @@ -32,7 +32,10 @@ const relay = { e2eeFraming: 2 as const } -async function authenticateSession(onLog?: ConnectionLogSink) { +async function authenticateSession( + onLog?: ConnectionLogSink, + isForeground: () => boolean = () => true +) { const session = connectMobileRelayRpcSession({ relay, resumeToken: 'resume-secret', @@ -41,6 +44,7 @@ async function authenticateSession(onLog?: ConnectionLogSink) { deviceToken: 'device-token', desktopPublicKeyB64: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', requestTimeoutMs: 30_000, + isForeground, onLog }) fakes.linkOptions!.onHello({ @@ -52,12 +56,12 @@ async function authenticateSession(onLog?: ConnectionLogSink) { acceptedAs: 'current', resumeExpiresAt: Date.now() + 300_000 }) + // Authentication publishes 'connected' and puts both advisories on the wire. fakes.linkOptions!.onAuthenticated() - await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) - const confirmation = sentRequests()[0]! + const [confirmation, capabilities] = sentRequests() fakes.linkOptions!.onText( JSON.stringify({ - id: confirmation.id, + id: confirmation!.id, ok: true, result: { v: 1, @@ -74,17 +78,16 @@ async function authenticateSession(onLog?: ConnectionLogSink) { _meta: { runtimeId: 'runtime-1' } }) ) - await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledTimes(2)) - const capabilities = sentRequests()[1]! fakes.linkOptions!.onText( JSON.stringify({ - id: capabilities.id, + id: capabilities!.id, ok: true, result: {}, _meta: { runtimeId: 'runtime-1' } }) ) - await vi.waitFor(() => expect(session.getState()).toBe('connected')) + await session.whenResumeConfirmed() + expect(session.getState()).toBe('connected') fakes.sendText.mockClear() return session } @@ -95,6 +98,13 @@ function sentRequests(): Array<{ id: string; method: string }> { ) } +function answerProbe(): void { + const probe = sentRequests().at(-1)! + fakes.linkOptions!.onText( + JSON.stringify({ id: probe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } }) + ) +} + describe('mobile relay RPC session liveness', () => { beforeEach(() => { vi.useFakeTimers() @@ -104,16 +114,66 @@ describe('mobile relay RPC session liveness', () => { }) afterEach(() => vi.useRealTimers()) - it('sends no periodic traffic while an authenticated relay is idle', async () => { + it('sweeps an idle foregrounded relay once per idle interval', async () => { const session = await authenticateSession() - await vi.advanceTimersByTimeAsync(60_000) + await vi.advanceTimersByTimeAsync(24_999) + expect(fakes.sendText).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(sentRequests().map(({ method }) => method)).toEqual(['status.get']) + answerProbe() + + // Inbound traffic re-arms the sweep rather than stacking probes on it. + await vi.advanceTimersByTimeAsync(24_999) + expect(fakes.sendText).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(1) + expect(fakes.sendText).toHaveBeenCalledTimes(2) + expect(session.getState()).toBe('connected') + session.close() + }) + + it('spends no idle probe while the app is backgrounded', async () => { + let foreground = true + const session = await authenticateSession(undefined, () => foreground) + foreground = false + + await vi.advanceTimersByTimeAsync(120_000) expect(fakes.sendText).not.toHaveBeenCalled() expect(session.getState()).toBe('connected') + + // The resume that follows probes at once instead of waiting out the sweep. + foreground = true + session.notifyForeground('app-resume') + expect(sentRequests().map(({ method }) => method)).toEqual(['status.get']) session.close() }) + it('terminates a relay whose socket died in the background on two 2s resume misses', async () => { + const onLog = vi.fn() + const session = await authenticateSession(onLog) + + session.notifyForeground('app-resume') + expect(fakes.sendText).toHaveBeenCalledOnce() + // Why: the first frame after a resume rides a cold radio, so one slow answer is + // tolerated — but the verdict still lands at 4s instead of the old 8s. + await vi.advanceTimersByTimeAsync(2_000) + expect(session.getState()).toBe('connected') + expect(fakes.sendText).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1_999) + expect(session.getState()).toBe('connected') + await vi.advanceTimersByTimeAsync(1) + + expect(session.getState()).toBe('disconnected') + expect(fakes.close).toHaveBeenCalledOnce() + expect(onLog).toHaveBeenCalledWith( + expect.objectContaining({ + code: 'liveness-timeout', + detail: expect.stringMatching(/^probe-timeout; 2\/2 probes missed;/) + }) + ) + }) + it('disconnects after two fair foreground misses', async () => { const onLog = vi.fn() const session = await authenticateSession(onLog) @@ -161,22 +221,25 @@ describe('mobile relay RPC session liveness', () => { expect(secondId).not.toBe(firstId) }) - it('rate-limits foreground sequences without suppressing a retry', async () => { + it('rate-limits focus nudges but never an app resume', async () => { const session = await authenticateSession() session.notifyForeground('focus') - const firstProbe = sentRequests()[0]! - fakes.linkOptions!.onText( - JSON.stringify({ id: firstProbe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } }) - ) + answerProbe() session.notifyForeground('focus') await vi.advanceTimersByTimeAsync(9_999) - session.notifyForeground('app-resume') expect(fakes.sendText).toHaveBeenCalledOnce() - await vi.advanceTimersByTimeAsync(1) + + // The resume owns the only evidence that the suspended socket is still alive. + session.notifyForeground('app-resume') + expect(fakes.sendText).toHaveBeenCalledTimes(2) + answerProbe() + session.notifyForeground('focus') + expect(fakes.sendText).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(10_000) session.notifyForeground('focus') - expect(fakes.sendText).toHaveBeenCalledTimes(2) + expect(fakes.sendText).toHaveBeenCalledTimes(3) session.close() }) @@ -189,9 +252,9 @@ describe('mobile relay RPC session liveness', () => { session.close() }) - it('does not probe when work follows prolonged inbound silence', async () => { + it('does not probe when work follows inbound silence', async () => { const session = await authenticateSession() - await vi.advanceTimersByTimeAsync(60_000) + await vi.advanceTimersByTimeAsync(20_000) const pending = session.sendRequest('terminal.send', { terminal: 'term', text: 'hi' }) const outcome = pending.catch(() => undefined) diff --git a/mobile/src/transport/mobile-relay-rpc-session.test.ts b/mobile/src/transport/mobile-relay-rpc-session.test.ts index 4bf617faf50..b4861ec3fc6 100644 --- a/mobile/src/transport/mobile-relay-rpc-session.test.ts +++ b/mobile/src/transport/mobile-relay-rpc-session.test.ts @@ -22,6 +22,10 @@ const fakes = vi.hoisted(() => ({ close: vi.fn() })) +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) +vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' })) +vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) })) + vi.mock('./mobile-relay-e2ee-link', () => ({ MobileRelayE2eeLink: class { constructor(options: NonNullable) { @@ -33,6 +37,8 @@ vi.mock('./mobile-relay-e2ee-link', () => ({ })) import { connectMobileRelayRpcSession } from './mobile-relay-rpc-session' +import { persistResumeConfirmation } from './mobile-relay-credential-rotation' +import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle' const relay = { v: 1 as const, @@ -43,6 +49,13 @@ const relay = { e2eeFraming: 2 as const } +type SentRequest = { + id: string + method: string + deviceToken: string + params: Record | undefined +} + function openSession() { return connectMobileRelayRpcSession({ relay, @@ -55,8 +68,11 @@ function openSession() { }) } -async function confirmResume() { - const session = openSession() +function sentRequests(): SentRequest[] { + return fakes.sendText.mock.calls.map(([value]) => JSON.parse(value as string) as SentRequest) +} + +function receiveHello(): void { fakes.linkOptions!.onHello({ type: 'relay-hello', ok: true, @@ -66,21 +82,31 @@ async function confirmResume() { acceptedAs: 'current', resumeExpiresAt: Date.now() + 300_000 }) +} + +// E2EE authentication alone publishes 'connected'; the confirm and the capability +// advisory are already on the wire by the time it returns. +function authenticateSession() { + const session = openSession() + receiveHello() expect(session.getState()).toBe('handshaking') fakes.linkOptions!.onAuthenticated() - await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) - const request = JSON.parse(fakes.sendText.mock.calls[0]![0] as string) as { - id: string - method: string - params: unknown + const [confirmationRequest, capabilityRequest] = sentRequests() + return { + session, + confirmationRequest: confirmationRequest!, + capabilityRequest: capabilityRequest! } +} + +function answerConfirm(request: SentRequest, relayHostId = relay.relayHostId): void { fakes.linkOptions!.onText( JSON.stringify({ id: request.id, ok: true, result: { v: 1, - relay, + relay: { ...relay, relayHostId }, resumeConfirmation: { v: 1, reqId: 'confirm-1', @@ -93,39 +119,32 @@ async function confirmResume() { _meta: { runtimeId: 'runtime-1' } }) ) - await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledTimes(2)) - const capabilityRequest = JSON.parse(fakes.sendText.mock.calls[1]![0] as string) as { - id: string - method: string - deviceToken: string - params: { clientCapabilities?: string[] } - } - return { session, confirmationRequest: request, capabilityRequest } } -async function authenticateSession(capabilitySupported = true) { - const { session, confirmationRequest, capabilityRequest } = await confirmResume() - expect(session.getState()).toBe('handshaking') +function answerCapability(request: SentRequest, supported = true): void { fakes.linkOptions!.onText( JSON.stringify( - capabilitySupported - ? { - id: capabilityRequest.id, - ok: true, - result: capabilityRequest.params, - _meta: { runtimeId: 'runtime-1' } - } + supported + ? { id: request.id, ok: true, result: request.params, _meta: { runtimeId: 'runtime-1' } } : { - id: capabilityRequest.id, + id: request.id, ok: false, error: { code: 'method_not_found', message: 'Unknown method' }, _meta: { runtimeId: 'runtime-1' } } ) ) - await vi.waitFor(() => expect(session.getState()).toBe('connected')) +} + +// Both advisories answered and the send log cleared, so a test can read its own frames. +async function settledSession(capabilitySupported = true) { + const authenticated = authenticateSession() + answerConfirm(authenticated.confirmationRequest) + answerCapability(authenticated.capabilityRequest, capabilitySupported) + await authenticated.session.whenResumeConfirmed() + expect(authenticated.session.getState()).toBe('connected') fakes.sendText.mockClear() - return { session, confirmationRequest, capabilityRequest } + return authenticated } describe('mobile relay RPC session', () => { @@ -137,7 +156,7 @@ describe('mobile relay RPC session', () => { afterEach(() => vi.useRealTimers()) it('releases stream listeners on failure even when close follows it', async () => { - const { session } = await authenticateSession() + const { session } = await settledSession() const listener = vi.fn() session.subscribe('runtime.clientEvents.subscribe', {}, listener) await Promise.resolve() @@ -166,8 +185,8 @@ describe('mobile relay RPC session', () => { expect(listener).toHaveBeenCalledTimes(1) }) - it('requires exact resume observations and confirms by request ID before becoming connected', async () => { - const { session, confirmationRequest, capabilityRequest } = await authenticateSession() + it('sends the resume confirm by request ID and the capability advisory concurrently', async () => { + const { session, confirmationRequest, capabilityRequest } = await settledSession() expect(fakes.linkOptions).toMatchObject({ endpoint: relay, @@ -192,21 +211,103 @@ describe('mobile relay RPC session', () => { }) it('connects when an older runtime rejects capability negotiation', async () => { - const { session } = await authenticateSession(false) + const { session } = await settledSession(false) expect(session.getState()).toBe('connected') expect(session.getFailure()).toBeNull() }) it('connects when the relay never answers capability negotiation', async () => { - const { session } = await confirmResume() + const { session, confirmationRequest } = authenticateSession() + answerConfirm(confirmationRequest) - // Why: the advisory's own deadline used to fail confirmResume, so a link too slow to + // Why: the advisory's own deadline used to fail the confirm, so a link too slow to // answer within the request timeout never published 'connected' — it just redialled. - await vi.waitFor(() => expect(session.getState()).toBe('connected'), { timeout: 5_000 }) + await session.whenResumeConfirmed() + expect(session.getState()).toBe('connected') expect(session.getFailure()).toBeNull() }) + it('publishes connected at authentication, ahead of the confirm answer', async () => { + const states: string[] = [] + const session = openSession() + session.onStateChange((state) => states.push(state)) + receiveHello() + fakes.linkOptions!.onAuthenticated() + + // Why: the transport carries traffic from here; two serialized advisory round + // trips used to add ~200ms to every phone reconnect before anything rendered. + expect(session.getState()).toBe('connected') + expect(states).toEqual(['handshaking', 'connected']) + expect(session.getResumeConfirmation()).toBeNull() + expect(sentRequests().map(({ method }) => method)).toEqual([ + 'pairing.getEndpoints', + 'runtime.clientCapabilities.update' + ]) + + const [confirmationRequest] = sentRequests() + answerConfirm(confirmationRequest!) + await session.whenResumeConfirmed() + expect(session.getResumeConfirmation()).toMatchObject({ reqId: 'confirm-1' }) + session.close() + }) + + it('fails a session whose confirm answers for another relay host after connected', async () => { + const { session, confirmationRequest } = authenticateSession() + expect(session.getState()).toBe('connected') + + answerConfirm(confirmationRequest, 'ZZZZZZZZZZZZZZZZ') + await session.whenResumeConfirmed() + + // A late failure is fine; a lost one is not. + expect(session.getState()).toBe('disconnected') + expect(session.getFailure()?.message).toBe('relay resume confirmation missing') + expect(fakes.close).toHaveBeenCalledOnce() + }) + + it('fails a session whose confirm never answers', async () => { + vi.useFakeTimers() + try { + const { session } = authenticateSession() + expect(session.getState()).toBe('connected') + + await vi.advanceTimersByTimeAsync(1_000) + + expect(session.getState()).toBe('disconnected') + expect(session.getFailure()?.message).toBe('relay RPC timed out: pairing.getEndpoints') + } finally { + vi.useRealTimers() + } + }) + + it('hands the landed confirmation to resume persistence', async () => { + const { session, confirmationRequest } = authenticateSession() + const bundle: MobileRelayCredentialBundle = { + v: 1, + hostId: 'host-1', + deviceToken: 'device-token', + current: { token: 'A'.repeat(43), hash: 'B'.repeat(43), version: 3, expiresAt: 1 } + } + const writeBundle = vi.fn(async () => {}) + // Why: persistence runs right after the migration, while the confirm is still + // in flight — it must wait for the answer instead of reading a null. + const persisting = persistResumeConfirmation({ + session, + bundle, + usedCredentialVersion: 3, + writeBundle + }) + expect(writeBundle).not.toHaveBeenCalled() + + answerConfirm(confirmationRequest) + const applied = await persisting + + expect(writeBundle).toHaveBeenCalledOnce() + expect(applied.bundle.current.expiresAt).toBe(session.getResumeExpiresAt()) + expect(applied.leaseExpiry).toBe(session.getResumeExpiresAt()) + session.close() + }) + // Why: ConnectionState stays 'connecting' until relay-hello, so the migration bound // needs a separate signal to tell "cell never answered the upgrade" from "cell took // relay-auth and is still resolving the assignment". @@ -231,7 +332,7 @@ describe('mobile relay RPC session', () => { expect(session.getDialStage()).toBe('handshaking') fakes.linkOptions!.onAuthenticated() expect(session.getDialStage()).toBe('confirming') - await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) + expect(fakes.sendText).toHaveBeenCalledTimes(2) expect(stages).toEqual(['awaiting-hello', 'handshaking', 'confirming']) session.close() }) @@ -254,7 +355,7 @@ describe('mobile relay RPC session', () => { }) it('routes terminal and browser binary streams after confirmation', async () => { - const { session } = await authenticateSession() + const { session } = await settledSession() const terminalListener = vi.fn() session.subscribe('terminal.subscribe', { terminal: 'term-1' }, terminalListener) await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) @@ -311,7 +412,7 @@ describe('mobile relay RPC session', () => { }) it('rejects pending RPC work when the physical link fails', async () => { - const { session } = await authenticateSession() + const { session } = await settledSession() const pending = session.sendRequest('status.get') await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) fakes.linkOptions!.onError(new Error('relay transport error')) @@ -323,7 +424,7 @@ describe('mobile relay RPC session', () => { }) it('marks in-flight requests delivery-unknown when the session closes', async () => { - const { session } = await authenticateSession() + const { session } = await settledSession() const pending = session.sendRequest('terminal.send', { terminal: 'term', text: 'hi' }) await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) session.close() @@ -333,7 +434,7 @@ describe('mobile relay RPC session', () => { }) it('marks a relay RPC timeout delivery-unknown', async () => { - const { session } = await authenticateSession() + const { session } = await settledSession() vi.useFakeTimers() try { const pending = session.sendRequest('terminal.send', { terminal: 'term', text: 'hi' }) diff --git a/mobile/src/transport/mobile-relay-rpc-session.ts b/mobile/src/transport/mobile-relay-rpc-session.ts index 67b50ea591e..f74aaadefaa 100644 --- a/mobile/src/transport/mobile-relay-rpc-session.ts +++ b/mobile/src/transport/mobile-relay-rpc-session.ts @@ -17,9 +17,17 @@ import type { RelayHostCloseReason } from '../../../src/shared/relay-host-close- import type { RpcClient } from './rpc-client' import type { ConnectionLogSink, ConnectionState, RpcResponse } from './types' -const RELAY_PROBE_TIMEOUT_MS = 4_000 -const RELAY_MISSED_PROBE_LIMIT = 2 -const RELAY_FOREGROUND_PROBE_MIN_INTERVAL_MS = 10_000 +// Ordinary foreground checks: two 4s misses, at most one voluntary probe per 10s. +const RELAY_PROBE = { timeoutMs: 4_000, missedProbeLimit: 2, minIntervalMs: 10_000 } +// A socket that died while the process was suspended must be admitted before the +// user reads the screen as broken. Two 2s misses, not one: the first frame after a +// resume rides a cold radio, and a single slow answer is not proof of a dead link. +const RELAY_RESUME_PROBE = { timeoutMs: 2_000, missedProbeLimit: 2 } +// Bounds the confirm exactly as migrateTo's own wait used to, so the supervisor's +// mutex is never held for the full request timeout waiting on a silent cell. +const RELAY_CONFIRM_TIMEOUT_MS = 12_000 +// Foreground-only sweep so a silently-dead relay surfaces without a user action. +const RELAY_IDLE_PROBE_MS = 25_000 let relayRpcSessionSequence = 0 export type MobileRelayRpcSession = RpcClient & @@ -29,6 +37,10 @@ export type MobileRelayRpcSession = RpcClient & getAttachDeadlineAt(): number | null getResumeExpiresAt(): number | null getResumeConfirmation(): DeviceResumeConfirmed | null + // Settles once the resume confirm has answered or failed the session. Never + // rejects. Anyone reading getResumeConfirmation()/getResumeExpiresAt() must + // await it: 'connected' is published at authentication, ahead of the confirm. + whenResumeConfirmed(): Promise getFailure(): Error | null } @@ -40,6 +52,8 @@ export function connectMobileRelayRpcSession(args: { deviceToken: string desktopPublicKeyB64: string requestTimeoutMs?: number + // Gates the idle liveness sweep; a backgrounded app must not spend probes. + isForeground?: () => boolean createSocket?: (url: string) => WebSocket onHostCloseReason?: (reason: RelayHostCloseReason) => void onLog?: ConnectionLogSink @@ -52,6 +66,7 @@ export function connectMobileRelayRpcSession(args: { let attachDeadlineAt: number | null = null let resumeExpiresAt: number | null = null let resumeConfirmation: DeviceResumeConfirmed | null = null + let resumeConfirmed: Promise | null = null let failure: Error | null = null let closed = false let logSequence = 0 @@ -86,7 +101,7 @@ export function connectMobileRelayRpcSession(args: { dialStage.advance('handshaking') publishState('handshaking') }, - onAuthenticated: () => void confirmResume(), + onAuthenticated: () => publishAuthenticated(), onText: (plaintext) => { livenessWatchdog.noteAuthenticatedInbound(livenessIdentity) handleText(plaintext) @@ -125,7 +140,7 @@ export function connectMobileRelayRpcSession(args: { }, notifyForeground: (reason) => { if (state === 'connected' && reason !== 'network-change') { - livenessWatchdog.probeNow(livenessIdentity) + livenessWatchdog.probeNow(livenessIdentity, reason === 'app-resume' ? 'resume' : 'nudge') } }, close() { @@ -144,14 +159,18 @@ export function connectMobileRelayRpcSession(args: { getAttachDeadlineAt: () => attachDeadlineAt, getResumeExpiresAt: () => resumeExpiresAt, getResumeConfirmation: () => resumeConfirmation, + whenResumeConfirmed: () => resumeConfirmed ?? Promise.resolve(), getFailure: () => failure } const livenessWatchdog = new RpcSessionLivenessWatchdog({ transport: 'relay', - idleProbeMs: null, - probeTimeoutMs: RELAY_PROBE_TIMEOUT_MS, - missedProbeLimit: RELAY_MISSED_PROBE_LIMIT, - voluntaryProbeMinIntervalMs: RELAY_FOREGROUND_PROBE_MIN_INTERVAL_MS, + idleProbeMs: RELAY_IDLE_PROBE_MS, + probeTimeoutMs: RELAY_PROBE.timeoutMs, + missedProbeLimit: RELAY_PROBE.missedProbeLimit, + voluntaryProbeMinIntervalMs: RELAY_PROBE.minIntervalMs, + urgentProbeTimeoutMs: RELAY_RESUME_PROBE.timeoutMs, + urgentMissedProbeLimit: RELAY_RESUME_PROBE.missedProbeLimit, + shouldIdleProbe: () => args.isForeground?.() ?? true, sendProbe: () => state === 'connected' && sendFrame({ id: pending.nextId(), method: 'status.get', params: undefined }), @@ -170,13 +189,33 @@ export function connectMobileRelayRpcSession(args: { }) return client - async function confirmResume(): Promise { + // Why: the transport carries traffic the moment E2EE authenticates. The resume + // confirm and the capability advisory ride it concurrently instead of putting + // two serialized round trips in front of 'connected'. + function publishAuthenticated(): void { + if (closed) { + return + } dialStage.advance('confirming') + resumeConfirmed = confirmResume() + // Why: an unanswered advisory says nothing, but a frame that never reached the + // wire proves the socket cannot carry traffic — that alone still fails. + void settleMobileRuntimeCapabilities((method, params) => + sendRpc(method, params, requestTimeoutMs, true) + ).catch((error: unknown) => fail(asError(error))) + lastConnectedAt = Date.now() + livenessWatchdog.start(livenessIdentity) + publishState('connected') + } + + // Off the critical path but never optional: a failed confirm or a relayHostId + // that is not ours still fails the session, only later than it used to. + async function confirmResume(): Promise { try { const response = await sendRpc( 'pairing.getEndpoints', { resumeConfirmReqId: args.resumeConfirmReqId }, - requestTimeoutMs, + Math.min(requestTimeoutMs, RELAY_CONFIRM_TIMEOUT_MS), true ) if (!response.ok) { @@ -188,13 +227,6 @@ export function connectMobileRelayRpcSession(args: { } resumeConfirmation = result.resumeConfirmation resumeExpiresAt = result.resumeConfirmation.resumeExpiresAt - lastConnectedAt = Date.now() - // Why: an unanswered advisory must not keep a slow relay from ever reaching connected. - await settleMobileRuntimeCapabilities((method, params) => - sendRpc(method, params, requestTimeoutMs, true) - ) - livenessWatchdog.start(livenessIdentity) - publishState('connected') } catch (error) { fail(asError(error)) } diff --git a/mobile/src/transport/mobile-relay-runtime-failover.test.ts b/mobile/src/transport/mobile-relay-runtime-failover.test.ts index ce7cca3fd9f..7098746587a 100644 --- a/mobile/src/transport/mobile-relay-runtime-failover.test.ts +++ b/mobile/src/transport/mobile-relay-runtime-failover.test.ts @@ -88,6 +88,7 @@ class FakeRelaySession extends FakeSession implements MobileRelayRpcSession { this.dialStage.onDialStageChange(listener) getResumeExpiresAt = () => Date.now() + 30 * 24 * 3_600_000 getResumeConfirmation = () => null + whenResumeConfirmed = () => Promise.resolve() getFailure = () => this.failure } @@ -277,6 +278,7 @@ describe('relay runtime recovery without direct connectivity', () => { relay, expect.objectContaining({ version: 3 }), expect.any(String), + expect.any(Function), expect.any(Function) ) expect(logical.getActivePath()).toBe('relay') @@ -367,6 +369,7 @@ describe('relay runtime recovery without direct connectivity', () => { relay, expect.objectContaining({ version: 2 }), expect.any(String), + expect.any(Function), expect.any(Function) ) expect(logical.getActivePath()).toBe('relay') @@ -397,6 +400,7 @@ describe('relay runtime recovery without direct connectivity', () => { relay, expect.objectContaining({ version: 1 }), expect.any(String), + expect.any(Function), expect.any(Function) ) expect(logical.getActivePath()).toBe('relay') diff --git a/mobile/src/transport/mobile-relay-session-establisher.ts b/mobile/src/transport/mobile-relay-session-establisher.ts index 9a04ae44137..9ec8ebb3a37 100644 --- a/mobile/src/transport/mobile-relay-session-establisher.ts +++ b/mobile/src/transport/mobile-relay-session-establisher.ts @@ -110,7 +110,8 @@ export class MobileRelaySessionEstablisher { if (reason === RELAY_HOST_CLOSE_REASON.SIGNED_OUT) { args.logical.setHostSignedOut(true) } - } + }, + args.isForeground ) try { // Why: backgrounding or a direct winner withdraws this dial before cutover. @@ -126,6 +127,17 @@ export class MobileRelaySessionEstablisher { } return { ok: false, error: session.getFailure() ?? toError(error) } } + // Why: migrateTo now resolves at E2EE authentication, so the resume confirm can + // still fail this session after the cutover. Booking a dying session as an + // established dial skips backoff and redials in a tight loop — the supervisor's + // bookkeeping waits for the verdict even though the UI is already connected. + await session.whenResumeConfirmed() + if (session.getState() !== 'connected') { + if (!args.isActive() || directWon(args.logical)) { + return { ok: false, error: new RelayDialAbortedError() } + } + return { ok: false, error: session.getFailure() ?? new Error('relay lost at confirm') } + } args.controller.setActiveSession(session) if (!args.isForeground()) { args.controller.suspendActiveRelay(args.logical) diff --git a/mobile/src/transport/relay-recovery-intent-queue.ts b/mobile/src/transport/relay-recovery-intent-queue.ts new file mode 100644 index 00000000000..c34e40b8990 --- /dev/null +++ b/mobile/src/transport/relay-recovery-intent-queue.ts @@ -0,0 +1,45 @@ +// Recovery requests that arrive while the supervisor's operation mutex is held. +// Two latches, because the intents are not interchangeable: an owning forced +// replacement books the shared cooldown and may bring a stale session down, while +// every other request must replay as a plain recovery. Nothing is ever dropped. +export class RelayRecoveryIntentQueue { + private replacement = false + private recovery = false + + queue(forceReplacement: boolean, ownsRecovery: boolean): void { + if (forceReplacement && ownsRecovery) { + this.replacement = true + return + } + this.recovery = true + } + + holdReplacement(): void { + this.replacement = true + } + + hasReplacement(): boolean { + return this.replacement + } + + clearReplacement(): void { + this.replacement = false + } + + takeReplacement(): boolean { + const queued = this.replacement + this.replacement = false + return queued + } + + takeRecovery(): boolean { + const queued = this.recovery + this.recovery = false + return queued + } + + clear(): void { + this.replacement = false + this.recovery = false + } +} diff --git a/mobile/src/transport/rpc-session-liveness-watchdog.ts b/mobile/src/transport/rpc-session-liveness-watchdog.ts index 36525f60fb0..b54aa0679b6 100644 --- a/mobile/src/transport/rpc-session-liveness-watchdog.ts +++ b/mobile/src/transport/rpc-session-liveness-watchdog.ts @@ -13,11 +13,19 @@ type WatchdogOptions = { probeTimeoutMs?: number missedProbeLimit?: number voluntaryProbeMinIntervalMs?: number + // Bounds for probeImmediately(); default to the ordinary probe bounds. + urgentProbeTimeoutMs?: number + urgentMissedProbeLimit?: number + // Gates the idle sweep only. False re-arms without probing — a backgrounded app + // must not spend a probe, and its resume probes immediately anyway. + shouldIdleProbe?: () => boolean now?: () => number setTimer?: typeof setTimeout clearTimer?: typeof clearTimeout } +type ProbeProfile = { timeoutMs: number; missedProbeLimit: number } + export type LivenessTimeoutEvidence = { transport: 'direct' | 'relay' reason: 'probe-send-failed' | 'probe-timeout' @@ -33,9 +41,10 @@ export class RpcSessionLivenessWatchdog { private missedProbes = 0 private lastInboundAt = 0 private lastVoluntaryProbeAt: number | null = null + private profile: ProbeProfile private readonly idleProbeMs: number | null - private readonly probeTimeoutMs: number - private readonly missedProbeLimit: number + private readonly ordinaryProfile: ProbeProfile + private readonly urgentProfile: ProbeProfile private readonly voluntaryProbeMinIntervalMs: number private readonly now: () => number private readonly setTimer: typeof setTimeout @@ -43,8 +52,15 @@ export class RpcSessionLivenessWatchdog { constructor(private readonly options: WatchdogOptions) { this.idleProbeMs = options.idleProbeMs === undefined ? LIVENESS_IDLE_MS : options.idleProbeMs - this.probeTimeoutMs = options.probeTimeoutMs ?? LIVENESS_PROBE_TIMEOUT_MS - this.missedProbeLimit = options.missedProbeLimit ?? MISSED_PROBE_LIMIT + this.ordinaryProfile = { + timeoutMs: options.probeTimeoutMs ?? LIVENESS_PROBE_TIMEOUT_MS, + missedProbeLimit: options.missedProbeLimit ?? MISSED_PROBE_LIMIT + } + this.urgentProfile = { + timeoutMs: options.urgentProbeTimeoutMs ?? this.ordinaryProfile.timeoutMs, + missedProbeLimit: options.urgentMissedProbeLimit ?? this.ordinaryProfile.missedProbeLimit + } + this.profile = this.ordinaryProfile this.voluntaryProbeMinIntervalMs = options.voluntaryProbeMinIntervalMs ?? 0 this.now = options.now ?? Date.now this.setTimer = options.setTimer ?? setTimeout @@ -58,6 +74,7 @@ export class RpcSessionLivenessWatchdog { this.missedProbes = 0 this.lastInboundAt = this.now() this.lastVoluntaryProbeAt = null + this.profile = this.ordinaryProfile this.armIdle(identity) } @@ -87,19 +104,24 @@ export class RpcSessionLivenessWatchdog { this.armIdle(identity) } - probeNow(identity: RpcSessionIdentity): void { - if (this.identity !== identity || this.probing) { + // 'resume' is evidence the socket may have died while the process was suspended: + // it ignores the voluntary minimum, runs on the urgent bounds, and replaces any + // probe already in flight so the verdict lands on the short clock. + probeNow(identity: RpcSessionIdentity, urgency: 'nudge' | 'resume' = 'nudge'): void { + const urgent = urgency === 'resume' + if (this.identity !== identity || (this.probing && !urgent)) { return } const now = this.now() if ( + !urgent && this.lastVoluntaryProbeAt !== null && now - this.lastVoluntaryProbeAt < this.voluntaryProbeMinIntervalMs ) { return } this.lastVoluntaryProbeAt = now - this.startProbe(identity) + this.startProbe(identity, urgent ? this.urgentProfile : this.ordinaryProfile) } stop(identity: RpcSessionIdentity): void { @@ -112,6 +134,7 @@ export class RpcSessionLivenessWatchdog { this.missedProbes = 0 this.lastInboundAt = 0 this.lastVoluntaryProbeAt = null + this.profile = this.ordinaryProfile } private armIdle(identity: RpcSessionIdentity, delayMs = this.idleProbeMs): void { @@ -124,6 +147,10 @@ export class RpcSessionLivenessWatchdog { if (this.identity !== identity) { return } + if (this.options.shouldIdleProbe && !this.options.shouldIdleProbe()) { + this.armIdle(identity) + return + } const idleMs = this.now() - this.lastInboundAt if (this.idleProbeMs !== null && idleMs < this.idleProbeMs) { this.armIdle(identity, Math.max(1, this.idleProbeMs - Math.max(0, idleMs))) @@ -133,11 +160,12 @@ export class RpcSessionLivenessWatchdog { }, delayMs) } - private startProbe(identity: RpcSessionIdentity): void { + private startProbe(identity: RpcSessionIdentity, profile = this.ordinaryProfile): void { if (this.identity !== identity) { return } this.clearActiveTimer() + this.profile = profile this.probing = true const sentAt = this.now() let sent = false @@ -150,7 +178,7 @@ export class RpcSessionLivenessWatchdog { this.terminateCurrent(identity, 'probe-send-failed') return } - this.timer = this.setTimer(() => this.handleProbeTimeout(identity, sentAt), this.probeTimeoutMs) + this.timer = this.setTimer(() => this.handleProbeTimeout(identity, sentAt), profile.timeoutMs) } private handleProbeTimeout(identity: RpcSessionIdentity, sentAt: number): void { @@ -158,27 +186,28 @@ export class RpcSessionLivenessWatchdog { if (this.identity !== identity) { return } + const profile = this.profile const elapsedMs = this.now() - sentAt - if (elapsedMs < 0 || elapsedMs > this.probeTimeoutMs * 1.5) { + if (elapsedMs < 0 || elapsedMs > profile.timeoutMs * 1.5) { console.log('[net] activity-probe unfair window skipped', { transport: this.options.transport, elapsedMs, - timeoutMs: this.probeTimeoutMs + timeoutMs: profile.timeoutMs }) - this.startProbe(identity) + this.startProbe(identity, profile) return } this.missedProbes += 1 - if (this.missedProbes >= this.missedProbeLimit) { + if (this.missedProbes >= profile.missedProbeLimit) { this.terminateCurrent(identity, 'probe-timeout') return } console.log('[net] activity-probe timeout tolerated', { transport: this.options.transport, missedProbes: this.missedProbes, - missedProbeLimit: this.missedProbeLimit + missedProbeLimit: profile.missedProbeLimit }) - this.startProbe(identity) + this.startProbe(identity, profile) } private terminateCurrent( @@ -194,13 +223,13 @@ export class RpcSessionLivenessWatchdog { console.log('[net] activity-probe TIMEOUT — forcing reconnect', { transport: this.options.transport, missedProbes: this.missedProbes, - missedProbeLimit: this.missedProbeLimit + missedProbeLimit: this.profile.missedProbeLimit }) this.options.onTimeout?.({ transport: this.options.transport, reason, missedProbes: this.missedProbes, - missedProbeLimit: this.missedProbeLimit, + missedProbeLimit: this.profile.missedProbeLimit, lastInboundAgeMs: Math.max(0, this.now() - this.lastInboundAt) }) this.options.terminate(identity) From 0ba7f8dc8d2dca757e51d4e4c25ff3539fc3eb4d Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 04:42:59 -0400 Subject: [PATCH 08/37] feat(mobile): draw the last known tab strip while a session reconnects (#19258) * feat(mobile): draw the last known tab strip while a session reconnects Reopening a workspace the phone has already visited threw away everything it knew. The route clears its tabs on mount, so until the reconnect lands and the first snapshot is applied the session screen has an empty header and a bare spinner, even though the strip it is about to be handed is the one it drew a minute ago. Persist the four fields the strip actually draws -- id, type, title, agent -- per host and workspace, and add a reconnecting-with-cache shape to the route state so those rows render immediately, disabled, under the ids the live snapshot will reuse. Live tabs always outrank the cache, so a mid-session drop keeps its mounted terminals; an exhausted retry loop or a rejected pairing outranks it the other way, because a strip the user cannot reach is worse than the existing offline affordance. With nothing cached the screen behaves exactly as before. The body stays a placeholder. Replaying stored scrollback into the terminal WebView would double-render the same rows once the live stream replays them, so the strip is the cached content and the body waits for the stream. * fix(mobile): keep shell titles and unpaired hosts out of the cached tab strip Review of the reconnect strip cache found two ways it leaked. A terminal's title is whatever the shell last set, which is routinely the command line: a psql URL with an inline password, a curl with a bearer token. Both fit well inside the 64-character cap and both were written to plaintext AsyncStorage verbatim. Browser tabs carried their page title the same way. Terminals and browsers now collapse to a fixed label, with a resolved agent naming itself because that lookup is a closed enum. The rule lives in the storage module rather than its caller, so it holds for entries an older build already wrote, and a tab type this build cannot draw is dropped instead of having its title trusted. The cache also survived forgetting a host. Nothing expired an entry, and the module-global memory map meant a later save from any surviving host serialized the forgotten host's rows straight back to disk. Both cleanup paths now evict by host, dropping the in-memory rows and rewriting storage, with a pending debounced write cancelled so it cannot restore them. Also: the storage key digests the workspace id, which ended in a filesystem path, and cached rows carry the same de-emphasis as the disabled tab-bar buttons beside them, so an inert row does not pass for a live one. --- .../src/cache/session-tab-strip-cache.test.ts | 282 ++++++++++++++++++ mobile/src/cache/session-tab-strip-cache.ts | 228 ++++++++++++++ .../session/MobileSessionActiveContent.tsx | 11 +- mobile/src/session/MobileSessionHeader.tsx | 59 ++-- .../session/mobile-session-frame-styles.ts | 5 + ...obile-session-reconnect-view-state.test.ts | 155 ++++++++++ .../mobile-session-reconnect-view-state.ts | 61 ++++ .../mobile-session-route-parity.test.ts | 27 +- ...ession-route-source-family.test-support.ts | 1 + .../mobile-session-tab-strip-entries.ts | 116 +++++++ .../session/use-mobile-session-controller.ts | 4 +- .../use-mobile-session-presentation.ts | 29 +- .../use-mobile-session-tab-strip-cache.ts | 66 ++++ .../transport/host-removal-lifecycle.test.ts | 28 ++ .../src/transport/host-removal-lifecycle.ts | 4 + .../unpaired-host-credential-deletion.test.ts | 82 +++++ .../unpaired-host-credential-deletion.ts | 8 + 17 files changed, 1119 insertions(+), 47 deletions(-) create mode 100644 mobile/src/cache/session-tab-strip-cache.test.ts create mode 100644 mobile/src/cache/session-tab-strip-cache.ts create mode 100644 mobile/src/session/mobile-session-reconnect-view-state.test.ts create mode 100644 mobile/src/session/mobile-session-reconnect-view-state.ts create mode 100644 mobile/src/session/mobile-session-tab-strip-entries.ts create mode 100644 mobile/src/session/use-mobile-session-tab-strip-cache.ts create mode 100644 mobile/src/transport/unpaired-host-credential-deletion.test.ts diff --git a/mobile/src/cache/session-tab-strip-cache.test.ts b/mobile/src/cache/session-tab-strip-cache.test.ts new file mode 100644 index 00000000000..fa1ed188edc --- /dev/null +++ b/mobile/src/cache/session-tab-strip-cache.test.ts @@ -0,0 +1,282 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const asyncStorage = vi.hoisted(() => ({ + getItem: vi.fn(), + setItem: vi.fn(), + removeItem: vi.fn() +})) + +vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) + +import { + deleteCachedSessionTabStripForHost, + getSessionTabStripCacheKey, + loadCachedSessionTabStrip, + readCachedSessionTabStrip, + resetSessionTabStripCacheForTests, + saveCachedSessionTabStrip +} from './session-tab-strip-cache' +import type { MobileSessionTabStripPreview } from '../session/mobile-session-tab-strip-entries' + +const STORAGE_KEY = 'orca:session-tab-strip:v1' + +function preview(...ids: string[]): MobileSessionTabStripPreview { + return { + tabs: ids.map((id) => ({ id, type: 'terminal' as const, title: id, agentId: null })), + activeTabId: ids[0] ?? null + } +} + +function lastWrittenFile(): { workspaces: { key: string }[] } { + const call = asyncStorage.setItem.mock.calls.at(-1) + return JSON.parse(String(call?.[1])) +} + +beforeEach(() => { + vi.useFakeTimers() + asyncStorage.getItem.mockReset().mockResolvedValue(null) + asyncStorage.setItem.mockReset().mockResolvedValue(undefined) + resetSessionTabStripCacheForTests() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('getSessionTabStripCacheKey', () => { + it('digests the workspace id so no filesystem path reaches the key', () => { + const path = '/Users/someone/private-client/worktrees/acquisition' + const key = getSessionTabStripCacheKey('host-1', `repo::${path}`) + + expect(key).not.toContain(path) + expect(key).not.toContain('someone') + expect(key).toMatch(/^\["host-1","[0-9a-f]{32}"\]$/) + }) + + it('joins the two ids unambiguously, whatever a worktree path contains', () => { + expect(getSessionTabStripCacheKey('host', 'a\nb')).not.toBe( + getSessionTabStripCacheKey('host\na', 'b') + ) + expect(getSessionTabStripCacheKey('host-1', 'wt-1')).not.toBe( + getSessionTabStripCacheKey('host-1', 'wt-2') + ) + }) + + it('needs both a host and a workspace', () => { + expect(getSessionTabStripCacheKey(undefined, 'wt-1')).toBeNull() + expect(getSessionTabStripCacheKey('host-1', undefined)).toBeNull() + }) +}) + +describe('session tab strip cache', () => { + it('serves a save back synchronously and persists it once the write settles', async () => { + const key = getSessionTabStripCacheKey('host-1', 'wt-1') + saveCachedSessionTabStrip(key, preview('tab-1', 'tab-2')) + + expect(readCachedSessionTabStrip(key)?.tabs.map((tab) => tab.id)).toEqual(['tab-1', 'tab-2']) + expect(asyncStorage.setItem).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(300) + + expect(asyncStorage.setItem.mock.calls[0]?.[0]).toBe(STORAGE_KEY) + expect(lastWrittenFile().workspaces.map((w) => w.key)).toEqual([key]) + }) + + it('reads nothing synchronously before the stored file is loaded', async () => { + const key = getSessionTabStripCacheKey('host-1', 'wt-1') + asyncStorage.getItem.mockResolvedValue( + JSON.stringify({ workspaces: [{ key, preview: preview('tab-1') }] }) + ) + + expect(readCachedSessionTabStrip(key)).toBeNull() + expect((await loadCachedSessionTabStrip(key))?.tabs.map((tab) => tab.id)).toEqual(['tab-1']) + expect(readCachedSessionTabStrip(key)?.tabs).toHaveLength(1) + }) + + it('returns null for a workspace with no stored strip', async () => { + expect(await loadCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', 'wt-9'))).toBeNull() + expect(await loadCachedSessionTabStrip(null)).toBeNull() + }) + + it('survives unreadable storage', async () => { + asyncStorage.getItem.mockResolvedValue('{not json') + + expect(await loadCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', 'wt-1'))).toBeNull() + }) + + it('evicts the least recently written workspace past the cap', async () => { + for (let i = 0; i < 14; i++) { + saveCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', `wt-${i}`), preview('tab-1')) + } + await vi.advanceTimersByTimeAsync(300) + + const keys = lastWrittenFile().workspaces.map((w) => w.key) + expect(keys).toHaveLength(12) + expect(keys).not.toContain(getSessionTabStripCacheKey('host-1', 'wt-0')) + expect(keys.at(-1)).toBe(getSessionTabStripCacheKey('host-1', 'wt-13')) + }) + + it('re-writing a workspace makes it the newest, not the oldest', async () => { + for (let i = 0; i < 12; i++) { + saveCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', `wt-${i}`), preview('tab-1')) + } + saveCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', 'wt-0'), preview('tab-2')) + saveCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', 'wt-99'), preview('tab-1')) + await vi.advanceTimersByTimeAsync(300) + + const keys = lastWrittenFile().workspaces.map((w) => w.key) + expect(keys).toContain(getSessionTabStripCacheKey('host-1', 'wt-0')) + expect(keys).not.toContain(getSessionTabStripCacheKey('host-1', 'wt-1')) + }) + + it('records a workspace the host has emptied, so a stale strip cannot outlive it', async () => { + const key = getSessionTabStripCacheKey('host-1', 'wt-1') + saveCachedSessionTabStrip(key, preview('tab-1')) + saveCachedSessionTabStrip(key, { tabs: [], activeTabId: null }) + + expect(readCachedSessionTabStrip(key)).toEqual({ tabs: [], activeTabId: null }) + }) + + it('caps tabs per workspace and title length, and drops an unmatched active id', async () => { + const key = getSessionTabStripCacheKey('host-1', 'wt-1') + saveCachedSessionTabStrip(key, { + // A file tab, because the titles that survive redaction at all are the ones the cap has + // to bound. + tabs: Array.from({ length: 30 }, (_, i) => ({ + id: `tab-${i}`, + type: 'file' as const, + title: 'x'.repeat(200), + agentId: null + })), + activeTabId: 'tab-29' + }) + + const stored = readCachedSessionTabStrip(key) + expect(stored?.tabs).toHaveLength(24) + expect(stored?.tabs[0]?.title).toHaveLength(64) + expect(stored?.activeTabId).toBeNull() + }) + + it('drops fields a future tab type might smuggle into storage', async () => { + const key = getSessionTabStripCacheKey('host-1', 'wt-1') + saveCachedSessionTabStrip(key, { + tabs: [ + { + id: 'tab-1', + type: 'file', + title: 'notes.md', + agentId: null, + filePath: '/Users/someone/secret/notes.md' + } as never + ], + activeTabId: 'tab-1' + }) + await vi.advanceTimersByTimeAsync(300) + + expect(String(asyncStorage.setItem.mock.calls.at(-1)?.[1])).not.toContain('/Users/someone') + }) + + it('drops a stored entry naming a tab type this build cannot draw', async () => { + const key = getSessionTabStripCacheKey('host-1', 'wt-1') + saveCachedSessionTabStrip(key, { + tabs: [ + { id: 'tab-1', type: 'from-a-newer-build', title: 'raw title', agentId: null } as never, + { id: 'tab-2', type: 'file', title: 'notes.md', agentId: null } + ], + activeTabId: 'tab-2' + }) + + expect(readCachedSessionTabStrip(key)?.tabs.map((tab) => tab.id)).toEqual(['tab-2']) + }) + + it('never writes a shell-controlled terminal title, however it arrives', async () => { + const secret = 'psql postgres://admin:hunter2@db.internal/prod' + const key = getSessionTabStripCacheKey('host-1', 'wt-1') + saveCachedSessionTabStrip(key, { + tabs: [ + { id: 'tab-1', type: 'terminal', title: secret, agentId: null }, + { id: 'tab-2', type: 'terminal', title: secret, agentId: 'claude' }, + { id: 'tab-3', type: 'terminal', title: secret, agentId: 'not-a-known-agent' }, + { id: 'tab-4', type: 'browser', title: 'Acme Corp — Q3 layoffs memo', agentId: null } + ], + activeTabId: 'tab-1' + }) + await vi.advanceTimersByTimeAsync(300) + + expect(readCachedSessionTabStrip(key)?.tabs.map((tab) => tab.title)).toEqual([ + 'Terminal', + 'Claude', + 'Terminal', + 'Browser' + ]) + const written = String(asyncStorage.setItem.mock.calls.at(-1)?.[1]) + expect(written).not.toContain('hunter2') + expect(written).not.toContain('postgres://') + expect(written).not.toContain('layoffs') + }) + + it('scrubs a stored title written by an older build on the way back out', async () => { + const key = getSessionTabStripCacheKey('host-1', 'wt-1') + asyncStorage.getItem.mockResolvedValue( + JSON.stringify({ + workspaces: [ + { + key, + preview: { + tabs: [{ id: 'tab-1', type: 'terminal', title: 'curl -H token', agentId: null }], + activeTabId: 'tab-1' + } + } + ] + }) + ) + + expect((await loadCachedSessionTabStrip(key))?.tabs[0]?.title).toBe('Terminal') + }) + + it('forgets an unpaired host and cannot resurrect it from a later save', async () => { + const hostA = getSessionTabStripCacheKey('host-a', 'wt-1') + const hostB = getSessionTabStripCacheKey('host-b', 'wt-1') + saveCachedSessionTabStrip(hostA, preview('tab-a')) + saveCachedSessionTabStrip(hostB, preview('tab-b')) + await vi.advanceTimersByTimeAsync(300) + + await deleteCachedSessionTabStripForHost('host-a') + + expect(readCachedSessionTabStrip(hostA)).toBeNull() + expect(readCachedSessionTabStrip(hostB)?.tabs).toHaveLength(1) + expect(lastWrittenFile().workspaces.map((w) => w.key)).toEqual([hostB]) + + saveCachedSessionTabStrip(hostB, preview('tab-b2')) + await vi.advanceTimersByTimeAsync(300) + + expect(lastWrittenFile().workspaces.map((w) => w.key)).toEqual([hostB]) + }) + + it('forgets a host whose rows are only on disk, never read this session', async () => { + const hostA = getSessionTabStripCacheKey('host-a', 'wt-1') + const hostB = getSessionTabStripCacheKey('host-b', 'wt-1') + asyncStorage.getItem.mockResolvedValue( + JSON.stringify({ + workspaces: [ + { key: hostA, preview: preview('tab-a') }, + { key: hostB, preview: preview('tab-b') } + ] + }) + ) + + await deleteCachedSessionTabStripForHost('host-a') + + expect(lastWrittenFile().workspaces.map((w) => w.key)).toEqual([hostB]) + }) + + it('drops a pending debounced write so it cannot restore the forgotten host', async () => { + const hostA = getSessionTabStripCacheKey('host-a', 'wt-1') + saveCachedSessionTabStrip(hostA, preview('tab-a')) + + await deleteCachedSessionTabStripForHost('host-a') + await vi.advanceTimersByTimeAsync(300) + + expect(lastWrittenFile().workspaces).toEqual([]) + }) +}) diff --git a/mobile/src/cache/session-tab-strip-cache.ts b/mobile/src/cache/session-tab-strip-cache.ts new file mode 100644 index 00000000000..222e2c3fd27 --- /dev/null +++ b/mobile/src/cache/session-tab-strip-cache.ts @@ -0,0 +1,228 @@ +// Why: reconnecting to a workspace the phone opened a minute ago tears the session screen back +// to an empty strip and a spinner, even though the tab list it is about to be handed is the one +// it just displayed. Persist the shape of the strip per workspace so a reconnect paints the +// known tabs immediately and swaps in live rows under the same keys. +// +// This file is the authority on what reaches plaintext storage, not its callers: every entry is +// rebuilt field by field on the way in, and shell-controlled titles are replaced with fixed +// labels here rather than trusted to have been scrubbed upstream. +import AsyncStorage from '@react-native-async-storage/async-storage' +import { sha256 } from '@noble/hashes/sha256' +import { + getPersistableTabStripTitle, + isDrawableTabStripType, + type MobileSessionTabStripEntry, + type MobileSessionTabStripPreview +} from '../session/mobile-session-tab-strip-entries' + +const STORAGE_KEY = 'orca:session-tab-strip:v1' +// A phone realistically revisits a handful of workspaces; the caps bound both the stored blob +// and the cost of a single write. +const MAX_WORKSPACES = 12 +const MAX_TABS_PER_WORKSPACE = 24 +const MAX_TITLE_LENGTH = 64 +const WRITE_DEBOUNCE_MS = 250 +// 128 bits of a digest: far past collision range for a dozen workspaces, and short enough that +// the stored blob stays small. +const WORKSPACE_DIGEST_LENGTH = 32 + +type StoredWorkspace = { key: string; preview: MobileSessionTabStripPreview } +type StoredFile = { workspaces: StoredWorkspace[] } + +// Insertion-ordered, so the first key is the least recently written one to evict. +let memoryCache: Map | null = null +let loadPromise: Promise> | null = null +let writeTimer: ReturnType | null = null + +/** + * A workspace id ends in a filesystem path, so it is digested rather than stored. The host id + * stays readable because forgetting a host has to be able to find that host's rows, and because + * host ids already key several other entries in this store. + */ +export function getSessionTabStripCacheKey( + hostId: string | undefined, + worktreeId: string | undefined +): string | null { + if (!hostId || !worktreeId) { + return null + } + return JSON.stringify([hostId, digestWorkspaceId(worktreeId)]) +} + +/** Whatever this process already knows, with no await — so a revisit paints on the first frame. */ +export function readCachedSessionTabStrip(key: string | null): MobileSessionTabStripPreview | null { + if (!key || !memoryCache) { + return null + } + return memoryCache.get(key) ?? null +} + +export async function loadCachedSessionTabStrip( + key: string | null +): Promise { + if (!key) { + return null + } + const cache = await loadFile() + return cache.get(key) ?? null +} + +export function saveCachedSessionTabStrip( + key: string | null, + preview: MobileSessionTabStripPreview +): void { + if (!key) { + return + } + const redacted = redactPreview(preview) + const cache = memoryCache ?? new Map() + memoryCache = cache + // Map.set on an existing key keeps its original iteration position, so delete first to make + // the re-inserted key the newest and give the cap true LRU eviction. + cache.delete(key) + cache.set(key, redacted) + while (cache.size > MAX_WORKSPACES) { + const oldest = cache.keys().next().value + if (oldest === undefined) { + break + } + cache.delete(oldest) + } + scheduleWrite(cache) +} + +/** + * Drop every workspace belonging to a host the user has unpaired. Both the in-memory rows and + * the stored blob have to go: leaving either behind means the next save for any other host + * serializes the forgotten host's tabs straight back to disk. + */ +export async function deleteCachedSessionTabStripForHost(hostId: string): Promise { + // Load first so the rewrite below preserves other hosts. If storage is unreadable we still + // rewrite, which can cost another host its rows — the wrong direction for a cache, the right + // one for a deletion the user asked for. + const cache = await loadFile() + // Deleting the entry the iterator is standing on is well-defined for a Map. + for (const key of cache.keys()) { + if (readHostIdFromKey(key) === hostId) { + cache.delete(key) + } + } + if (writeTimer) { + clearTimeout(writeTimer) + writeTimer = null + } + await writeFile(cache) +} + +export function resetSessionTabStripCacheForTests(): void { + if (writeTimer) { + clearTimeout(writeTimer) + writeTimer = null + } + memoryCache = null + loadPromise = null +} + +function digestWorkspaceId(worktreeId: string): string { + const digest = sha256(new TextEncoder().encode(worktreeId)) + let hex = '' + for (const byte of digest) { + hex += byte.toString(16).padStart(2, '0') + } + return hex.slice(0, WORKSPACE_DIGEST_LENGTH) +} + +function readHostIdFromKey(key: string): string | null { + try { + const parsed = JSON.parse(key) as unknown + return Array.isArray(parsed) && typeof parsed[0] === 'string' ? parsed[0] : null + } catch { + return null + } +} + +async function loadFile(): Promise> { + if (memoryCache) { + return memoryCache + } + loadPromise ??= (async () => { + const parsed = await readStoredFile() + // A save that landed while the read was in flight owns the newer truth. + const cache = memoryCache ?? new Map() + for (const workspace of parsed) { + if (!cache.has(workspace.key)) { + cache.set(workspace.key, workspace.preview) + } + } + memoryCache = cache + return cache + })() + return loadPromise +} + +async function readStoredFile(): Promise { + try { + const raw = await AsyncStorage.getItem(STORAGE_KEY) + if (!raw) { + return [] + } + const parsed = JSON.parse(raw) as StoredFile + if (typeof parsed !== 'object' || parsed === null || !Array.isArray(parsed.workspaces)) { + return [] + } + return parsed.workspaces.flatMap((workspace) => { + if (typeof workspace?.key !== 'string' || !Array.isArray(workspace.preview?.tabs)) { + return [] + } + return [{ key: workspace.key, preview: redactPreview(workspace.preview) }] + }) + } catch { + return [] + } +} + +// Why: a flurry of snapshots (one per desktop republication) must not hammer AsyncStorage. +function scheduleWrite(cache: Map): void { + if (writeTimer) { + clearTimeout(writeTimer) + } + writeTimer = setTimeout(() => { + writeTimer = null + void writeFile(cache) + }, WRITE_DEBOUNCE_MS) +} + +async function writeFile(cache: Map): Promise { + const workspaces: StoredWorkspace[] = [...cache].map(([key, preview]) => ({ key, preview })) + await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify({ workspaces })).catch(() => {}) +} + +// Rebuilt field by field so a field later added to the live tab type cannot ride into storage +// without someone deciding it belongs there. +function redactPreview(preview: MobileSessionTabStripPreview): MobileSessionTabStripPreview { + const tabs: MobileSessionTabStripEntry[] = [] + for (const tab of preview.tabs ?? []) { + if (typeof tab?.id !== 'string' || !isDrawableTabStripType(tab.type)) { + continue + } + const agentId = typeof tab.agentId === 'string' ? tab.agentId : null + const title = typeof tab.title === 'string' ? tab.title : '' + tabs.push({ + id: tab.id, + type: tab.type, + title: getPersistableTabStripTitle({ type: tab.type, title, agentId }).slice( + 0, + MAX_TITLE_LENGTH + ), + agentId + }) + if (tabs.length === MAX_TABS_PER_WORKSPACE) { + break + } + } + const activeTabId = + typeof preview.activeTabId === 'string' && tabs.some((tab) => tab.id === preview.activeTabId) + ? preview.activeTabId + : null + return { tabs, activeTabId } +} diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index 019e83c6a99..00c852dbf01 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -74,6 +74,7 @@ export function MobileSessionActiveContent({ activePendingTerminalTab, isPendingTerminalRecoveryParked, retryPendingTerminalRecovery, + reconnectViewState, showLoadingState, showEmptyState, keyboardLift, @@ -81,7 +82,15 @@ export function MobileSessionActiveContent({ toastAnimatedStyle, createTabBusy } = controller - return showLoadingState ? ( + // Why: the cached strip in the header is the content during a reconnect; the terminal body + // cannot be, because replaying stored scrollback into the WebView would double-render once the + // live stream replays the same rows. See mobile-session-reconnect-view-state. + return reconnectViewState.kind === 'reconnecting-with-cache' ? ( + + + {reconnectViewState.label} + + ) : showLoadingState ? ( diff --git a/mobile/src/session/MobileSessionHeader.tsx b/mobile/src/session/MobileSessionHeader.tsx index 552f507a787..a23c216c729 100644 --- a/mobile/src/session/MobileSessionHeader.tsx +++ b/mobile/src/session/MobileSessionHeader.tsx @@ -14,10 +14,6 @@ import { MobileSessionHeaderIconButton } from './MobileSessionHeaderIconButton' import { triggerMediumImpact } from '../platform/haptics' import { StatusDot } from '../components/StatusDot' import { MobileAgentIcon } from '../components/MobileAgentIcon' -import { - getMobileSessionTabTitle, - resolveMobileTerminalTabAgentId -} from './mobile-terminal-tab-agent' import { colors } from '../theme/mobile-theme' import { QuickCommandsTabButton } from './QuickCommandsTabButton' import { styles } from './mobile-session-styles' @@ -32,7 +28,6 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC forceReconnectHost, worktreeName, activePanel, - activeSessionTabId, activeSessionTabIdRef, tabStripRef, tabStripOffsetRef, @@ -52,7 +47,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC scrollActiveTabIntoView, switchSessionTab, openSessionTabActionSheetAfterKeyboardDismiss, - visibleTabs, + tabStripRows, showConnectionRetry, terminalSummary, handlePanelTap, @@ -117,7 +112,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC ) : null} - {visibleTabs.length > 0 && ( + {tabStripRows.length > 0 && ( {/* Why: tab taps must register on first press with the keyboard open instead of being eaten by dismissal (#5106). */} - {visibleTabs.map((t) => ( + {tabStripRows.map(({ entry, isActive, tab }) => ( { const { x, width } = e.nativeEvent.layout - tabLayoutsRef.current.set(t.id, { x, width }) - if (t.id === activeSessionTabIdRef.current) { - scrollActiveTabIntoView(t.id, false) + tabLayoutsRef.current.set(entry.id, { x, width }) + if (entry.id === activeSessionTabIdRef.current) { + scrollActiveTabIntoView(entry.id, false) } }} - onPress={() => switchSessionTab(t)} - onLongPress={() => { - triggerMediumImpact() - openSessionTabActionSheetAfterKeyboardDismiss(t) - }} + // A cached preview row has no live tab behind it, so both gestures need the + // reconnect to land first. + disabled={tab === null} + onPress={tab === null ? undefined : () => switchSessionTab(tab)} + onLongPress={ + tab === null + ? undefined + : () => { + triggerMediumImpact() + openSessionTabActionSheetAfterKeyboardDismiss(tab) + } + } delayLongPress={400} > - {t.type === 'browser' && ( + {entry.type === 'browser' && ( )} - {t.type === 'markdown' && ( + {entry.type === 'markdown' && ( )} - {t.type === 'file' && ( + {entry.type === 'file' && ( )} - {t.type === 'agent-session' && } - {t.type === 'terminal' && - (() => { - const agentId = resolveMobileTerminalTabAgentId(t) - return agentId ? : null - })()} + {entry.agentId !== null && } - {getMobileSessionTabTitle(t)} + {entry.title} diff --git a/mobile/src/session/mobile-session-frame-styles.ts b/mobile/src/session/mobile-session-frame-styles.ts index a02c14be014..22d3c6e76cc 100644 --- a/mobile/src/session/mobile-session-frame-styles.ts +++ b/mobile/src/session/mobile-session-frame-styles.ts @@ -102,6 +102,11 @@ export const mobileSessionFrameStyles = StyleSheet.create({ borderBottomWidth: 2, borderBottomColor: 'transparent' }, + // Why: a cached row is inert until the reconnect lands, so it carries the same de-emphasis as + // the disabled tab-bar buttons beside it rather than passing for a live tab. + tabPreview: { + opacity: 0.45 + }, tabActive: { // Neutral grey underline, matching the desktop terminal tab's active // indicator (a muted foreground/card mix), not a blue accent. diff --git a/mobile/src/session/mobile-session-reconnect-view-state.test.ts b/mobile/src/session/mobile-session-reconnect-view-state.test.ts new file mode 100644 index 00000000000..09f9bbb8447 --- /dev/null +++ b/mobile/src/session/mobile-session-reconnect-view-state.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, it } from 'vitest' +import { selectMobileSessionReconnectViewState } from './mobile-session-reconnect-view-state' +import { + getMobileSessionTabStripRows, + toMobileSessionTabStripPreview, + type MobileSessionTabStripPreview +} from './mobile-session-tab-strip-entries' +import type { MobileSessionTab } from './mobile-session-route-types' + +function terminalTab(id: string, title: string, isActive = false): MobileSessionTab { + return { type: 'terminal', id, title, terminal: `h-${id}`, isActive } +} + +const cachedPreview: MobileSessionTabStripPreview = { + tabs: [ + { id: 'tab-1', type: 'terminal', title: 'claude', agentId: 'claude' }, + { id: 'tab-2', type: 'terminal', title: 'shell', agentId: null } + ], + activeTabId: 'tab-1' +} + +const base = { + connState: 'reconnecting', + verdictKind: 'normal', + terminalsLoaded: false, + liveTabCount: 0, + activeHandle: null, + cachedPreview: null +} as const + +describe('selectMobileSessionReconnectViewState', () => { + it('renders the cached strip with a progress label while reconnecting', () => { + const state = selectMobileSessionReconnectViewState({ ...base, cachedPreview }) + + expect(state).toEqual({ + kind: 'reconnecting-with-cache', + preview: cachedPreview, + label: 'Reconnecting…' + }) + }) + + it('labels the post-connect hydration gap as loading, not reconnecting', () => { + const state = selectMobileSessionReconnectViewState({ + ...base, + connState: 'connected', + cachedPreview + }) + + expect(state.kind === 'reconnecting-with-cache' && state.label).toBe('Loading tabs…') + }) + + it('blocks when nothing is cached for this workspace', () => { + expect(selectMobileSessionReconnectViewState(base)).toEqual({ kind: 'blocking' }) + expect( + selectMobileSessionReconnectViewState({ + ...base, + cachedPreview: { tabs: [], activeTabId: null } + }) + ).toEqual({ kind: 'blocking' }) + }) + + it('keeps mounted live content instead of swapping in its own cached snapshot', () => { + expect( + selectMobileSessionReconnectViewState({ ...base, liveTabCount: 2, cachedPreview }) + ).toEqual({ kind: 'live' }) + expect( + selectMobileSessionReconnectViewState({ ...base, activeHandle: 'h-1', cachedPreview }) + ).toEqual({ kind: 'live' }) + }) + + it('treats a host-confirmed empty workspace as live', () => { + expect( + selectMobileSessionReconnectViewState({ + ...base, + connState: 'connected', + terminalsLoaded: true, + cachedPreview + }) + ).toEqual({ kind: 'live' }) + }) + + it('falls back to the offline state once the retry loop or the pairing has failed', () => { + expect( + selectMobileSessionReconnectViewState({ ...base, verdictKind: 'unreachable', cachedPreview }) + ).toEqual({ kind: 'offline' }) + expect( + selectMobileSessionReconnectViewState({ ...base, verdictKind: 'auth-failed', cachedPreview }) + ).toEqual({ kind: 'offline' }) + }) + + it('keeps showing the cache through a transient warning verdict', () => { + expect( + selectMobileSessionReconnectViewState({ ...base, verdictKind: 'warning', cachedPreview }).kind + ).toBe('reconnecting-with-cache') + }) +}) + +describe('getMobileSessionTabStripRows', () => { + it('draws disabled preview rows while reconnecting, then the live tabs under the same keys', () => { + const preview = selectMobileSessionReconnectViewState({ ...base, cachedPreview }) + const previewRows = getMobileSessionTabStripRows({ + liveTabs: [], + activeSessionTabId: null, + preview: preview.kind === 'reconnecting-with-cache' ? preview.preview : null + }) + + expect(previewRows.map((row) => row.entry.id)).toEqual(['tab-1', 'tab-2']) + expect(previewRows.map((row) => row.tab)).toEqual([null, null]) + expect(previewRows.map((row) => row.isActive)).toEqual([true, false]) + + const liveTabs = [terminalTab('tab-1', 'claude', true), terminalTab('tab-2', 'shell')] + const liveRows = getMobileSessionTabStripRows({ + liveTabs, + activeSessionTabId: 'tab-1', + preview: null + }) + + expect(liveRows.map((row) => row.entry.id)).toEqual(previewRows.map((row) => row.entry.id)) + expect(liveRows.map((row) => row.isActive)).toEqual(previewRows.map((row) => row.isActive)) + expect(liveRows.every((row) => row.tab !== null)).toBe(true) + }) + + it('prefers live tabs over a preview that is still present', () => { + const rows = getMobileSessionTabStripRows({ + liveTabs: [terminalTab('tab-9', 'fresh', true)], + activeSessionTabId: 'tab-9', + preview: cachedPreview + }) + + expect(rows.map((row) => row.entry.id)).toEqual(['tab-9']) + }) + + it('keeps only the drawn fields when projecting a preview to persist', () => { + const preview = toMobileSessionTabStripPreview( + [ + { + type: 'terminal', + id: 'tab-1', + title: 'claude', + terminal: 'h-1', + launchAgent: 'claude', + launchDraft: 'unsent secret prompt', + isActive: true + } + ], + 'tab-1' + ) + + expect(preview).toEqual({ + tabs: [{ id: 'tab-1', type: 'terminal', title: 'claude', agentId: 'claude' }], + activeTabId: 'tab-1' + }) + expect(JSON.stringify(preview)).not.toContain('unsent secret prompt') + }) +}) diff --git a/mobile/src/session/mobile-session-reconnect-view-state.ts b/mobile/src/session/mobile-session-reconnect-view-state.ts new file mode 100644 index 00000000000..fe980676408 --- /dev/null +++ b/mobile/src/session/mobile-session-reconnect-view-state.ts @@ -0,0 +1,61 @@ +import type { ConnectionVerdict } from '../transport/connection-health' +import type { ConnectionState } from '../transport/types' +import type { MobileSessionTabStripPreview } from './mobile-session-tab-strip-entries' + +/** + * What the session screen should draw while the phone is not yet serving live tabs. + * + * - `live`: real tabs are mounted (or the host has confirmed there are none). The existing + * loading/empty/content branches own the screen. + * - `reconnecting-with-cache`: nothing live yet, but this workspace's last strip is on the + * device. Draw it, disabled, with a compact progress line instead of a bare spinner. + * - `offline`: the retry loop has given up or the pairing is rejected. A stale strip would + * imply a session we cannot reach, so fall back to the existing offline affordance. + * - `blocking`: nothing live and nothing cached. Unchanged from before this state existed. + */ +export type MobileSessionReconnectViewState = + | { kind: 'live' } + | { kind: 'reconnecting-with-cache'; preview: MobileSessionTabStripPreview; label: string } + | { kind: 'offline' } + | { kind: 'blocking' } + +export function selectMobileSessionReconnectViewState(args: { + connState: ConnectionState + verdictKind: ConnectionVerdict['kind'] + terminalsLoaded: boolean + liveTabCount: number + activeHandle: string | null + cachedPreview: MobileSessionTabStripPreview | null +}): MobileSessionReconnectViewState { + const { connState, verdictKind, terminalsLoaded, liveTabCount, activeHandle, cachedPreview } = + args + // A mounted terminal or tab is the real thing; a mid-session drop must never trade it for a + // snapshot of itself, however the connection is faring. + if (liveTabCount > 0 || activeHandle !== null) { + return { kind: 'live' } + } + // The host has answered and said this workspace is empty — that is live truth, not a gap. + if (connState === 'connected' && terminalsLoaded) { + return { kind: 'live' } + } + if (verdictKind === 'unreachable' || verdictKind === 'auth-failed') { + return { kind: 'offline' } + } + if (cachedPreview && cachedPreview.tabs.length > 0) { + return { + kind: 'reconnecting-with-cache', + preview: cachedPreview, + label: reconnectProgressLabel(connState) + } + } + return { kind: 'blocking' } +} + +function reconnectProgressLabel(connState: ConnectionState): string { + if (connState === 'connected') { + return 'Loading tabs…' + } + return connState === 'reconnecting' || connState === 'disconnected' + ? 'Reconnecting…' + : 'Connecting…' +} diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index bc951bfa206..1455765771f 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -37,6 +37,7 @@ const LOGIC_EXPANSION_NAMES = new Set([ 'useMobileSessionContentCreateActions', 'useMobileSessionCloseActions', 'useMobileSessionBulkClose', + 'useMobileSessionTabStripCache', 'useMobileSessionPresentation', 'useMobileSessionPanelRouteActions' ]) @@ -62,12 +63,12 @@ const HOST_COMPONENT_NAMES = new Set([ 'View' ]) -const HEAD_MAIN_HOOK_SHA256 = '10071240ef9edafc2b9c8bed73be83dceaf7828e3b29f17dab55da020a7697a6' -const HEAD_HOOK_BINDING_SHA256 = '1dadb8c3dc0573ea20659ce7251629669e618dd0effaeac3a4536b29c2e865a1' +const HEAD_MAIN_HOOK_SHA256 = '1b539cb02e2b6a3ea906b3c23050b8ed072e01e86ff64b3fde37c0643e9ea008' +const HEAD_HOOK_BINDING_SHA256 = 'fb32bba96822e00df7e451751101784839683c7b31e50e3ee871e13cddabe619' const HEAD_CALLBACK_IDENTITY_SHA256 = '2a9e4825df007f6ef53b81aa5004991d6318eee7507b44d625c07e630be432eb' const HEAD_CALLBACK_BODY_SHA256 = '22103ba85a86e3a3fcb80a7509c7a455d79863010cde3af02db6565b55e3ebe9' -const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' +const HEAD_EFFECT_SHA256 = '016d046a108bd5b44ffcf0d277d5c64bb10657e13d79f9d37b91c056eef743df' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = '536c72b233c813bb0cea164b090bdce5406ceb965bbc5b83c1f89b89b46f3821' @@ -79,11 +80,11 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - '31951b0b83be01ebfa659c4b94df9ad7eaff6404df5338fbade89eb7473a3cb4' -const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' -const HEAD_LEAF_JSX_SHA256 = '21dba981875e173f692590bf910d60964660c5f4cbb79f3a377c7e54f6a1f016' + '0ad9a4e8b336b9f10db4d39553bc1880f00c164d575766fe31f6e92cc1cccd25' +const HEAD_HOST_JSX_SHA256 = 'd2ebf1684d3ea579707e545334f9abbc4977552bf5322df11765b4f974d7078e' +const HEAD_LEAF_JSX_SHA256 = '9d6f8e326f69ddda44855c4af988bfdfadce34fe47c47946fbbc2eb3cb0b8782' const HEAD_STYLE_REFERENCE_SHA256 = - '295a3501c2c6d7bea7c8bbf38b3f3534f01344cd7e1b91bb8e07c040821d596a' + 'e12ba3494873d828d84ea4d2cc6ce8ee3414cec7f371e00eef8cb18cb3cc7a3b' const HEAD_IDENTITY_FIELD_SHA256 = '91146853930a34dd1f3d80e5c97fbacd7cf19fb93dd26fe8fc6f29169622f9d6' const HEAD_NAVIGATION_SHA256 = '9d96f5dad7de555d6553eac39c0fab00efad507470fd562cb9beaa32db16f512' @@ -472,13 +473,13 @@ describe('mobile session route extraction parity', () => { const contentBindings = CONTENT_COMPONENT_NAMES.flatMap( (name) => readHookFacts(name, definitions).bindings ) - expect(main.hooks).toHaveLength(266) + expect(main.hooks).toHaveLength(269) expect(hash(main.hooks)).toBe(HEAD_MAIN_HOOK_SHA256) expect(hash(main.bindings)).toBe(HEAD_HOOK_BINDING_SHA256) expect(main.callbacks).toHaveLength(77) expect(hash(main.callbacks)).toBe(HEAD_CALLBACK_IDENTITY_SHA256) expect(hash(main.callbackBodies)).toBe(HEAD_CALLBACK_BODY_SHA256) - expect(main.effects).toHaveLength(24) + expect(main.effects).toHaveLength(26) expect(hash(main.effects)).toBe(HEAD_EFFECT_SHA256) expect(contentBindings).toHaveLength(14) expect(hash(contentBindings)).toBe(HEAD_CONTENT_HOOK_SHA256) @@ -517,14 +518,14 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(546) + expect(strings).toHaveLength(548) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) - expect(jsx.host).toHaveLength(124) + expect(jsx.host).toHaveLength(127) expect(hash(jsx.host)).toBe(HEAD_HOST_JSX_SHA256) - expect(jsx.leaf).toHaveLength(61) + expect(jsx.leaf).toHaveLength(60) expect(hash(jsx.leaf)).toBe(HEAD_LEAF_JSX_SHA256) - expect(jsx.styleReferences).toHaveLength(172) + expect(jsx.styleReferences).toHaveLength(175) expect(hash(jsx.styleReferences)).toBe(HEAD_STYLE_REFERENCE_SHA256) }) }) diff --git a/mobile/src/session/mobile-session-route-source-family.test-support.ts b/mobile/src/session/mobile-session-route-source-family.test-support.ts index 41f2d8b9c2f..acb2bef34a8 100644 --- a/mobile/src/session/mobile-session-route-source-family.test-support.ts +++ b/mobile/src/session/mobile-session-route-source-family.test-support.ts @@ -33,6 +33,7 @@ export const MOBILE_SESSION_ROUTE_SOURCE_FILES = [ './use-mobile-session-content-create-actions.ts', './use-mobile-session-close-actions.ts', './use-mobile-session-bulk-close.ts', + './use-mobile-session-tab-strip-cache.ts', './use-mobile-session-presentation.ts', './use-mobile-session-panel-route-actions.tsx', './MobileSessionMarkdownReader.tsx', diff --git a/mobile/src/session/mobile-session-tab-strip-entries.ts b/mobile/src/session/mobile-session-tab-strip-entries.ts new file mode 100644 index 00000000000..5f4569403b0 --- /dev/null +++ b/mobile/src/session/mobile-session-tab-strip-entries.ts @@ -0,0 +1,116 @@ +import { TUI_AGENT_DISPLAY_NAMES } from '../../../src/shared/tui-agent-display-names' +import type { MobileSessionTab, MobileSessionTabType } from './mobile-session-route-types' +import { + getMobileSessionTabTitle, + resolveMobileTerminalTabAgentId +} from './mobile-terminal-tab-agent' + +/** + * The only session-tab fields the tab strip draws. Everything else the live tab carries (unsent + * launch drafts, absolute file paths, browser URLs, agent session ids) stays on the wire. + */ +export type MobileSessionTabStripEntry = { + id: string + type: MobileSessionTabType + title: string + agentId: string | null +} + +export type MobileSessionTabStripPreview = { + tabs: readonly MobileSessionTabStripEntry[] + activeTabId: string | null +} + +export type MobileSessionTabStripRow = { + entry: MobileSessionTabStripEntry + isActive: boolean + /** null on a preview row: switching to that tab needs a live connection. */ + tab: MobileSessionTab | null +} + +export function toMobileSessionTabStripEntry(tab: MobileSessionTab): MobileSessionTabStripEntry { + return { + id: tab.id, + type: tab.type, + title: getMobileSessionTabTitle(tab), + agentId: + tab.type === 'agent-session' + ? tab.agent + : tab.type === 'terminal' + ? resolveMobileTerminalTabAgentId(tab) + : null + } +} + +/** + * Every tab type the strip knows how to draw. A stored entry naming anything else is dropped + * rather than trusted, so a type added later fails closed: its rows go missing from the preview + * instead of carrying an unreviewed title into storage. + */ +const drawableTabTypes = new Set([ + 'terminal', + 'markdown', + 'file', + 'browser', + 'agent-session' +] satisfies readonly MobileSessionTabType[]) + +export function isDrawableTabStripType(type: string): type is MobileSessionTabType { + return drawableTabTypes.has(type) +} + +const agentDisplayNames: Readonly> = TUI_AGENT_DISPLAY_NAMES + +/** + * The title a strip entry may be written to disk under. + * + * A terminal's title is whatever the shell last set, which is routinely the command line — + * `psql postgres://user:password@host/db`, `curl -H "Authorization: Bearer ..."`. None of that + * belongs in plaintext storage, and a browser tab's page title is no better. Both collapse to a + * fixed label, so what survives is the shape of the strip, not its contents. A resolved agent + * still names itself, because that lookup is a closed enum: an unrecognised id yields the + * generic label rather than passing text through. + */ +export function getPersistableTabStripTitle( + entry: Pick +): string { + if (entry.type === 'terminal') { + const agentLabel = entry.agentId === null ? undefined : agentDisplayNames[entry.agentId] + return agentLabel ?? 'Terminal' + } + if (entry.type === 'browser') { + return 'Browser' + } + return entry.title +} + +export function toMobileSessionTabStripPreview( + tabs: readonly MobileSessionTab[], + activeTabId: string | null +): MobileSessionTabStripPreview { + return { tabs: tabs.map(toMobileSessionTabStripEntry), activeTabId } +} + +/** + * Rows for the header strip. Live tabs always win; the preview only fills a strip that has no + * live rows yet, and its ids are the live ids, so the swap reuses the same React keys. + */ +export function getMobileSessionTabStripRows(args: { + liveTabs: readonly MobileSessionTab[] + activeSessionTabId: string | null + preview: MobileSessionTabStripPreview | null +}): MobileSessionTabStripRow[] { + const { liveTabs, activeSessionTabId, preview } = args + if (liveTabs.length > 0 || !preview) { + return liveTabs.map((tab) => ({ + entry: toMobileSessionTabStripEntry(tab), + isActive: tab.id === activeSessionTabId, + tab + })) + } + return preview.tabs.map((entry) => ({ + entry, + isActive: entry.id === preview.activeTabId, + tab: null + })) +} diff --git a/mobile/src/session/use-mobile-session-controller.ts b/mobile/src/session/use-mobile-session-controller.ts index f188b30b17a..b2427f806c2 100644 --- a/mobile/src/session/use-mobile-session-controller.ts +++ b/mobile/src/session/use-mobile-session-controller.ts @@ -27,6 +27,7 @@ import { useMobileSessionTerminalCreateActions } from './use-mobile-session-term import { useMobileSessionContentCreateActions } from './use-mobile-session-content-create-actions' import { useMobileSessionCloseActions } from './use-mobile-session-close-actions' import { useMobileSessionBulkClose } from './use-mobile-session-bulk-close' +import { useMobileSessionTabStripCache } from './use-mobile-session-tab-strip-cache' import { useMobileSessionPresentation } from './use-mobile-session-presentation' import { useMobileSessionPanelRouteActions } from './use-mobile-session-panel-route-actions' @@ -113,7 +114,8 @@ export function useMobileSessionController() { useMobileSessionCloseActions(contentCreateActions) ) const bulkClose = Object.assign(closeActions, useMobileSessionBulkClose(closeActions)) - const presentation = Object.assign(bulkClose, useMobileSessionPresentation(bulkClose)) + const tabStripCache = Object.assign(bulkClose, useMobileSessionTabStripCache(bulkClose)) + const presentation = Object.assign(tabStripCache, useMobileSessionPresentation(tabStripCache)) const panelRouteActions = Object.assign( presentation, useMobileSessionPanelRouteActions(presentation) diff --git a/mobile/src/session/use-mobile-session-presentation.ts b/mobile/src/session/use-mobile-session-presentation.ts index 2565f729940..e43b59cabef 100644 --- a/mobile/src/session/use-mobile-session-presentation.ts +++ b/mobile/src/session/use-mobile-session-presentation.ts @@ -3,9 +3,11 @@ import { classifyConnection, verdictDisplayLabel } from '../transport/connection import { computeActiveTerminalKeyboardLift } from '../terminal/terminal-keyboard-avoidance-lift' import { useInitialSessionTerminalAutoCreate } from './use-initial-session-terminal-autocreate' import { MOBILE_SESSION_STATUS_LABELS } from './mobile-session-route-helpers' -import type { MobileSessionBulkCloseModel } from './use-mobile-session-bulk-close' +import { selectMobileSessionReconnectViewState } from './mobile-session-reconnect-view-state' +import { getMobileSessionTabStripRows } from './mobile-session-tab-strip-entries' +import type { MobileSessionTabStripCacheModel } from './use-mobile-session-tab-strip-cache' -export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) { +export function useMobileSessionPresentation(scope: MobileSessionTabStripCacheModel) { const { created, worktreeId, @@ -24,6 +26,8 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) terminalKeyboardMetrics, toastOpacityRef, hostEndpoint, + activeSessionTabId, + cachedTabStrip, initialSessionAutoCreateRef, terminalFrameHeightRef, handleCreateTerminal, @@ -58,6 +62,23 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) const showConnectionRetry = connectionVerdict.kind === 'warning' || connectionVerdict.kind === 'unreachable' + // Why: a reconnect to a workspace this phone has already drawn should re-draw it, not blank + // the screen while the RPCs land. See mobile-session-reconnect-view-state. + const reconnectViewState = selectMobileSessionReconnectViewState({ + connState, + verdictKind: connectionVerdict.kind, + terminalsLoaded, + liveTabCount: visibleTabs.length, + activeHandle, + cachedPreview: cachedTabStrip + }) + const tabStripRows = getMobileSessionTabStripRows({ + liveTabs: visibleTabs, + activeSessionTabId, + preview: + reconnectViewState.kind === 'reconnecting-with-cache' ? reconnectViewState.preview : null + }) + const terminalSummary = connState === 'connected' ? showLoadingState @@ -88,6 +109,8 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) return { showLoadingState, showEmptyState, + reconnectViewState, + tabStripRows, connectionVerdict, showConnectionRetry, terminalSummary, @@ -97,5 +120,5 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) } } -export type MobileSessionPresentationModel = MobileSessionBulkCloseModel & +export type MobileSessionPresentationModel = MobileSessionTabStripCacheModel & ReturnType diff --git a/mobile/src/session/use-mobile-session-tab-strip-cache.ts b/mobile/src/session/use-mobile-session-tab-strip-cache.ts new file mode 100644 index 00000000000..d0207afd83c --- /dev/null +++ b/mobile/src/session/use-mobile-session-tab-strip-cache.ts @@ -0,0 +1,66 @@ +import { useEffect, useState } from 'react' +import { + getSessionTabStripCacheKey, + loadCachedSessionTabStrip, + readCachedSessionTabStrip, + saveCachedSessionTabStrip +} from '../cache/session-tab-strip-cache' +import { + toMobileSessionTabStripPreview, + type MobileSessionTabStripPreview +} from './mobile-session-tab-strip-entries' +import type { MobileSessionBulkCloseModel } from './use-mobile-session-bulk-close' + +/** + * Keeps the last drawn tab strip for this workspace on the device, so a reconnect has something + * to render before the first snapshot lands. See mobile-session-reconnect-view-state. + */ +export function useMobileSessionTabStripCache(scope: MobileSessionBulkCloseModel) { + const { hostId, worktreeId, connState, terminalsLoaded } = scope + const { visibleTabs, activeSessionTabId, activeHandle } = scope + const cacheKey = getSessionTabStripCacheKey(hostId, worktreeId) + // Why: state settles a commit behind the key it was read for, so carry the key with it — + // otherwise the first render after a workspace switch draws the previous workspace's strip. + const [loaded, setLoaded] = useState<{ + key: string | null + preview: MobileSessionTabStripPreview | null + }>(() => ({ key: cacheKey, preview: readCachedSessionTabStrip(cacheKey) })) + + useEffect(() => { + // Synchronous first, so an in-session revisit never blinks through the uncached branch. + setLoaded({ key: cacheKey, preview: readCachedSessionTabStrip(cacheKey) }) + let disposed = false + void loadCachedSessionTabStrip(cacheKey).then((preview) => { + if (!disposed) { + setLoaded({ key: cacheKey, preview }) + } + }) + return () => { + disposed = true + } + }, [cacheKey]) + const cachedTabStrip = loaded.key === cacheKey ? loaded.preview : null + + // Only a host-confirmed strip is worth persisting, and an emptied workspace has to be written + // too — skipping it would leave yesterday's tabs to be drawn over a session that no longer has + // them. The one reading we do not trust is a live terminal with no tab record behind it, which + // is the same case the empty state refuses to claim (use-mobile-session-presentation). + // react-doctor-disable-next-line react-doctor/effect-needs-cleanup + useEffect(() => { + if (connState !== 'connected' || !terminalsLoaded) { + return + } + if (visibleTabs.length === 0 && activeHandle !== null) { + return + } + saveCachedSessionTabStrip( + cacheKey, + toMobileSessionTabStripPreview(visibleTabs, activeSessionTabId) + ) + }, [activeHandle, activeSessionTabId, cacheKey, connState, terminalsLoaded, visibleTabs]) + + return { cachedTabStrip } +} + +export type MobileSessionTabStripCacheModel = MobileSessionBulkCloseModel & + ReturnType diff --git a/mobile/src/transport/host-removal-lifecycle.test.ts b/mobile/src/transport/host-removal-lifecycle.test.ts index 6c96ef1c446..3dca9514362 100644 --- a/mobile/src/transport/host-removal-lifecycle.test.ts +++ b/mobile/src/transport/host-removal-lifecycle.test.ts @@ -17,6 +17,12 @@ vi.mock('./host-store', () => ({ })) import { removeHostAndCloseClient } from './host-removal-lifecycle' +import { + getSessionTabStripCacheKey, + readCachedSessionTabStrip, + resetSessionTabStripCacheForTests, + saveCachedSessionTabStrip +} from '../cache/session-tab-strip-cache' import { getHostNotificationSession, resetHostNotificationSessionsForTests @@ -27,6 +33,7 @@ describe('host removal lifecycle', () => { removeHostMock.mockReset() asyncStorage.removeItem.mockClear() resetHostNotificationSessionsForTests() + resetSessionTabStripCacheForTests() }) it('closes the client only after metadata removal commits', async () => { @@ -88,4 +95,25 @@ describe('host removal lifecycle', () => { expect(asyncStorage.removeItem).toHaveBeenCalledWith('orca:mobileNotificationsWatermark:host-1') }) + + it('drops the removed host cached tab strip and keeps every other host', async () => { + // Why: the strip is plaintext and nothing else in the app ever expires an entry, so a + // forgotten host would keep its tab titles on disk and get them rewritten by the next + // save for any surviving host. + removeHostMock.mockResolvedValue(undefined) + const removed = getSessionTabStripCacheKey('host-1', 'wt-1') + const kept = getSessionTabStripCacheKey('host-2', 'wt-1') + const strip = { + tabs: [{ id: 'tab-1', type: 'terminal' as const, title: 'Terminal', agentId: null }], + activeTabId: 'tab-1' + } + saveCachedSessionTabStrip(removed, strip) + saveCachedSessionTabStrip(kept, strip) + + await removeHostAndCloseClient('host-1', vi.fn()) + // Fire-and-forget, like clearWatermark above; let its microtasks land. + await vi.waitFor(() => expect(readCachedSessionTabStrip(removed)).toBeNull()) + + expect(readCachedSessionTabStrip(kept)?.tabs).toHaveLength(1) + }) }) diff --git a/mobile/src/transport/host-removal-lifecycle.ts b/mobile/src/transport/host-removal-lifecycle.ts index cd0a09cb67e..3883cfb9140 100644 --- a/mobile/src/transport/host-removal-lifecycle.ts +++ b/mobile/src/transport/host-removal-lifecycle.ts @@ -1,3 +1,4 @@ +import { deleteCachedSessionTabStripForHost } from '../cache/session-tab-strip-cache' import { clearWatermark, forgetHostNotificationSession @@ -17,4 +18,7 @@ export async function removeHostAndCloseClient( // re-pair of the same host would inherit a watermark for a counter it never saw. forgetHostNotificationSession(hostId) void clearWatermark(hostId) + // Why: the cached tab strip is plaintext and host-scoped, so forgetting the host has to drop + // it here too — nothing else in the app ever expires an entry. + void deleteCachedSessionTabStripForHost(hostId) } diff --git a/mobile/src/transport/unpaired-host-credential-deletion.test.ts b/mobile/src/transport/unpaired-host-credential-deletion.test.ts new file mode 100644 index 00000000000..cd6ebe4a2fd --- /dev/null +++ b/mobile/src/transport/unpaired-host-credential-deletion.test.ts @@ -0,0 +1,82 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const asyncStorage = vi.hoisted(() => ({ + getItem: vi.fn(async () => null), + setItem: vi.fn(async () => undefined), + removeItem: vi.fn(async () => undefined) +})) +const deletions = vi.hoisted(() => ({ + deviceToken: vi.fn(async () => undefined), + credentialBundle: vi.fn(async () => undefined), + directUpgradeJournal: vi.fn(async () => undefined), + clearWriteRevision: vi.fn() +})) + +vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) +vi.mock('./host-device-token-store', () => ({ deleteHostDeviceToken: deletions.deviceToken })) +vi.mock('./mobile-relay-credential-bundle', () => ({ + deleteMobileRelayCredentialBundle: deletions.credentialBundle +})) +vi.mock('./mobile-relay-direct-upgrade-journal', () => ({ + deleteMobileRelayDirectUpgradeJournal: deletions.directUpgradeJournal +})) +vi.mock('./host-credential-write-revision', () => ({ + clearHostCredentialWriteRevision: deletions.clearWriteRevision, + getHostCredentialWriteRevision: () => 0 +})) + +import { createUnpairedHostCredentialDeletion } from './unpaired-host-credential-deletion' +import { + getSessionTabStripCacheKey, + readCachedSessionTabStrip, + resetSessionTabStripCacheForTests, + saveCachedSessionTabStrip +} from '../cache/session-tab-strip-cache' + +const strip = { + tabs: [{ id: 'tab-1', type: 'terminal' as const, title: 'Terminal', agentId: null }], + activeTabId: 'tab-1' +} + +function createDeletion(storedHostIds: string[] = []) { + return createUnpairedHostCredentialDeletion({ + waitForHostMutations: async () => undefined, + hasStoredHost: async (hostId) => storedHostIds.includes(hostId), + onDeleted: vi.fn() + }) +} + +beforeEach(() => { + asyncStorage.getItem.mockClear() + asyncStorage.setItem.mockClear() + for (const mock of Object.values(deletions)) { + mock.mockClear() + } + resetSessionTabStripCacheForTests() +}) + +describe('unpaired host credential deletion', () => { + it('takes the cached tab strip with the credentials, leaving other hosts alone', async () => { + // Why: the strip is not a credential, but it is host-scoped plaintext written from the + // session screen. Without this sweep it outlives the pairing that produced it. + const unpaired = getSessionTabStripCacheKey('host-1', 'wt-1') + const other = getSessionTabStripCacheKey('host-2', 'wt-1') + saveCachedSessionTabStrip(unpaired, strip) + saveCachedSessionTabStrip(other, strip) + + await createDeletion()('host-1', 0) + + expect(readCachedSessionTabStrip(unpaired)).toBeNull() + expect(readCachedSessionTabStrip(other)?.tabs).toHaveLength(1) + }) + + it('leaves the strip alone when the host turned out to still be paired', async () => { + const stillPaired = getSessionTabStripCacheKey('host-1', 'wt-1') + saveCachedSessionTabStrip(stillPaired, strip) + + await createDeletion(['host-1'])('host-1', 0) + + expect(readCachedSessionTabStrip(stillPaired)?.tabs).toHaveLength(1) + expect(deletions.deviceToken).not.toHaveBeenCalled() + }) +}) diff --git a/mobile/src/transport/unpaired-host-credential-deletion.ts b/mobile/src/transport/unpaired-host-credential-deletion.ts index cc9c27e49ad..06220824b78 100644 --- a/mobile/src/transport/unpaired-host-credential-deletion.ts +++ b/mobile/src/transport/unpaired-host-credential-deletion.ts @@ -1,3 +1,4 @@ +import { deleteCachedSessionTabStripForHost } from '../cache/session-tab-strip-cache' import { deleteHostDeviceToken } from './host-device-token-store' import { clearHostCredentialWriteRevision, @@ -52,6 +53,13 @@ export function createUnpairedHostCredentialDeletion(dependencies: DeletionDepen return } assertWriteRevisionUnchanged(hostId, writeRevision) + // The cached tab strip is not a credential, but it is host-scoped plaintext that outlives + // the pairing unless this sweep takes it too. + await deleteCachedSessionTabStripForHost(hostId) + if (await shouldSkip(hostId, writeRevision)) { + return + } + assertWriteRevisionUnchanged(hostId, writeRevision) clearHostCredentialWriteRevision(hostId) dependencies.onDeleted(hostId) } From e068947d4c910b6aa8d8635588e176976667bad6 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 04:51:48 -0400 Subject: [PATCH 09/37] feat(relay): alert on far-cell placement and skewed region hints (#19253) * feat(relay): alert on far-cell placement and skewed region hints US desktops were homed on asia-east2 cells for weeks in 2026-08 with every existing relay alert green. Roughly 226 of 332 hosts on those cells were non-APAC, and a phone connect took ~10 s there against ~0.6 s in region, but nothing in Cloud Monitoring could see distance: the connection, queue, heap, and SQL bars all measure a cell's own health, which was fine. Three policies close that gap. Two read distance per cell, from the accept and control-RTT timing added in the parent commit: phone-accept p95 above 2 s, and control ping p50 above 150 ms. The third reads the cause fleet-wide, as the asia-east2 share of the region hints desktops send the director, so a mis-picking client probe is visible before it lands anyone on a far cell. All three are MQL rather than the metric filters the other relay policies use. Every runtime metric is a DELTA DISTRIBUTION, and a filter condition can only align one with a percentile; each alert needs the sum of the extracted values as a volume floor so a sparse window cannot page. None of these metrics exists in the project yet, so what was checked against production is the query shape: the same MQL run over existing metrics of the same kind. The skew denominator needs one log-based metric per hint key, so `requestedRegionsDelta` now has one per relay region plus the unhinted bucket. Those ride the existing snapshot metric family, which adds map entries without touching the live metrics. A ratchet test pins the key list to relay-contract's RELAY_REGIONS: a region added there without a metric would shrink the denominator, so the test fails rather than letting the share quietly inflate. * fix(relay): compare hinted regions against placed ones, not a fixed share Review found the skew alert inverted at both ends. A fixed 40% bar on the asia-east2 share of region hints was silent through the exact broken state it was written for, and would page forever once the desktop probe is fixed and the genuine APAC share rises past it. An absolute share cannot separate those because it has no reference point. The hint share now has one: the share of assignments the director actually placed in that region during the same hour. Measured over twelve hours on 2026-09-07, while the probe was still mis-picking, asia-east2 was 33.8% of 33,800 hinted requests and 7.9% of 45,364 assignments. That is a 4.27x divergence and a 25.9-point gap, so the alert fires above 2x and 15 points, inside the broken state and outside a healthy one. Both bars must hold: the ratio alone blows up on tiny placement counts, the gap alone misses a proportionally large skew at low volume. The reviewer proposed either bar alone; requiring both keeps each one meaningful and still clears today's numbers with room. `unhinted` requests leave the denominator. They were 27% of all requests, so a client that always sends a hint would move the number from 21.9% to 35.0% with no behaviour change at all. The comparison needs per-region placement counters, so `selectedRegionsDelta` gets log-based metrics alongside the requested ones. Rather than extract four hyphenated map keys through quoted field paths, which nothing in the project does and which cannot be checked without applying, the relay now also publishes flat `requestedRegionDelta` and `selectedRegionDelta` fields next to the untouched maps. They are emitted as zeros in every interval, so no series can drop out of the alert's inner join in an hour with no asia placements, which is exactly the hour the skew is worst. Additive only: metricVersion is unchanged, the maps still carry anything outside the catalog, and the emitter's leak guard still passes. Two corrections to what the previous commit claimed. None of these metrics exist in the project yet, so the code, the doc and this message now say what was actually checked against production: the query shapes, run over existing metrics of the same kind. And the control-RTT policy records that EU desktops on us-central1 sit at 100-130 ms, so a European-heavy cell can approach the 150 ms bar while correctly homed. The skew alert will stay lit after a client fix until the backlog is rehomed. Sticky assignment never re-consults the hint, so a desktop already on an asia cell keeps landing there whatever it now asks for. The policy description and the doc both say so, so nobody reads a slow clear as a failed fix. * fix(relay): cross-multiply the skew bars so a zero placement share still fires `hint_share / placement_share` is undefined in the hour that matters most. When the director placed nobody in the region, MQL returns no rows for either 0/0 or x/0, so the series disappears before the gap and volume clauses run and the alert stays silent. That hour is not hypothetical: it is every desktop asking for a region while the director puts nobody there, which is what a drained, fenced, or full region looks like, and it is the most extreme skew the alert can see. The condition is now cross-multiplied, `hint_share > 2 * placement_share`, which is well defined at zero. Both forms were run read-only against production surrogates chosen so the placement denominator is exactly zero: the ratio form returned no rows, the cross-multiplied form returned the series with the condition true on every point. A second surrogate pass with a tiny hint share returned the series with the condition false, so the gap clause still suppresses the healthy shape rather than the query silently matching everything. The flat field names are no longer derived on either side. Terraform title cased each dash-separated part and the emitter upper cased each part's first character, so the ratchet had to pin two source expressions by regex, which a reformat would break and which never compared the actual rendered names. Both sides now declare a literal map, relay-contract's RELAY_REGION_METRIC_SEGMENTS and Terraform's relay_region_field_segments, and the test compares the two declarations against each other and against the expected names. `satisfies Record` makes a region added without a segment a compile error rather than a silent gap in the alert's denominators. Both ratchets were checked by mutation: a wrong Terraform segment, a contract region with no Terraform entry, and a revert to the ratio form each fail the node test, and the new region fails the contract build. --- .../relay/src/relay-observability.test.ts | 22 +- cloud/apps/relay/src/relay-observability.ts | 20 +- .../terraform-root-partition/families.json | 3 + .../relay-region-hint-metrics.test.mjs | 84 ++++++++ cloud/docs/relay-incident-monitor.md | 73 +++++++ cloud/infra/terraform/relay-observability.tf | 200 +++++++++++++++++- cloud/package.json | 2 +- .../relay-contract/src/relay-regions.ts | 9 + 8 files changed, 408 insertions(+), 5 deletions(-) create mode 100644 cloud/dev/scripts/relay-region-hint-metrics.test.mjs diff --git a/cloud/apps/relay/src/relay-observability.test.ts b/cloud/apps/relay/src/relay-observability.test.ts index 249b7e0915c..22802b7f8aa 100644 --- a/cloud/apps/relay/src/relay-observability.test.ts +++ b/cloud/apps/relay/src/relay-observability.test.ts @@ -1,3 +1,4 @@ +import { RELAY_REGION_METRIC_SEGMENTS, RELAY_REGIONS } from '@orca-cloud/relay-contract' import { describe, expect, it, vi } from 'vitest' import type { RelayDatabase } from './database.js' import { observeRelayDatabase } from './observed-relay-database.js' @@ -112,14 +113,31 @@ describe('relay observability', () => { requestedRegionsDelta: { 'asia-east2': 1, unhinted: 1 }, selectedRegionsDelta: { 'us-central1': 1 }, regionFallbacksDelta: { 'asia-east2': 1 }, - unavailableRegionsDelta: { 'asia-east2': 1 } + unavailableRegionsDelta: { 'asia-east2': 1 }, + // Flat per-region siblings the log-based metrics extract; `unhinted` stays map-only. + requestedRegionUsCentral1Delta: 0, + requestedRegionAsiaEast2Delta: 1, + selectedRegionUsCentral1Delta: 1, + selectedRegionAsiaEast2Delta: 0 }) expect(entries[1]).toMatchObject({ requestedRegionsDelta: {}, selectedRegionsDelta: {}, regionFallbacksDelta: {}, - unavailableRegionsDelta: {} + unavailableRegionsDelta: {}, + // Zeros keep publishing so an idle window cannot drop a series out of the skew join. + requestedRegionUsCentral1Delta: 0, + requestedRegionAsiaEast2Delta: 0, + selectedRegionUsCentral1Delta: 0, + selectedRegionAsiaEast2Delta: 0 }) + // A region added to the contract has to reach the flat keys, or the skew alert's + // denominator silently misses it. + for (const segment of Object.values(RELAY_REGION_METRIC_SEGMENTS)) { + expect(entries[0]).toHaveProperty(`requestedRegion${segment}Delta`) + expect(entries[0]).toHaveProperty(`selectedRegion${segment}Delta`) + } + expect(Object.keys(RELAY_REGION_METRIC_SEGMENTS).sort()).toEqual([...RELAY_REGIONS].sort()) }) it('emits bounded aggregate runtime signals without identities or credentials', () => { diff --git a/cloud/apps/relay/src/relay-observability.ts b/cloud/apps/relay/src/relay-observability.ts index c96ef36289c..9f937afdb6e 100644 --- a/cloud/apps/relay/src/relay-observability.ts +++ b/cloud/apps/relay/src/relay-observability.ts @@ -1,5 +1,5 @@ import { monitorEventLoopDelay, performance } from 'node:perf_hooks' -import type { RelayRegion } from '@orca-cloud/relay-contract' +import { RELAY_REGION_METRIC_SEGMENTS, type RelayRegion } from '@orca-cloud/relay-contract' import type { ControlRenewalOutcome } from './assignment-store.js' import type { CellInventoryHoldCounts } from './cell-inventory-hold-samples.js' import type { PostgresPoolPressureCounts } from './postgres-pool-pressure.js' @@ -363,6 +363,8 @@ export class RelayObservability implements RelayRuntimeObserver { placementRejectionsByReasonDelta: deltas.placementRejectionsByReason, requestedRegionsDelta: deltas.requestedRegions, selectedRegionsDelta: deltas.selectedRegions, + ...regionCounterFields('requestedRegion', deltas.requestedRegions), + ...regionCounterFields('selectedRegion', deltas.selectedRegions), regionFallbacksDelta: deltas.regionFallbacks, unavailableRegionsDelta: deltas.unavailableRegions, controlClosesByCodeDelta: deltas.controlClosesByCode, @@ -413,6 +415,22 @@ export class RelayObservability implements RelayRuntimeObserver { } } +// Flat siblings of the nested region maps, always emitted for every region including zeros. +// A log-based metric cannot reach `requestedRegionsDelta."asia-east2"` without a quoted field +// path, and an absent key would drop a series out of the inner join the region-skew alert does. +// The maps stay authoritative and keep carrying anything outside the catalog, such as `unhinted`. +function regionCounterFields( + prefix: 'requestedRegion' | 'selectedRegion', + counts: Record +): Record { + return Object.fromEntries( + Object.entries(RELAY_REGION_METRIC_SEGMENTS).map(([region, segment]) => [ + `${prefix}${segment}Delta`, + counts[region] ?? 0 + ]) + ) +} + function increment(counts: Record, key: string): void { counts[key] = (counts[key] ?? 0) + 1 } diff --git a/cloud/dev/fixtures/terraform-root-partition/families.json b/cloud/dev/fixtures/terraform-root-partition/families.json index dfe100fd2dd..dd6f6944322 100644 --- a/cloud/dev/fixtures/terraform-root-partition/families.json +++ b/cloud/dev/fixtures/terraform-root-partition/families.json @@ -133,14 +133,17 @@ "google_logging_metric.relay_snapshot", "google_monitoring_alert_policy.relay_assignment_5xx", "google_monitoring_alert_policy.relay_assignment_edge_429", + "google_monitoring_alert_policy.relay_cell_control_rtt", "google_monitoring_alert_policy.relay_cell_process_exit", "google_monitoring_alert_policy.relay_cloud_nat_port_drops", "google_monitoring_alert_policy.relay_cloud_sql_backends", "google_monitoring_alert_policy.relay_cloud_sql_checkpoint_loop", "google_monitoring_alert_policy.relay_cloud_sql_disk", "google_monitoring_alert_policy.relay_custom", + "google_monitoring_alert_policy.relay_far_cell_accept_latency", "google_monitoring_alert_policy.relay_gce_connection_headroom", "google_monitoring_alert_policy.relay_postgres_retry_exhausted", + "google_monitoring_alert_policy.relay_region_hint_skew", "google_monitoring_dashboard.relay_incident", "google_project_iam_custom_role.github_production_relay_capacity_mutation", "google_project_iam_custom_role.github_relay_asia_topology_mutation", diff --git a/cloud/dev/scripts/relay-region-hint-metrics.test.mjs b/cloud/dev/scripts/relay-region-hint-metrics.test.mjs new file mode 100644 index 00000000000..8f331efce18 --- /dev/null +++ b/cloud/dev/scripts/relay-region-hint-metrics.test.mjs @@ -0,0 +1,84 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' +import { fileURLToPath } from 'node:url' + +// Why: the region-skew alert compares asia-east2's share of assignment hints against its share of +// actual placements. Both shares are sums over one log-based metric per region, and the region +// list is written out by hand in Terraform. A region added to the contract without matching +// metrics would silently drop out of both denominators and move the ratio the alert fires on. + +const read = (relative) => readFileSync(fileURLToPath(new URL(relative, import.meta.url)), 'utf8') +const collapse = (text) => text.replaceAll(/\s+/g, ' ') + +const contractRegions = (() => { + const source = read('../../packages/relay-contract/src/relay-regions.ts') + const literal = /export const RELAY_REGIONS = \[([^\]]*)\]/.exec(source) + assert.ok(literal, 'RELAY_REGIONS literal not found in relay-regions.ts') + return [...literal[1].matchAll(/'([^']+)'/g)].map((match) => match[1]) +})() + +const terraform = read('../../infra/terraform/relay-observability.tf') + +const terraformRegions = (() => { + const literal = /relay_region_keys = \[([^\]]*)\]/.exec(terraform) + assert.ok(literal, 'relay_region_keys not found in relay-observability.tf') + return [...literal[1].matchAll(/"([^"]+)"/g)].map((match) => match[1]) +})() + +// Both sides now spell the field-name segments out, so the test compares the two declared maps +// rather than two source expressions. Reformatting either file cannot break this, and a literal +// expected value below still catches an identical wrong edit made to both. +const declaredSegments = (source, open, close) => { + const body = source.slice(source.indexOf(open) + open.length, source.indexOf(close, source.indexOf(open))) + return Object.fromEntries( + [...body.matchAll(/'?"?([a-z0-9-]+)'?"?\s*[:=]\s*'?"?([A-Za-z0-9]+)'?"?/g)].map((match) => [ + match[1], + match[2] + ]) + ) +} + +const terraformSegments = declaredSegments(terraform, 'relay_region_field_segments = {', '}') +const contractSegments = declaredSegments( + read('../../packages/relay-contract/src/relay-regions.ts'), + 'RELAY_REGION_METRIC_SEGMENTS = {', + '}' +) + +test('terraform covers exactly the regions the contract can hint or select', () => { + assert.deepEqual([...terraformRegions].sort(), [...contractRegions].sort()) +}) + +test('terraform and the contract declare the same flat field segments', () => { + assert.deepEqual(terraformSegments, contractSegments) + // Pinned literally so the same wrong edit applied to both sides still fails. + assert.deepEqual(terraformSegments, { 'us-central1': 'UsCentral1', 'asia-east2': 'AsiaEast2' }) + assert.deepEqual(Object.keys(terraformSegments).sort(), [...contractRegions].sort()) +}) + +test('the skew query compares a catalogued region against itself', () => { + const columns = terraformRegions.map((region) => region.replaceAll('-', '_')) + const hint = /hint_share: req_([a-z0-9_]+) \//.exec(terraform) + const placement = /placement_share: sel_([a-z0-9_]+) \//.exec(terraform) + assert.ok(hint && placement, 'skew query share columns not found') + assert.equal(hint[1], placement[1], 'the two shares must be about the same region') + assert.ok(columns.includes(hint[1]), `${hint[1]} is not one of ${columns.join(', ')}`) +}) + +test('the skew condition never divides by the placement share', () => { + // A zero-placement hour is the worst skew there is; MQL drops the row on x/0, so the ratio form + // silences exactly the case the alert exists for. + assert.ok( + !/hint_share \/ placement_share/.test(terraform), + 'cross-multiply instead: hint_share > 2 * placement_share' + ) + assert.match(collapse(terraform), /condition hint_share > 2 \* placement_share/) +}) + +test('the unhinted bucket stays out of the skew denominators', () => { + assert.ok( + !terraformRegions.includes('unhinted'), + 'unhinted requests are a client-side choice, not a region; including them moves the share' + ) +}) diff --git a/cloud/docs/relay-incident-monitor.md b/cloud/docs/relay-incident-monitor.md index 8a8dfda1495..696efb85296 100644 --- a/cloud/docs/relay-incident-monitor.md +++ b/cloud/docs/relay-incident-monitor.md @@ -121,6 +121,79 @@ durably marked consumed before mutation and cannot authorize another run. Expected enabled cells must also have a powered runtime, healthy and ready endpoints, fresh heartbeats, and matching live admission. +## Region placement alert policies + +Cloud Monitoring alert policies, not monitor freeze bars: these page from +`cloud/infra/terraform/relay-observability.tf` on the shared relay channel in +`relay_alert_notification_channels`, and they do not gate any workflow. All +three exist because US desktops sat on asia-east2 cells for weeks in 2026-08 +with every existing bar green. + +| Alert policy | Condition | +| --- | ---: | +| Orca Relay: far-cell phone accept latency | per cell, median 30-second `clientAcceptTotalMsP95` over 15 minutes above 2,000 ms with at least 20 completed accepts | +| Orca Relay: cell control round trip | per cell, median `controlRttMsP50` over one hour above 150 ms with at least 500 samples | +| Orca Relay: region hint skew | fleet-wide, asia-east2 share of hinted requests over one hour more than 2x and more than 15 points above its share of actual placements, with at least 500 hinted requests | + +Threshold basis: + +- Accept latency. An in-region phone accept completes in 0.3-0.6 s and a + cross-Pacific one in 5-10 s, so 2,000 ms sits outside in-region noise and + well under the far-cell floor. The 20-accept minimum keeps one slow accept + on a quiet cell off the pager. The p95 is the published value, so the + window aggregate is its median, not its max. +- Control round trip. In-region is tens of milliseconds; a US desktop on an + asia-east2 cell is 200 ms or more. Only the p50 is used. The desktop echoes + the pong on its main thread, so the published p95 and max track renderer + stalls rather than distance. 500 samples per hour is about two + continuously connected hosts at the 15-second control ping. Tuning risk: EU + desktops on us-central1 sit at 100-130 ms, so a cell whose population is + mostly European can approach the bar while correctly homed. Check where the + hosts are before reading a first breach as mis-homing. +- Region hint skew. This compares two shares of the same hour rather than + testing one absolute share, because an absolute bar is wrong at both ends. + Measured over twelve hours on 2026-09-07, while the desktop region probe + was still mis-picking: asia-east2 was 33.8% of the 33,800 hinted requests + and only 7.9% of the 45,364 assignments, a divergence of 4.27x and a gap of + 25.9 points. A fixed 40% bar would have stayed silent through that, and + once the probe is fixed the genuine APAC share climbs past any such bar and + pages forever on the correct end state. The 2x and 15-point bars sit inside + the broken state and outside a healthy one. `unhinted` requests are + excluded from the denominator: they were 27% of all requests, so a client + change that always sends a hint would move the number with no behaviour + change at all. The two bars are cross-multiplied rather than divided. An + hour that placed nobody in the region is the most extreme skew there is, + and it happens whenever the region is drained, fenced, or at capacity, but + dividing by that zero placement share makes MQL drop the row and lose the + series before any other clause runs. + +Expect the skew alert to stay lit after a client fix until the mis-homed +backlog is rehomed. Sticky assignment never re-consults the hint, so a +desktop already on an asia cell keeps being placed there whatever it now +asks for; the ratio clears only once the rehome sweep has drained. + +All three conditions are written in MQL rather than the metric filters the +other relay policies use. Every runtime metric is a DELTA DISTRIBUTION, and +the only scalar aligners a filter condition can apply to one are percentiles; +each of these alerts needs the sum of the extracted values as a volume floor, +which is `sum(value.)` in MQL and unreachable otherwise. None of the +metrics they read exists in the project yet, so what was checked against +production is the query shape: the same MQL run over existing metrics of the +same kind confirmed the distribution sum, the join arity, the unit literals, +and the condition clause. + +The skew shares are built from one log-based metric per region for hints and +one per region for placements. They read flat `requestedRegionDelta` +and `selectedRegionDelta` fields that the relay publishes as zeros in +every interval, not the nested region maps: a log-based metric would need a +quoted field path to reach a hyphenated map key, and an absent key would drop +a series out of the inner join. The region list lives in Terraform as +`relay_region_keys` and is pinned to relay-contract's `RELAY_REGIONS` by +`dev/scripts/relay-region-hint-metrics.test.mjs`. Both sides spell the field +name segments out as literal maps rather than deriving them, so the same test +compares the two declarations directly. Adding a region to the contract +without its segment is a compile error in relay-contract, not a silent gap. + ## Implementation log - Recalibrated the relay pool freezes from 30 waiters / 1,000 ms to diff --git a/cloud/infra/terraform/relay-observability.tf b/cloud/infra/terraform/relay-observability.tf index 0d4b181d338..4c6722d3532 100644 --- a/cloud/infra/terraform/relay-observability.tf +++ b/cloud/infra/terraform/relay-observability.tf @@ -93,6 +93,80 @@ locals { db_oldest_wait_ms = { field = "databasePoolOldestWaitMs", description = "Current oldest PostgreSQL pool waiter age." } db_wait_ms_max = { field = "databasePoolWaitMsMax", description = "Maximum PostgreSQL pool wait during the interval." } } + + # Regions the director can hint or select. Pinned to relay-contract's RELAY_REGIONS by + # dev/scripts/relay-region-hint-metrics.test.mjs, which also checks the flat field names below + # against the emitter. A region missing here drops out of both shares the skew alert compares. + relay_region_keys = ["us-central1", "asia-east2"] + # Flat emitter fields, not the nested `requestedRegionsDelta` map: a log-based metric would need + # a quoted field path to reach a hyphenated map key, and the relay publishes these as zeros in + # every interval so no series can drop out of the alert's inner join. Spelled out rather than + # derived, so this literal and relay-contract's RELAY_REGION_METRIC_SEGMENTS can be compared + # directly; reformatting either side cannot break the check and neither can drift alone. + relay_region_field_segments = { + "us-central1" = "UsCentral1" + "asia-east2" = "AsiaEast2" + } + relay_region_columns = { for key in local.relay_region_keys : key => replace(key, "-", "_") } + relay_region_share_metrics = merge( + { + for key in local.relay_region_keys : + "requested_regions_${local.relay_region_columns[key]}" => { + field = "requestedRegion${local.relay_region_field_segments[key]}Delta" + description = "Assignment requests that hinted ${key}." + } + }, + { + for key in local.relay_region_keys : + "selected_regions_${local.relay_region_columns[key]}" => { + field = "selectedRegion${local.relay_region_field_segments[key]}Delta" + description = "Assignments that placed a host in ${key}." + } + } + ) + relay_region_hinted_total = join(" + ", [for key in local.relay_region_keys : "req_${local.relay_region_columns[key]}"]) + relay_region_selected_total = join(" + ", [for key in local.relay_region_keys : "sel_${local.relay_region_columns[key]}"]) + # MQL, not a filter condition: every runtime metric is a DELTA DISTRIBUTION, and the only scalar + # aligners a `condition_threshold` can apply to one are percentiles. Both shares need the sum of + # the extracted values, which is `sum(value.)` in MQL and unreachable otherwise. + relay_region_hint_skew_query = join("\n", concat( + ["{"], + flatten([ + for index, entry in [ + for key in local.relay_region_keys : { metric = "requested_regions_${local.relay_region_columns[key]}", column = "req_${local.relay_region_columns[key]}" } + ] : [ + index == 0 ? "" : ";", + " fetch cloud_run_revision::logging.googleapis.com/user/orca_relay_${entry.metric}", + " | align delta(1h) | every 1h", + " | group_by [], [${entry.column}: sum(value.orca_relay_${entry.metric})]" + ] + ]), + flatten([ + for key in local.relay_region_keys : [ + ";", + " fetch cloud_run_revision::logging.googleapis.com/user/orca_relay_selected_regions_${local.relay_region_columns[key]}", + " | align delta(1h) | every 1h", + " | group_by [], [sel_${local.relay_region_columns[key]}: sum(value.orca_relay_selected_regions_${local.relay_region_columns[key]})]" + ] + ]), + [ + "}", + "| join", + "| value [", + " hint_share: req_asia_east2 / (${local.relay_region_hinted_total}),", + " placement_share: sel_asia_east2 / (${local.relay_region_selected_total}),", + " hinted_requests: ${local.relay_region_hinted_total}", + " ]", + # Cross-multiplied, never a plain ratio of the two shares: an hour that placed nobody in the + # region makes that ratio 0/0 or x/0, and MQL drops the row instead of yielding a number, so + # the whole series vanishes before the other clauses run. That hour is the worst skew there + # is - every desktop asking for a region the director is putting nobody in - and it happens + # whenever the region is drained, fenced, or at capacity. Both forms were run read-only + # against production surrogates with a zero denominator: the ratio returned no rows, this + # returned the series with the condition true. + "| condition hint_share > 2 * placement_share && hint_share - placement_share > 0.15 '1' && hinted_requests > 500 '1'" + ] + )) relay_custom_alerts = { connection_headroom = { pages_oncall = true @@ -214,7 +288,9 @@ locals { } resource "google_logging_metric" "relay_snapshot" { - for_each = local.relay_runtime_metrics + # Region-request metrics ride the same event and shape; merging adds map entries only, so the + # existing metric instances are untouched (a label change, not a new key, is what recreates them). + for_each = merge(local.relay_runtime_metrics, local.relay_region_share_metrics) project = var.project_id name = "orca_relay_${each.key}" @@ -685,6 +761,128 @@ resource "google_monitoring_alert_policy" "relay_cell_process_exit" { depends_on = [google_logging_metric.relay_incident] } +# Why: nothing fired while US desktops sat on asia-east2 cells for weeks in 2026-08. The two +# per-cell policies below read that as distance, and the fleet-wide one reads it as a bad region +# hint. All three are MQL because each needs the sum of a DELTA DISTRIBUTION as a volume floor, +# and the only scalar aligners a `condition_threshold` can apply to a distribution are percentiles. +# `join` is an inner join and the relay omits its percentile fields on an empty interval, so an +# idle cell drops out rather than alerting on nothing. The per-cell arms fetch `gce_instance` +# only: production runs no Cloud Run cells (`relay_cells` is empty), and a future one would need +# its own arm here. None of the metrics these query exist in the project yet, so what was checked +# against production is the query shape: the same MQL run over existing metrics of the same kind +# confirmed the distribution sum, the join arity, the unit literals, and the condition clause. +resource "google_monitoring_alert_policy" "relay_far_cell_accept_latency" { + project = var.project_id + display_name = "Orca Relay: far-cell phone accept latency" + combiner = "OR" + enabled = true + notification_channels = var.relay_alert_notification_channels + + conditions { + display_name = "Phone accept p95 above 2 s for 15 minutes" + + condition_monitoring_query_language { + # percentile(..., 50) over the window, not max: the published value is already a p95, so the + # median of the interval p95s reads as sustained slowness instead of one bad 30-second flush. + query = <<-EOT + { + fetch gce_instance::logging.googleapis.com/user/orca_relay_client_accept_total_ms_p95 + | align delta(15m) | every 15m + | group_by [metric.cell_id], [accept_p95_ms: percentile(value.orca_relay_client_accept_total_ms_p95, 50)] + ; + fetch gce_instance::logging.googleapis.com/user/orca_relay_client_accepts_completed + | align delta(15m) | every 15m + | group_by [metric.cell_id], [accepts: sum(value.orca_relay_client_accepts_completed)] + } + | join + | condition accept_p95_ms > 2000 'ms' && accepts >= 20 '1' + EOT + duration = "0s" + + trigger { + count = 1 + } + } + } + + documentation { + content = "Phones on this cell are taking over two seconds to reach relay-hello. Measured separation: an in-region accept completes in 0.3-0.6 s and a cross-Pacific one in 5-10 s, so 2 s sits well outside in-region noise and well below the far-cell floor. The 20-accept floor over 15 minutes keeps a single slow accept on a quiet cell from paging. Check which regions the cell's hosts are actually in before touching capacity: the 2026-08 cause was desktops requesting the wrong region, not a slow cell. Read the per-stage `orca_relay_client_accept_*_ms_p95` metrics to separate distance from assignment, credential, or attach work." + mime_type = "text/markdown" + } + + depends_on = [google_logging_metric.relay_snapshot] +} + +resource "google_monitoring_alert_policy" "relay_cell_control_rtt" { + project = var.project_id + display_name = "Orca Relay: cell control round trip" + combiner = "OR" + enabled = true + notification_channels = var.relay_alert_notification_channels + + conditions { + display_name = "Control ping p50 above 150 ms for an hour" + + condition_monitoring_query_language { + # p50 only. The desktop echoes the pong on its main thread, so the published p95 and max + # track renderer stalls, not distance; the median is the only column that reads as distance. + query = <<-EOT + { + fetch gce_instance::logging.googleapis.com/user/orca_relay_control_rtt_ms_p50 + | align delta(1h) | every 1h + | group_by [metric.cell_id], [control_rtt_p50_ms: percentile(value.orca_relay_control_rtt_ms_p50, 50)] + ; + fetch gce_instance::logging.googleapis.com/user/orca_relay_control_rtt_samples + | align delta(1h) | every 1h + | group_by [metric.cell_id], [samples: sum(value.orca_relay_control_rtt_samples)] + } + | join + | condition control_rtt_p50_ms > 150 'ms' && samples >= 500 '1' + EOT + duration = "0s" + + trigger { + count = 1 + } + } + } + + documentation { + content = "The median desktop on this cell is more than 150 ms away from it, which is a mis-homed population rather than a cell fault: an in-region control ping is tens of milliseconds and a US desktop on an asia-east2 cell is 200 ms or more. This is the signal that was missing while roughly 226 of 332 hosts on the asia cells were non-APAC for weeks in 2026-08. Confirm with the assignment table which regions those hosts requested, then rehome; do not restart or drain the cell on this alert alone. The 500-sample floor is about two continuously connected hosts at the 15-second control ping, so a nearly idle cell cannot alert on one desktop. Tuning risk: EU desktops on us-central1 sit at 100-130 ms, so a cell whose population is mostly European can approach 150 ms while correctly homed. Check where the hosts are before treating a first breach as mis-homing, and raise the bar only with that evidence." + mime_type = "text/markdown" + } + + depends_on = [google_logging_metric.relay_snapshot] +} + +resource "google_monitoring_alert_policy" "relay_region_hint_skew" { + project = var.project_id + display_name = "Orca Relay: region hint skew" + combiner = "OR" + enabled = true + notification_channels = var.relay_alert_notification_channels + + conditions { + display_name = "asia-east2 hint share above 2x its placement share for an hour" + + condition_monitoring_query_language { + query = local.relay_region_hint_skew_query + duration = "0s" + + trigger { + count = 1 + } + } + } + + documentation { + content = "Desktops are asking the director for asia-east2 far more often than the director actually places them there, which is what silently homed US desktops on asia cells through 2026-08. The alert compares two shares of the same hour and never an absolute share, because an absolute bar is wrong at both ends: measured over twelve hours on 2026-09-07, while the desktop region probe was still mis-picking, asia-east2 was 33.8% of the 33,800 hinted requests but only 7.9% of the 45,364 assignments, and once the probe is fixed the genuine APAC share will climb past any fixed bar that would have caught this. Divergence was 4.27x with a 25.9-point gap, so the 2x and 15-point bars sit well inside the broken state and well outside a healthy one. `unhinted` requests are excluded from the denominator: they were 27% of all requests, and a client change that always sends a hint would move this number without any behaviour changing. Expect this to stay lit until the mis-homed backlog is rehomed, because sticky assignment never re-consults the hint, so a desktop already on an asia cell keeps being placed there no matter what it now asks for. Investigate the desktop region probe first, not relay placement." + mime_type = "text/markdown" + } + + depends_on = [google_logging_metric.relay_snapshot] +} + # Why: the four signals that had to be assembled by hand during the 2026-09-04 incident. resource "google_monitoring_dashboard" "relay_incident" { project = var.project_id diff --git a/cloud/package.json b/cloud/package.json index 62dbadc7455..242bbbd824c 100644 --- a/cloud/package.json +++ b/cloud/package.json @@ -20,7 +20,7 @@ "load:relay:model": "node dev/scripts/run-relay-load-model.mjs", "load:relay:recovery-gate": "node dev/scripts/run-relay-recovery-wave-gate.mjs", "ops:relay": "pnpm --filter @orca-cloud/relay-ops dev", - "pretest": "node --test dev/scripts/capture-terraform-plan-baseline.test.mjs dev/scripts/operate-relay-asia-admission.test.mjs dev/scripts/prepare-relay-asia-director-cells.test.mjs dev/scripts/prepare-relay-asia-topology-input.test.mjs dev/scripts/production-cloud-sql-rollout-lock.test.mjs dev/scripts/read-relay-serving-regional-placement-version.test.mjs dev/scripts/relay-asia-admission-workflow.test.mjs dev/scripts/relay-asia-rollout-evidence.test.mjs dev/scripts/relay-asia-topology-workflow.test.mjs dev/scripts/relay-cloud-sql-connection-budget.test.mjs dev/scripts/relay-load-reader-evidence.test.mjs dev/scripts/relay-staging-deploy-identity.test.mjs dev/scripts/sanitize-relay-asia-admission-result.test.mjs dev/scripts/terraform-root-partition.test.mjs dev/scripts/validate-relay-asia-topology-plan.test.mjs ../.github/actions/cloud-sql-rollout-lease/action-contract.test.mjs ../.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs", + "pretest": "node --test dev/scripts/capture-terraform-plan-baseline.test.mjs dev/scripts/operate-relay-asia-admission.test.mjs dev/scripts/prepare-relay-asia-director-cells.test.mjs dev/scripts/prepare-relay-asia-topology-input.test.mjs dev/scripts/production-cloud-sql-rollout-lock.test.mjs dev/scripts/read-relay-serving-regional-placement-version.test.mjs dev/scripts/relay-asia-admission-workflow.test.mjs dev/scripts/relay-asia-rollout-evidence.test.mjs dev/scripts/relay-asia-topology-workflow.test.mjs dev/scripts/relay-cloud-sql-connection-budget.test.mjs dev/scripts/relay-load-reader-evidence.test.mjs dev/scripts/relay-region-hint-metrics.test.mjs dev/scripts/relay-staging-deploy-identity.test.mjs dev/scripts/sanitize-relay-asia-admission-result.test.mjs dev/scripts/terraform-root-partition.test.mjs dev/scripts/validate-relay-asia-topology-plan.test.mjs ../.github/actions/cloud-sql-rollout-lease/action-contract.test.mjs ../.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs", "test": "pnpm -r test && node --test dev/scripts/classify-relay-production-capacity-director.test.mjs dev/scripts/classify-relay-staging-bootstrap.test.mjs dev/scripts/deploy-relay-blue-green.test.mjs dev/scripts/deploy-relay-gce-candidate.test.mjs dev/scripts/deploy-relay-gce-multi-target.test.mjs dev/scripts/github-smoke-token.test.mjs dev/scripts/infra.test.mjs dev/scripts/operate-relay-regional-rehome.test.mjs dev/scripts/power-staging-relay.test.mjs dev/scripts/prepare-relay-capacity-canary.test.mjs dev/scripts/prepare-relay-production-capacity-canary.test.mjs dev/scripts/probe-relay-legacy-admission.test.mjs dev/scripts/probe-relay-rehome-trust.test.mjs dev/scripts/production-cell-image-digest-consistency.test.mjs dev/scripts/read-relay-production-capacity-identity.test.mjs dev/scripts/relay-admin-endpoint-retry-workflow.test.mjs dev/scripts/relay-admin-transient-retry.test.mjs dev/scripts/relay-admission-selector.test.mjs dev/scripts/relay-gce-terraform-fence.test.mjs dev/scripts/relay-load-connection-failure.test.mjs dev/scripts/relay-load-control-peer.test.mjs dev/scripts/relay-load-director-capacity-gate.test.mjs dev/scripts/relay-load-model.test.mjs dev/scripts/relay-load-phase-barrier.test.mjs dev/scripts/relay-load-placement-boundary.test.mjs dev/scripts/relay-load-profile.test.mjs dev/scripts/relay-load-rebind-boundary.test.mjs dev/scripts/relay-load-region-behavior.test.mjs dev/scripts/relay-load-request-unit-boundary.test.mjs dev/scripts/relay-load-run-lifecycle.test.mjs dev/scripts/relay-monitor-evidence.test.mjs dev/scripts/relay-production-capacity-wave.test.mjs dev/scripts/relay-production-capacity-workflow.test.mjs dev/scripts/relay-production-identity-boundaries.test.mjs dev/scripts/relay-production-same-cap-wave.test.mjs dev/scripts/relay-public-workflow-contract.test.mjs dev/scripts/relay-recovery-wave-gate.test.mjs dev/scripts/relay-region-observation-evidence.test.mjs dev/scripts/relay-regional-rehome-workflow.test.mjs dev/scripts/relay-rehome-aggregate-evidence.test.mjs dev/scripts/relay-repository.test.mjs dev/scripts/relay-same-cap-script-census.test.mjs dev/scripts/relay-staging-c4-refresh-workflow.test.mjs dev/scripts/relay-staging-capacity-identity.test.mjs dev/scripts/staging-relay-apply-guard.test.mjs dev/scripts/validate-relay-capacity-plan.test.mjs dev/scripts/verify-relay-capacity-transition.test.mjs dev/scripts/verify-relay-legacy-bootstrap.test.mjs dev/scripts/workload-identity-attribute-conditions.test.mjs", "typecheck": "pnpm -r typecheck" }, diff --git a/cloud/packages/relay-contract/src/relay-regions.ts b/cloud/packages/relay-contract/src/relay-regions.ts index 38ac36cd738..6b8837829df 100644 --- a/cloud/packages/relay-contract/src/relay-regions.ts +++ b/cloud/packages/relay-contract/src/relay-regions.ts @@ -8,6 +8,15 @@ export type RelayRegion = z.infer export const RELAY_DEFAULT_REGION: RelayRegion = 'us-central1' +// Field-name segment for the flat per-region runtime counters, spelled out rather than derived so +// the Terraform side can hold the same literal and a test can compare the two. `satisfies` makes a +// new region a compile error here, which is the point: a region with no segment would silently +// drop out of the region-skew alert's denominators. +export const RELAY_REGION_METRIC_SEGMENTS = { + 'us-central1': 'UsCentral1', + 'asia-east2': 'AsiaEast2' +} as const satisfies Record + const RelayProbeOriginSchema = z.string().url().max(2_048).refine(isCanonicalHttpsOrigin) export const RelayRegionCatalogResponseSchema = z From fede3eb2ffef58c884ff907563883c6ac0afd83b Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 04:54:28 -0400 Subject: [PATCH 10/37] fix(test): give federation tests a real read-after-write sync barrier (#19262) `syncOrchestrationFederation()` coalesces onto an already-in-flight relay-tick sync, which may have pulled from the peer before the caller's mutation existed. Tests used it as a barrier, so `keeps a timed-out remote question resumable` could reply against a home DB that had never imported the worker's question: the reply failed with `Message not found`, no `to_worker` relay was enqueued, and the resume ask surfaced it 5s later as a spurious timeout. Add `syncFederationBarrier()`, which chains each active dispatch past the current round via `syncOrchestrationFederatedDispatchAfterCurrent`, and use it at every barrier-purpose sync site. The two tests whose subject is the sync machinery itself keep the raw call. Also assert the reply response, so a failed reply fails at the reply instead of masquerading as a timeout. Production is unaffected: `syncOrchestrationFederation` has no production callers, real read-after-write paths already use the after-current sync, and relay ticks retry every second. --- .../federation-control-mail.test.ts | 5 +++-- .../federation-sync-barrier.test-support.ts | 17 +++++++++++++++ .../federation/federation.test.ts | 21 +++++++++++-------- 3 files changed, 32 insertions(+), 11 deletions(-) create mode 100644 src/main/runtime/rpc/methods/orchestration/federation/federation-sync-barrier.test-support.ts diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts index b351582d14b..755f85fd512 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts @@ -8,6 +8,7 @@ import type { RpcRequest } from '../../../core' import { RpcDispatcher } from '../../../dispatcher' import { fingerprintAuthenticatedPairingCredential } from '../../../orchestration-mutation-executor' import { ORCHESTRATION_METHODS } from '../../orchestration' +import { syncFederationBarrier } from './federation-sync-barrier.test-support' describe('orchestration federation control mail', () => { const homeToken = 'run-home-device-token' @@ -160,7 +161,7 @@ describe('orchestration federation control mail', () => { }) expect(homeDb.listPendingFederationRelay(dispatchId, 'to_worker')).toHaveLength(1) - await homeRuntime.syncOrchestrationFederation() + await syncFederationBarrier(homeRuntime, homeDb) const checked = await workerDispatcher.dispatch(checkRequest('check-imported')) expect(checked).toMatchObject({ @@ -252,7 +253,7 @@ describe('orchestration federation control mail', () => { settleRemoteOutcome: 'succeeded' }) - await homeRuntime.syncOrchestrationFederation() + await syncFederationBarrier(homeRuntime, homeDb) expect(homeDb.getWorkerDispatch(dispatchId)?.state).toBe('succeeded') expect(workerDb.getUnreadMessages(`dispatch:${dispatchId}`)).toHaveLength(0) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-sync-barrier.test-support.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-sync-barrier.test-support.ts new file mode 100644 index 00000000000..675c55068ce --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-sync-barrier.test-support.ts @@ -0,0 +1,17 @@ +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' + +// A run-wide sync coalesces onto whatever relay tick is already in flight, and that tick may have +// read the peer before the test's latest mutation existed. Chain past the current round instead so +// awaiting the barrier really means "everything enqueued before this call has been exchanged". +export async function syncFederationBarrier( + runtime: OrcaRuntimeService, + db: OrchestrationDb +): Promise { + const dispatches = db.listActiveFederatedDispatches() + await Promise.allSettled( + dispatches.map((dispatch) => + runtime.syncOrchestrationFederatedDispatchAfterCurrent(dispatch.dispatch_id) + ) + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts index 8146c43ed29..e627e112530 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts @@ -11,6 +11,7 @@ import { RpcDispatcher } from '../../../dispatcher' import { ORCHESTRATION_METHODS } from '../../orchestration' import { createFederationWorkerStartRequest as startRequest } from './federation-request.test-support' import { configureFederationWorkerRuntime } from './federation-runtime.test-support' +import { syncFederationBarrier } from './federation-sync-barrier.test-support' describe('orchestration federation', () => { const databases: OrchestrationDb[] = [] @@ -310,7 +311,7 @@ describe('orchestration federation', () => { expect(sent).toMatchObject({ ok: true, result: { lifecycle: { action: 'completed' } } }) expect(homeDb.getTask(task.id)?.status).toBe('completed') - await homeRuntime.syncOrchestrationFederation() + await syncFederationBarrier(homeRuntime, homeDb) expect(homeDb.getTask(task.id)?.status).toBe('completed') expect(homeDb.getWorkerDispatch(dispatch.id)?.state).toBe('succeeded') @@ -362,7 +363,7 @@ describe('orchestration federation', () => { ).toHaveLength(1) ) - await homeRuntime.syncOrchestrationFederation() + await syncFederationBarrier(homeRuntime, homeDb) const question = homeDb .getRunMailboxHistory(task.run_id, 10) .find((message) => message.type === 'question') @@ -383,7 +384,7 @@ describe('orchestration federation', () => { } }) expect(reply).toMatchObject({ ok: true, result: { question: { status: 'answered' } } }) - await homeRuntime.syncOrchestrationFederation() + await syncFederationBarrier(homeRuntime, homeDb) await expect(ask).resolves.toMatchObject({ ok: true, @@ -426,8 +427,8 @@ describe('orchestration federation', () => { }) const questionId = (timedOut as { result: { messageId: string } }).result.messageId - await homeRuntime.syncOrchestrationFederation() - await homeDispatcher.dispatch({ + await syncFederationBarrier(homeRuntime, homeDb) + const lateReply = await homeDispatcher.dispatch({ id: 'rpc_home_late_reply', authToken: 'coordinator-token', orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, @@ -435,6 +436,8 @@ describe('orchestration federation', () => { method: 'orchestration.reply', params: { id: questionId, body: 'yes', from: 'term_coord' } }) + // A rejected reply enqueues no relay, which would only surface as the resume timing out. + expect(lateReply).toMatchObject({ ok: true, result: { question: { status: 'answered' } } }) restartWorkerRuntime() const resumed = workerDispatcher.dispatch({ id: 'rpc_remote_ask_resume', @@ -445,7 +448,7 @@ describe('orchestration federation', () => { method: 'orchestration.ask', params: { from: 'term_windows_worker', resume: questionId, timeoutMs: 5_000 } }) - await homeRuntime.syncOrchestrationFederation() + await syncFederationBarrier(homeRuntime, homeDb) await expect(resumed).resolves.toMatchObject({ ok: true, @@ -476,8 +479,8 @@ describe('orchestration federation', () => { loseNextAckResponse = true const remoteCall = vi.spyOn(homeRuntime, 'callOrchestrationWorkerServer') - await expect(homeRuntime.syncOrchestrationFederation()).resolves.toBeUndefined() - await homeRuntime.syncOrchestrationFederation() + await expect(syncFederationBarrier(homeRuntime, homeDb)).resolves.toBeUndefined() + await syncFederationBarrier(homeRuntime, homeDb) expect( homeDb @@ -612,7 +615,7 @@ describe('orchestration federation', () => { it('treats a worker runtime ID change as an epoch, not a new server', async () => { const task = createHomeTask() await homeDispatcher.dispatch(startRequest(task.id)) - await homeRuntime.syncOrchestrationFederation() + await syncFederationBarrier(homeRuntime, homeDb) vi.spyOn(homeRuntime, 'ensureOrchestrationFederationRelay').mockImplementation(() => {}) const dispatch = homeDb.getDispatchContext(task.id)! const oldEpoch = homeDb.getFederatedDispatch(dispatch.id)?.remote_runtime_epoch From d74f8cb787c0892d1fe980549384abc5a1744cad Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 04:56:13 -0400 Subject: [PATCH 11/37] revert(mobile): hold the relay reconnect path and cache-first reconnect for a separate mobile pass (#19265) * Revert "feat(mobile): draw the last known tab strip while a session reconnects (#19258)" This reverts commit 0ba7f8dc8d2dca757e51d4e4c25ff3539fc3eb4d. * Revert "perf(mobile): cut the relay reconnect critical path and admit dead sockets faster (#19236)" This reverts commit 23df74d85a0b566f4663f34339532789b6ac8287. --- .../src/cache/session-tab-strip-cache.test.ts | 282 ------------------ mobile/src/cache/session-tab-strip-cache.ts | 228 -------------- .../session/MobileSessionActiveContent.tsx | 11 +- mobile/src/session/MobileSessionHeader.tsx | 59 ++-- .../session/mobile-session-frame-styles.ts | 5 - ...obile-session-reconnect-view-state.test.ts | 155 ---------- .../mobile-session-reconnect-view-state.ts | 61 ---- .../mobile-session-route-parity.test.ts | 27 +- ...ession-route-source-family.test-support.ts | 1 - .../mobile-session-tab-strip-entries.ts | 116 ------- .../session/use-mobile-session-controller.ts | 4 +- .../use-mobile-session-presentation.ts | 29 +- .../use-mobile-session-tab-strip-cache.ts | 66 ---- .../transport/host-removal-lifecycle.test.ts | 28 -- .../src/transport/host-removal-lifecycle.ts | 4 - .../transport/mobile-direct-return-probe.ts | 22 +- .../transport/mobile-endpoint-lifecycle.ts | 3 +- .../mobile-endpoint-supervisor-contract.ts | 4 +- ...e-endpoint-supervisor-direct-probe.test.ts | 106 ------- .../mobile-endpoint-supervisor-test-fakes.ts | 1 - .../mobile-endpoint-supervisor.test.ts | 3 - .../transport/mobile-endpoint-supervisor.ts | 31 +- .../mobile-relay-credential-rotation.ts | 4 - .../mobile-relay-rpc-session-liveness.test.ts | 103 ++----- .../mobile-relay-rpc-session.test.ts | 183 +++--------- .../src/transport/mobile-relay-rpc-session.ts | 68 ++--- .../mobile-relay-runtime-failover.test.ts | 4 - .../mobile-relay-session-establisher.ts | 14 +- .../transport/relay-recovery-intent-queue.ts | 45 --- .../rpc-session-liveness-watchdog.ts | 63 ++-- .../unpaired-host-credential-deletion.test.ts | 82 ----- .../unpaired-host-credential-deletion.ts | 8 - 32 files changed, 165 insertions(+), 1655 deletions(-) delete mode 100644 mobile/src/cache/session-tab-strip-cache.test.ts delete mode 100644 mobile/src/cache/session-tab-strip-cache.ts delete mode 100644 mobile/src/session/mobile-session-reconnect-view-state.test.ts delete mode 100644 mobile/src/session/mobile-session-reconnect-view-state.ts delete mode 100644 mobile/src/session/mobile-session-tab-strip-entries.ts delete mode 100644 mobile/src/session/use-mobile-session-tab-strip-cache.ts delete mode 100644 mobile/src/transport/relay-recovery-intent-queue.ts delete mode 100644 mobile/src/transport/unpaired-host-credential-deletion.test.ts diff --git a/mobile/src/cache/session-tab-strip-cache.test.ts b/mobile/src/cache/session-tab-strip-cache.test.ts deleted file mode 100644 index fa1ed188edc..00000000000 --- a/mobile/src/cache/session-tab-strip-cache.test.ts +++ /dev/null @@ -1,282 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const asyncStorage = vi.hoisted(() => ({ - getItem: vi.fn(), - setItem: vi.fn(), - removeItem: vi.fn() -})) - -vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) - -import { - deleteCachedSessionTabStripForHost, - getSessionTabStripCacheKey, - loadCachedSessionTabStrip, - readCachedSessionTabStrip, - resetSessionTabStripCacheForTests, - saveCachedSessionTabStrip -} from './session-tab-strip-cache' -import type { MobileSessionTabStripPreview } from '../session/mobile-session-tab-strip-entries' - -const STORAGE_KEY = 'orca:session-tab-strip:v1' - -function preview(...ids: string[]): MobileSessionTabStripPreview { - return { - tabs: ids.map((id) => ({ id, type: 'terminal' as const, title: id, agentId: null })), - activeTabId: ids[0] ?? null - } -} - -function lastWrittenFile(): { workspaces: { key: string }[] } { - const call = asyncStorage.setItem.mock.calls.at(-1) - return JSON.parse(String(call?.[1])) -} - -beforeEach(() => { - vi.useFakeTimers() - asyncStorage.getItem.mockReset().mockResolvedValue(null) - asyncStorage.setItem.mockReset().mockResolvedValue(undefined) - resetSessionTabStripCacheForTests() -}) - -afterEach(() => { - vi.useRealTimers() -}) - -describe('getSessionTabStripCacheKey', () => { - it('digests the workspace id so no filesystem path reaches the key', () => { - const path = '/Users/someone/private-client/worktrees/acquisition' - const key = getSessionTabStripCacheKey('host-1', `repo::${path}`) - - expect(key).not.toContain(path) - expect(key).not.toContain('someone') - expect(key).toMatch(/^\["host-1","[0-9a-f]{32}"\]$/) - }) - - it('joins the two ids unambiguously, whatever a worktree path contains', () => { - expect(getSessionTabStripCacheKey('host', 'a\nb')).not.toBe( - getSessionTabStripCacheKey('host\na', 'b') - ) - expect(getSessionTabStripCacheKey('host-1', 'wt-1')).not.toBe( - getSessionTabStripCacheKey('host-1', 'wt-2') - ) - }) - - it('needs both a host and a workspace', () => { - expect(getSessionTabStripCacheKey(undefined, 'wt-1')).toBeNull() - expect(getSessionTabStripCacheKey('host-1', undefined)).toBeNull() - }) -}) - -describe('session tab strip cache', () => { - it('serves a save back synchronously and persists it once the write settles', async () => { - const key = getSessionTabStripCacheKey('host-1', 'wt-1') - saveCachedSessionTabStrip(key, preview('tab-1', 'tab-2')) - - expect(readCachedSessionTabStrip(key)?.tabs.map((tab) => tab.id)).toEqual(['tab-1', 'tab-2']) - expect(asyncStorage.setItem).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(300) - - expect(asyncStorage.setItem.mock.calls[0]?.[0]).toBe(STORAGE_KEY) - expect(lastWrittenFile().workspaces.map((w) => w.key)).toEqual([key]) - }) - - it('reads nothing synchronously before the stored file is loaded', async () => { - const key = getSessionTabStripCacheKey('host-1', 'wt-1') - asyncStorage.getItem.mockResolvedValue( - JSON.stringify({ workspaces: [{ key, preview: preview('tab-1') }] }) - ) - - expect(readCachedSessionTabStrip(key)).toBeNull() - expect((await loadCachedSessionTabStrip(key))?.tabs.map((tab) => tab.id)).toEqual(['tab-1']) - expect(readCachedSessionTabStrip(key)?.tabs).toHaveLength(1) - }) - - it('returns null for a workspace with no stored strip', async () => { - expect(await loadCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', 'wt-9'))).toBeNull() - expect(await loadCachedSessionTabStrip(null)).toBeNull() - }) - - it('survives unreadable storage', async () => { - asyncStorage.getItem.mockResolvedValue('{not json') - - expect(await loadCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', 'wt-1'))).toBeNull() - }) - - it('evicts the least recently written workspace past the cap', async () => { - for (let i = 0; i < 14; i++) { - saveCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', `wt-${i}`), preview('tab-1')) - } - await vi.advanceTimersByTimeAsync(300) - - const keys = lastWrittenFile().workspaces.map((w) => w.key) - expect(keys).toHaveLength(12) - expect(keys).not.toContain(getSessionTabStripCacheKey('host-1', 'wt-0')) - expect(keys.at(-1)).toBe(getSessionTabStripCacheKey('host-1', 'wt-13')) - }) - - it('re-writing a workspace makes it the newest, not the oldest', async () => { - for (let i = 0; i < 12; i++) { - saveCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', `wt-${i}`), preview('tab-1')) - } - saveCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', 'wt-0'), preview('tab-2')) - saveCachedSessionTabStrip(getSessionTabStripCacheKey('host-1', 'wt-99'), preview('tab-1')) - await vi.advanceTimersByTimeAsync(300) - - const keys = lastWrittenFile().workspaces.map((w) => w.key) - expect(keys).toContain(getSessionTabStripCacheKey('host-1', 'wt-0')) - expect(keys).not.toContain(getSessionTabStripCacheKey('host-1', 'wt-1')) - }) - - it('records a workspace the host has emptied, so a stale strip cannot outlive it', async () => { - const key = getSessionTabStripCacheKey('host-1', 'wt-1') - saveCachedSessionTabStrip(key, preview('tab-1')) - saveCachedSessionTabStrip(key, { tabs: [], activeTabId: null }) - - expect(readCachedSessionTabStrip(key)).toEqual({ tabs: [], activeTabId: null }) - }) - - it('caps tabs per workspace and title length, and drops an unmatched active id', async () => { - const key = getSessionTabStripCacheKey('host-1', 'wt-1') - saveCachedSessionTabStrip(key, { - // A file tab, because the titles that survive redaction at all are the ones the cap has - // to bound. - tabs: Array.from({ length: 30 }, (_, i) => ({ - id: `tab-${i}`, - type: 'file' as const, - title: 'x'.repeat(200), - agentId: null - })), - activeTabId: 'tab-29' - }) - - const stored = readCachedSessionTabStrip(key) - expect(stored?.tabs).toHaveLength(24) - expect(stored?.tabs[0]?.title).toHaveLength(64) - expect(stored?.activeTabId).toBeNull() - }) - - it('drops fields a future tab type might smuggle into storage', async () => { - const key = getSessionTabStripCacheKey('host-1', 'wt-1') - saveCachedSessionTabStrip(key, { - tabs: [ - { - id: 'tab-1', - type: 'file', - title: 'notes.md', - agentId: null, - filePath: '/Users/someone/secret/notes.md' - } as never - ], - activeTabId: 'tab-1' - }) - await vi.advanceTimersByTimeAsync(300) - - expect(String(asyncStorage.setItem.mock.calls.at(-1)?.[1])).not.toContain('/Users/someone') - }) - - it('drops a stored entry naming a tab type this build cannot draw', async () => { - const key = getSessionTabStripCacheKey('host-1', 'wt-1') - saveCachedSessionTabStrip(key, { - tabs: [ - { id: 'tab-1', type: 'from-a-newer-build', title: 'raw title', agentId: null } as never, - { id: 'tab-2', type: 'file', title: 'notes.md', agentId: null } - ], - activeTabId: 'tab-2' - }) - - expect(readCachedSessionTabStrip(key)?.tabs.map((tab) => tab.id)).toEqual(['tab-2']) - }) - - it('never writes a shell-controlled terminal title, however it arrives', async () => { - const secret = 'psql postgres://admin:hunter2@db.internal/prod' - const key = getSessionTabStripCacheKey('host-1', 'wt-1') - saveCachedSessionTabStrip(key, { - tabs: [ - { id: 'tab-1', type: 'terminal', title: secret, agentId: null }, - { id: 'tab-2', type: 'terminal', title: secret, agentId: 'claude' }, - { id: 'tab-3', type: 'terminal', title: secret, agentId: 'not-a-known-agent' }, - { id: 'tab-4', type: 'browser', title: 'Acme Corp — Q3 layoffs memo', agentId: null } - ], - activeTabId: 'tab-1' - }) - await vi.advanceTimersByTimeAsync(300) - - expect(readCachedSessionTabStrip(key)?.tabs.map((tab) => tab.title)).toEqual([ - 'Terminal', - 'Claude', - 'Terminal', - 'Browser' - ]) - const written = String(asyncStorage.setItem.mock.calls.at(-1)?.[1]) - expect(written).not.toContain('hunter2') - expect(written).not.toContain('postgres://') - expect(written).not.toContain('layoffs') - }) - - it('scrubs a stored title written by an older build on the way back out', async () => { - const key = getSessionTabStripCacheKey('host-1', 'wt-1') - asyncStorage.getItem.mockResolvedValue( - JSON.stringify({ - workspaces: [ - { - key, - preview: { - tabs: [{ id: 'tab-1', type: 'terminal', title: 'curl -H token', agentId: null }], - activeTabId: 'tab-1' - } - } - ] - }) - ) - - expect((await loadCachedSessionTabStrip(key))?.tabs[0]?.title).toBe('Terminal') - }) - - it('forgets an unpaired host and cannot resurrect it from a later save', async () => { - const hostA = getSessionTabStripCacheKey('host-a', 'wt-1') - const hostB = getSessionTabStripCacheKey('host-b', 'wt-1') - saveCachedSessionTabStrip(hostA, preview('tab-a')) - saveCachedSessionTabStrip(hostB, preview('tab-b')) - await vi.advanceTimersByTimeAsync(300) - - await deleteCachedSessionTabStripForHost('host-a') - - expect(readCachedSessionTabStrip(hostA)).toBeNull() - expect(readCachedSessionTabStrip(hostB)?.tabs).toHaveLength(1) - expect(lastWrittenFile().workspaces.map((w) => w.key)).toEqual([hostB]) - - saveCachedSessionTabStrip(hostB, preview('tab-b2')) - await vi.advanceTimersByTimeAsync(300) - - expect(lastWrittenFile().workspaces.map((w) => w.key)).toEqual([hostB]) - }) - - it('forgets a host whose rows are only on disk, never read this session', async () => { - const hostA = getSessionTabStripCacheKey('host-a', 'wt-1') - const hostB = getSessionTabStripCacheKey('host-b', 'wt-1') - asyncStorage.getItem.mockResolvedValue( - JSON.stringify({ - workspaces: [ - { key: hostA, preview: preview('tab-a') }, - { key: hostB, preview: preview('tab-b') } - ] - }) - ) - - await deleteCachedSessionTabStripForHost('host-a') - - expect(lastWrittenFile().workspaces.map((w) => w.key)).toEqual([hostB]) - }) - - it('drops a pending debounced write so it cannot restore the forgotten host', async () => { - const hostA = getSessionTabStripCacheKey('host-a', 'wt-1') - saveCachedSessionTabStrip(hostA, preview('tab-a')) - - await deleteCachedSessionTabStripForHost('host-a') - await vi.advanceTimersByTimeAsync(300) - - expect(lastWrittenFile().workspaces).toEqual([]) - }) -}) diff --git a/mobile/src/cache/session-tab-strip-cache.ts b/mobile/src/cache/session-tab-strip-cache.ts deleted file mode 100644 index 222e2c3fd27..00000000000 --- a/mobile/src/cache/session-tab-strip-cache.ts +++ /dev/null @@ -1,228 +0,0 @@ -// Why: reconnecting to a workspace the phone opened a minute ago tears the session screen back -// to an empty strip and a spinner, even though the tab list it is about to be handed is the one -// it just displayed. Persist the shape of the strip per workspace so a reconnect paints the -// known tabs immediately and swaps in live rows under the same keys. -// -// This file is the authority on what reaches plaintext storage, not its callers: every entry is -// rebuilt field by field on the way in, and shell-controlled titles are replaced with fixed -// labels here rather than trusted to have been scrubbed upstream. -import AsyncStorage from '@react-native-async-storage/async-storage' -import { sha256 } from '@noble/hashes/sha256' -import { - getPersistableTabStripTitle, - isDrawableTabStripType, - type MobileSessionTabStripEntry, - type MobileSessionTabStripPreview -} from '../session/mobile-session-tab-strip-entries' - -const STORAGE_KEY = 'orca:session-tab-strip:v1' -// A phone realistically revisits a handful of workspaces; the caps bound both the stored blob -// and the cost of a single write. -const MAX_WORKSPACES = 12 -const MAX_TABS_PER_WORKSPACE = 24 -const MAX_TITLE_LENGTH = 64 -const WRITE_DEBOUNCE_MS = 250 -// 128 bits of a digest: far past collision range for a dozen workspaces, and short enough that -// the stored blob stays small. -const WORKSPACE_DIGEST_LENGTH = 32 - -type StoredWorkspace = { key: string; preview: MobileSessionTabStripPreview } -type StoredFile = { workspaces: StoredWorkspace[] } - -// Insertion-ordered, so the first key is the least recently written one to evict. -let memoryCache: Map | null = null -let loadPromise: Promise> | null = null -let writeTimer: ReturnType | null = null - -/** - * A workspace id ends in a filesystem path, so it is digested rather than stored. The host id - * stays readable because forgetting a host has to be able to find that host's rows, and because - * host ids already key several other entries in this store. - */ -export function getSessionTabStripCacheKey( - hostId: string | undefined, - worktreeId: string | undefined -): string | null { - if (!hostId || !worktreeId) { - return null - } - return JSON.stringify([hostId, digestWorkspaceId(worktreeId)]) -} - -/** Whatever this process already knows, with no await — so a revisit paints on the first frame. */ -export function readCachedSessionTabStrip(key: string | null): MobileSessionTabStripPreview | null { - if (!key || !memoryCache) { - return null - } - return memoryCache.get(key) ?? null -} - -export async function loadCachedSessionTabStrip( - key: string | null -): Promise { - if (!key) { - return null - } - const cache = await loadFile() - return cache.get(key) ?? null -} - -export function saveCachedSessionTabStrip( - key: string | null, - preview: MobileSessionTabStripPreview -): void { - if (!key) { - return - } - const redacted = redactPreview(preview) - const cache = memoryCache ?? new Map() - memoryCache = cache - // Map.set on an existing key keeps its original iteration position, so delete first to make - // the re-inserted key the newest and give the cap true LRU eviction. - cache.delete(key) - cache.set(key, redacted) - while (cache.size > MAX_WORKSPACES) { - const oldest = cache.keys().next().value - if (oldest === undefined) { - break - } - cache.delete(oldest) - } - scheduleWrite(cache) -} - -/** - * Drop every workspace belonging to a host the user has unpaired. Both the in-memory rows and - * the stored blob have to go: leaving either behind means the next save for any other host - * serializes the forgotten host's tabs straight back to disk. - */ -export async function deleteCachedSessionTabStripForHost(hostId: string): Promise { - // Load first so the rewrite below preserves other hosts. If storage is unreadable we still - // rewrite, which can cost another host its rows — the wrong direction for a cache, the right - // one for a deletion the user asked for. - const cache = await loadFile() - // Deleting the entry the iterator is standing on is well-defined for a Map. - for (const key of cache.keys()) { - if (readHostIdFromKey(key) === hostId) { - cache.delete(key) - } - } - if (writeTimer) { - clearTimeout(writeTimer) - writeTimer = null - } - await writeFile(cache) -} - -export function resetSessionTabStripCacheForTests(): void { - if (writeTimer) { - clearTimeout(writeTimer) - writeTimer = null - } - memoryCache = null - loadPromise = null -} - -function digestWorkspaceId(worktreeId: string): string { - const digest = sha256(new TextEncoder().encode(worktreeId)) - let hex = '' - for (const byte of digest) { - hex += byte.toString(16).padStart(2, '0') - } - return hex.slice(0, WORKSPACE_DIGEST_LENGTH) -} - -function readHostIdFromKey(key: string): string | null { - try { - const parsed = JSON.parse(key) as unknown - return Array.isArray(parsed) && typeof parsed[0] === 'string' ? parsed[0] : null - } catch { - return null - } -} - -async function loadFile(): Promise> { - if (memoryCache) { - return memoryCache - } - loadPromise ??= (async () => { - const parsed = await readStoredFile() - // A save that landed while the read was in flight owns the newer truth. - const cache = memoryCache ?? new Map() - for (const workspace of parsed) { - if (!cache.has(workspace.key)) { - cache.set(workspace.key, workspace.preview) - } - } - memoryCache = cache - return cache - })() - return loadPromise -} - -async function readStoredFile(): Promise { - try { - const raw = await AsyncStorage.getItem(STORAGE_KEY) - if (!raw) { - return [] - } - const parsed = JSON.parse(raw) as StoredFile - if (typeof parsed !== 'object' || parsed === null || !Array.isArray(parsed.workspaces)) { - return [] - } - return parsed.workspaces.flatMap((workspace) => { - if (typeof workspace?.key !== 'string' || !Array.isArray(workspace.preview?.tabs)) { - return [] - } - return [{ key: workspace.key, preview: redactPreview(workspace.preview) }] - }) - } catch { - return [] - } -} - -// Why: a flurry of snapshots (one per desktop republication) must not hammer AsyncStorage. -function scheduleWrite(cache: Map): void { - if (writeTimer) { - clearTimeout(writeTimer) - } - writeTimer = setTimeout(() => { - writeTimer = null - void writeFile(cache) - }, WRITE_DEBOUNCE_MS) -} - -async function writeFile(cache: Map): Promise { - const workspaces: StoredWorkspace[] = [...cache].map(([key, preview]) => ({ key, preview })) - await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify({ workspaces })).catch(() => {}) -} - -// Rebuilt field by field so a field later added to the live tab type cannot ride into storage -// without someone deciding it belongs there. -function redactPreview(preview: MobileSessionTabStripPreview): MobileSessionTabStripPreview { - const tabs: MobileSessionTabStripEntry[] = [] - for (const tab of preview.tabs ?? []) { - if (typeof tab?.id !== 'string' || !isDrawableTabStripType(tab.type)) { - continue - } - const agentId = typeof tab.agentId === 'string' ? tab.agentId : null - const title = typeof tab.title === 'string' ? tab.title : '' - tabs.push({ - id: tab.id, - type: tab.type, - title: getPersistableTabStripTitle({ type: tab.type, title, agentId }).slice( - 0, - MAX_TITLE_LENGTH - ), - agentId - }) - if (tabs.length === MAX_TABS_PER_WORKSPACE) { - break - } - } - const activeTabId = - typeof preview.activeTabId === 'string' && tabs.some((tab) => tab.id === preview.activeTabId) - ? preview.activeTabId - : null - return { tabs, activeTabId } -} diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index 00c852dbf01..019e83c6a99 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -74,7 +74,6 @@ export function MobileSessionActiveContent({ activePendingTerminalTab, isPendingTerminalRecoveryParked, retryPendingTerminalRecovery, - reconnectViewState, showLoadingState, showEmptyState, keyboardLift, @@ -82,15 +81,7 @@ export function MobileSessionActiveContent({ toastAnimatedStyle, createTabBusy } = controller - // Why: the cached strip in the header is the content during a reconnect; the terminal body - // cannot be, because replaying stored scrollback into the WebView would double-render once the - // live stream replays the same rows. See mobile-session-reconnect-view-state. - return reconnectViewState.kind === 'reconnecting-with-cache' ? ( - - - {reconnectViewState.label} - - ) : showLoadingState ? ( + return showLoadingState ? ( diff --git a/mobile/src/session/MobileSessionHeader.tsx b/mobile/src/session/MobileSessionHeader.tsx index a23c216c729..552f507a787 100644 --- a/mobile/src/session/MobileSessionHeader.tsx +++ b/mobile/src/session/MobileSessionHeader.tsx @@ -14,6 +14,10 @@ import { MobileSessionHeaderIconButton } from './MobileSessionHeaderIconButton' import { triggerMediumImpact } from '../platform/haptics' import { StatusDot } from '../components/StatusDot' import { MobileAgentIcon } from '../components/MobileAgentIcon' +import { + getMobileSessionTabTitle, + resolveMobileTerminalTabAgentId +} from './mobile-terminal-tab-agent' import { colors } from '../theme/mobile-theme' import { QuickCommandsTabButton } from './QuickCommandsTabButton' import { styles } from './mobile-session-styles' @@ -28,6 +32,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC forceReconnectHost, worktreeName, activePanel, + activeSessionTabId, activeSessionTabIdRef, tabStripRef, tabStripOffsetRef, @@ -47,7 +52,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC scrollActiveTabIntoView, switchSessionTab, openSessionTabActionSheetAfterKeyboardDismiss, - tabStripRows, + visibleTabs, showConnectionRetry, terminalSummary, handlePanelTap, @@ -112,7 +117,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC ) : null} - {tabStripRows.length > 0 && ( + {visibleTabs.length > 0 && ( {/* Why: tab taps must register on first press with the keyboard open instead of being eaten by dismissal (#5106). */} - {tabStripRows.map(({ entry, isActive, tab }) => ( + {visibleTabs.map((t) => ( { const { x, width } = e.nativeEvent.layout - tabLayoutsRef.current.set(entry.id, { x, width }) - if (entry.id === activeSessionTabIdRef.current) { - scrollActiveTabIntoView(entry.id, false) + tabLayoutsRef.current.set(t.id, { x, width }) + if (t.id === activeSessionTabIdRef.current) { + scrollActiveTabIntoView(t.id, false) } }} - // A cached preview row has no live tab behind it, so both gestures need the - // reconnect to land first. - disabled={tab === null} - onPress={tab === null ? undefined : () => switchSessionTab(tab)} - onLongPress={ - tab === null - ? undefined - : () => { - triggerMediumImpact() - openSessionTabActionSheetAfterKeyboardDismiss(tab) - } - } + onPress={() => switchSessionTab(t)} + onLongPress={() => { + triggerMediumImpact() + openSessionTabActionSheetAfterKeyboardDismiss(t) + }} delayLongPress={400} > - {entry.type === 'browser' && ( + {t.type === 'browser' && ( )} - {entry.type === 'markdown' && ( + {t.type === 'markdown' && ( )} - {entry.type === 'file' && ( + {t.type === 'file' && ( )} - {entry.agentId !== null && } + {t.type === 'agent-session' && } + {t.type === 'terminal' && + (() => { + const agentId = resolveMobileTerminalTabAgentId(t) + return agentId ? : null + })()} - {entry.title} + {getMobileSessionTabTitle(t)} diff --git a/mobile/src/session/mobile-session-frame-styles.ts b/mobile/src/session/mobile-session-frame-styles.ts index 22d3c6e76cc..a02c14be014 100644 --- a/mobile/src/session/mobile-session-frame-styles.ts +++ b/mobile/src/session/mobile-session-frame-styles.ts @@ -102,11 +102,6 @@ export const mobileSessionFrameStyles = StyleSheet.create({ borderBottomWidth: 2, borderBottomColor: 'transparent' }, - // Why: a cached row is inert until the reconnect lands, so it carries the same de-emphasis as - // the disabled tab-bar buttons beside it rather than passing for a live tab. - tabPreview: { - opacity: 0.45 - }, tabActive: { // Neutral grey underline, matching the desktop terminal tab's active // indicator (a muted foreground/card mix), not a blue accent. diff --git a/mobile/src/session/mobile-session-reconnect-view-state.test.ts b/mobile/src/session/mobile-session-reconnect-view-state.test.ts deleted file mode 100644 index 09f9bbb8447..00000000000 --- a/mobile/src/session/mobile-session-reconnect-view-state.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { selectMobileSessionReconnectViewState } from './mobile-session-reconnect-view-state' -import { - getMobileSessionTabStripRows, - toMobileSessionTabStripPreview, - type MobileSessionTabStripPreview -} from './mobile-session-tab-strip-entries' -import type { MobileSessionTab } from './mobile-session-route-types' - -function terminalTab(id: string, title: string, isActive = false): MobileSessionTab { - return { type: 'terminal', id, title, terminal: `h-${id}`, isActive } -} - -const cachedPreview: MobileSessionTabStripPreview = { - tabs: [ - { id: 'tab-1', type: 'terminal', title: 'claude', agentId: 'claude' }, - { id: 'tab-2', type: 'terminal', title: 'shell', agentId: null } - ], - activeTabId: 'tab-1' -} - -const base = { - connState: 'reconnecting', - verdictKind: 'normal', - terminalsLoaded: false, - liveTabCount: 0, - activeHandle: null, - cachedPreview: null -} as const - -describe('selectMobileSessionReconnectViewState', () => { - it('renders the cached strip with a progress label while reconnecting', () => { - const state = selectMobileSessionReconnectViewState({ ...base, cachedPreview }) - - expect(state).toEqual({ - kind: 'reconnecting-with-cache', - preview: cachedPreview, - label: 'Reconnecting…' - }) - }) - - it('labels the post-connect hydration gap as loading, not reconnecting', () => { - const state = selectMobileSessionReconnectViewState({ - ...base, - connState: 'connected', - cachedPreview - }) - - expect(state.kind === 'reconnecting-with-cache' && state.label).toBe('Loading tabs…') - }) - - it('blocks when nothing is cached for this workspace', () => { - expect(selectMobileSessionReconnectViewState(base)).toEqual({ kind: 'blocking' }) - expect( - selectMobileSessionReconnectViewState({ - ...base, - cachedPreview: { tabs: [], activeTabId: null } - }) - ).toEqual({ kind: 'blocking' }) - }) - - it('keeps mounted live content instead of swapping in its own cached snapshot', () => { - expect( - selectMobileSessionReconnectViewState({ ...base, liveTabCount: 2, cachedPreview }) - ).toEqual({ kind: 'live' }) - expect( - selectMobileSessionReconnectViewState({ ...base, activeHandle: 'h-1', cachedPreview }) - ).toEqual({ kind: 'live' }) - }) - - it('treats a host-confirmed empty workspace as live', () => { - expect( - selectMobileSessionReconnectViewState({ - ...base, - connState: 'connected', - terminalsLoaded: true, - cachedPreview - }) - ).toEqual({ kind: 'live' }) - }) - - it('falls back to the offline state once the retry loop or the pairing has failed', () => { - expect( - selectMobileSessionReconnectViewState({ ...base, verdictKind: 'unreachable', cachedPreview }) - ).toEqual({ kind: 'offline' }) - expect( - selectMobileSessionReconnectViewState({ ...base, verdictKind: 'auth-failed', cachedPreview }) - ).toEqual({ kind: 'offline' }) - }) - - it('keeps showing the cache through a transient warning verdict', () => { - expect( - selectMobileSessionReconnectViewState({ ...base, verdictKind: 'warning', cachedPreview }).kind - ).toBe('reconnecting-with-cache') - }) -}) - -describe('getMobileSessionTabStripRows', () => { - it('draws disabled preview rows while reconnecting, then the live tabs under the same keys', () => { - const preview = selectMobileSessionReconnectViewState({ ...base, cachedPreview }) - const previewRows = getMobileSessionTabStripRows({ - liveTabs: [], - activeSessionTabId: null, - preview: preview.kind === 'reconnecting-with-cache' ? preview.preview : null - }) - - expect(previewRows.map((row) => row.entry.id)).toEqual(['tab-1', 'tab-2']) - expect(previewRows.map((row) => row.tab)).toEqual([null, null]) - expect(previewRows.map((row) => row.isActive)).toEqual([true, false]) - - const liveTabs = [terminalTab('tab-1', 'claude', true), terminalTab('tab-2', 'shell')] - const liveRows = getMobileSessionTabStripRows({ - liveTabs, - activeSessionTabId: 'tab-1', - preview: null - }) - - expect(liveRows.map((row) => row.entry.id)).toEqual(previewRows.map((row) => row.entry.id)) - expect(liveRows.map((row) => row.isActive)).toEqual(previewRows.map((row) => row.isActive)) - expect(liveRows.every((row) => row.tab !== null)).toBe(true) - }) - - it('prefers live tabs over a preview that is still present', () => { - const rows = getMobileSessionTabStripRows({ - liveTabs: [terminalTab('tab-9', 'fresh', true)], - activeSessionTabId: 'tab-9', - preview: cachedPreview - }) - - expect(rows.map((row) => row.entry.id)).toEqual(['tab-9']) - }) - - it('keeps only the drawn fields when projecting a preview to persist', () => { - const preview = toMobileSessionTabStripPreview( - [ - { - type: 'terminal', - id: 'tab-1', - title: 'claude', - terminal: 'h-1', - launchAgent: 'claude', - launchDraft: 'unsent secret prompt', - isActive: true - } - ], - 'tab-1' - ) - - expect(preview).toEqual({ - tabs: [{ id: 'tab-1', type: 'terminal', title: 'claude', agentId: 'claude' }], - activeTabId: 'tab-1' - }) - expect(JSON.stringify(preview)).not.toContain('unsent secret prompt') - }) -}) diff --git a/mobile/src/session/mobile-session-reconnect-view-state.ts b/mobile/src/session/mobile-session-reconnect-view-state.ts deleted file mode 100644 index fe980676408..00000000000 --- a/mobile/src/session/mobile-session-reconnect-view-state.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { ConnectionVerdict } from '../transport/connection-health' -import type { ConnectionState } from '../transport/types' -import type { MobileSessionTabStripPreview } from './mobile-session-tab-strip-entries' - -/** - * What the session screen should draw while the phone is not yet serving live tabs. - * - * - `live`: real tabs are mounted (or the host has confirmed there are none). The existing - * loading/empty/content branches own the screen. - * - `reconnecting-with-cache`: nothing live yet, but this workspace's last strip is on the - * device. Draw it, disabled, with a compact progress line instead of a bare spinner. - * - `offline`: the retry loop has given up or the pairing is rejected. A stale strip would - * imply a session we cannot reach, so fall back to the existing offline affordance. - * - `blocking`: nothing live and nothing cached. Unchanged from before this state existed. - */ -export type MobileSessionReconnectViewState = - | { kind: 'live' } - | { kind: 'reconnecting-with-cache'; preview: MobileSessionTabStripPreview; label: string } - | { kind: 'offline' } - | { kind: 'blocking' } - -export function selectMobileSessionReconnectViewState(args: { - connState: ConnectionState - verdictKind: ConnectionVerdict['kind'] - terminalsLoaded: boolean - liveTabCount: number - activeHandle: string | null - cachedPreview: MobileSessionTabStripPreview | null -}): MobileSessionReconnectViewState { - const { connState, verdictKind, terminalsLoaded, liveTabCount, activeHandle, cachedPreview } = - args - // A mounted terminal or tab is the real thing; a mid-session drop must never trade it for a - // snapshot of itself, however the connection is faring. - if (liveTabCount > 0 || activeHandle !== null) { - return { kind: 'live' } - } - // The host has answered and said this workspace is empty — that is live truth, not a gap. - if (connState === 'connected' && terminalsLoaded) { - return { kind: 'live' } - } - if (verdictKind === 'unreachable' || verdictKind === 'auth-failed') { - return { kind: 'offline' } - } - if (cachedPreview && cachedPreview.tabs.length > 0) { - return { - kind: 'reconnecting-with-cache', - preview: cachedPreview, - label: reconnectProgressLabel(connState) - } - } - return { kind: 'blocking' } -} - -function reconnectProgressLabel(connState: ConnectionState): string { - if (connState === 'connected') { - return 'Loading tabs…' - } - return connState === 'reconnecting' || connState === 'disconnected' - ? 'Reconnecting…' - : 'Connecting…' -} diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index 1455765771f..bc951bfa206 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -37,7 +37,6 @@ const LOGIC_EXPANSION_NAMES = new Set([ 'useMobileSessionContentCreateActions', 'useMobileSessionCloseActions', 'useMobileSessionBulkClose', - 'useMobileSessionTabStripCache', 'useMobileSessionPresentation', 'useMobileSessionPanelRouteActions' ]) @@ -63,12 +62,12 @@ const HOST_COMPONENT_NAMES = new Set([ 'View' ]) -const HEAD_MAIN_HOOK_SHA256 = '1b539cb02e2b6a3ea906b3c23050b8ed072e01e86ff64b3fde37c0643e9ea008' -const HEAD_HOOK_BINDING_SHA256 = 'fb32bba96822e00df7e451751101784839683c7b31e50e3ee871e13cddabe619' +const HEAD_MAIN_HOOK_SHA256 = '10071240ef9edafc2b9c8bed73be83dceaf7828e3b29f17dab55da020a7697a6' +const HEAD_HOOK_BINDING_SHA256 = '1dadb8c3dc0573ea20659ce7251629669e618dd0effaeac3a4536b29c2e865a1' const HEAD_CALLBACK_IDENTITY_SHA256 = '2a9e4825df007f6ef53b81aa5004991d6318eee7507b44d625c07e630be432eb' const HEAD_CALLBACK_BODY_SHA256 = '22103ba85a86e3a3fcb80a7509c7a455d79863010cde3af02db6565b55e3ebe9' -const HEAD_EFFECT_SHA256 = '016d046a108bd5b44ffcf0d277d5c64bb10657e13d79f9d37b91c056eef743df' +const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = '536c72b233c813bb0cea164b090bdce5406ceb965bbc5b83c1f89b89b46f3821' @@ -80,11 +79,11 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - '0ad9a4e8b336b9f10db4d39553bc1880f00c164d575766fe31f6e92cc1cccd25' -const HEAD_HOST_JSX_SHA256 = 'd2ebf1684d3ea579707e545334f9abbc4977552bf5322df11765b4f974d7078e' -const HEAD_LEAF_JSX_SHA256 = '9d6f8e326f69ddda44855c4af988bfdfadce34fe47c47946fbbc2eb3cb0b8782' + '31951b0b83be01ebfa659c4b94df9ad7eaff6404df5338fbade89eb7473a3cb4' +const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' +const HEAD_LEAF_JSX_SHA256 = '21dba981875e173f692590bf910d60964660c5f4cbb79f3a377c7e54f6a1f016' const HEAD_STYLE_REFERENCE_SHA256 = - 'e12ba3494873d828d84ea4d2cc6ce8ee3414cec7f371e00eef8cb18cb3cc7a3b' + '295a3501c2c6d7bea7c8bbf38b3f3534f01344cd7e1b91bb8e07c040821d596a' const HEAD_IDENTITY_FIELD_SHA256 = '91146853930a34dd1f3d80e5c97fbacd7cf19fb93dd26fe8fc6f29169622f9d6' const HEAD_NAVIGATION_SHA256 = '9d96f5dad7de555d6553eac39c0fab00efad507470fd562cb9beaa32db16f512' @@ -473,13 +472,13 @@ describe('mobile session route extraction parity', () => { const contentBindings = CONTENT_COMPONENT_NAMES.flatMap( (name) => readHookFacts(name, definitions).bindings ) - expect(main.hooks).toHaveLength(269) + expect(main.hooks).toHaveLength(266) expect(hash(main.hooks)).toBe(HEAD_MAIN_HOOK_SHA256) expect(hash(main.bindings)).toBe(HEAD_HOOK_BINDING_SHA256) expect(main.callbacks).toHaveLength(77) expect(hash(main.callbacks)).toBe(HEAD_CALLBACK_IDENTITY_SHA256) expect(hash(main.callbackBodies)).toBe(HEAD_CALLBACK_BODY_SHA256) - expect(main.effects).toHaveLength(26) + expect(main.effects).toHaveLength(24) expect(hash(main.effects)).toBe(HEAD_EFFECT_SHA256) expect(contentBindings).toHaveLength(14) expect(hash(contentBindings)).toBe(HEAD_CONTENT_HOOK_SHA256) @@ -518,14 +517,14 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(548) + expect(strings).toHaveLength(546) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) - expect(jsx.host).toHaveLength(127) + expect(jsx.host).toHaveLength(124) expect(hash(jsx.host)).toBe(HEAD_HOST_JSX_SHA256) - expect(jsx.leaf).toHaveLength(60) + expect(jsx.leaf).toHaveLength(61) expect(hash(jsx.leaf)).toBe(HEAD_LEAF_JSX_SHA256) - expect(jsx.styleReferences).toHaveLength(175) + expect(jsx.styleReferences).toHaveLength(172) expect(hash(jsx.styleReferences)).toBe(HEAD_STYLE_REFERENCE_SHA256) }) }) diff --git a/mobile/src/session/mobile-session-route-source-family.test-support.ts b/mobile/src/session/mobile-session-route-source-family.test-support.ts index acb2bef34a8..41f2d8b9c2f 100644 --- a/mobile/src/session/mobile-session-route-source-family.test-support.ts +++ b/mobile/src/session/mobile-session-route-source-family.test-support.ts @@ -33,7 +33,6 @@ export const MOBILE_SESSION_ROUTE_SOURCE_FILES = [ './use-mobile-session-content-create-actions.ts', './use-mobile-session-close-actions.ts', './use-mobile-session-bulk-close.ts', - './use-mobile-session-tab-strip-cache.ts', './use-mobile-session-presentation.ts', './use-mobile-session-panel-route-actions.tsx', './MobileSessionMarkdownReader.tsx', diff --git a/mobile/src/session/mobile-session-tab-strip-entries.ts b/mobile/src/session/mobile-session-tab-strip-entries.ts deleted file mode 100644 index 5f4569403b0..00000000000 --- a/mobile/src/session/mobile-session-tab-strip-entries.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { TUI_AGENT_DISPLAY_NAMES } from '../../../src/shared/tui-agent-display-names' -import type { MobileSessionTab, MobileSessionTabType } from './mobile-session-route-types' -import { - getMobileSessionTabTitle, - resolveMobileTerminalTabAgentId -} from './mobile-terminal-tab-agent' - -/** - * The only session-tab fields the tab strip draws. Everything else the live tab carries (unsent - * launch drafts, absolute file paths, browser URLs, agent session ids) stays on the wire. - */ -export type MobileSessionTabStripEntry = { - id: string - type: MobileSessionTabType - title: string - agentId: string | null -} - -export type MobileSessionTabStripPreview = { - tabs: readonly MobileSessionTabStripEntry[] - activeTabId: string | null -} - -export type MobileSessionTabStripRow = { - entry: MobileSessionTabStripEntry - isActive: boolean - /** null on a preview row: switching to that tab needs a live connection. */ - tab: MobileSessionTab | null -} - -export function toMobileSessionTabStripEntry(tab: MobileSessionTab): MobileSessionTabStripEntry { - return { - id: tab.id, - type: tab.type, - title: getMobileSessionTabTitle(tab), - agentId: - tab.type === 'agent-session' - ? tab.agent - : tab.type === 'terminal' - ? resolveMobileTerminalTabAgentId(tab) - : null - } -} - -/** - * Every tab type the strip knows how to draw. A stored entry naming anything else is dropped - * rather than trusted, so a type added later fails closed: its rows go missing from the preview - * instead of carrying an unreviewed title into storage. - */ -const drawableTabTypes = new Set([ - 'terminal', - 'markdown', - 'file', - 'browser', - 'agent-session' -] satisfies readonly MobileSessionTabType[]) - -export function isDrawableTabStripType(type: string): type is MobileSessionTabType { - return drawableTabTypes.has(type) -} - -const agentDisplayNames: Readonly> = TUI_AGENT_DISPLAY_NAMES - -/** - * The title a strip entry may be written to disk under. - * - * A terminal's title is whatever the shell last set, which is routinely the command line — - * `psql postgres://user:password@host/db`, `curl -H "Authorization: Bearer ..."`. None of that - * belongs in plaintext storage, and a browser tab's page title is no better. Both collapse to a - * fixed label, so what survives is the shape of the strip, not its contents. A resolved agent - * still names itself, because that lookup is a closed enum: an unrecognised id yields the - * generic label rather than passing text through. - */ -export function getPersistableTabStripTitle( - entry: Pick -): string { - if (entry.type === 'terminal') { - const agentLabel = entry.agentId === null ? undefined : agentDisplayNames[entry.agentId] - return agentLabel ?? 'Terminal' - } - if (entry.type === 'browser') { - return 'Browser' - } - return entry.title -} - -export function toMobileSessionTabStripPreview( - tabs: readonly MobileSessionTab[], - activeTabId: string | null -): MobileSessionTabStripPreview { - return { tabs: tabs.map(toMobileSessionTabStripEntry), activeTabId } -} - -/** - * Rows for the header strip. Live tabs always win; the preview only fills a strip that has no - * live rows yet, and its ids are the live ids, so the swap reuses the same React keys. - */ -export function getMobileSessionTabStripRows(args: { - liveTabs: readonly MobileSessionTab[] - activeSessionTabId: string | null - preview: MobileSessionTabStripPreview | null -}): MobileSessionTabStripRow[] { - const { liveTabs, activeSessionTabId, preview } = args - if (liveTabs.length > 0 || !preview) { - return liveTabs.map((tab) => ({ - entry: toMobileSessionTabStripEntry(tab), - isActive: tab.id === activeSessionTabId, - tab - })) - } - return preview.tabs.map((entry) => ({ - entry, - isActive: entry.id === preview.activeTabId, - tab: null - })) -} diff --git a/mobile/src/session/use-mobile-session-controller.ts b/mobile/src/session/use-mobile-session-controller.ts index b2427f806c2..f188b30b17a 100644 --- a/mobile/src/session/use-mobile-session-controller.ts +++ b/mobile/src/session/use-mobile-session-controller.ts @@ -27,7 +27,6 @@ import { useMobileSessionTerminalCreateActions } from './use-mobile-session-term import { useMobileSessionContentCreateActions } from './use-mobile-session-content-create-actions' import { useMobileSessionCloseActions } from './use-mobile-session-close-actions' import { useMobileSessionBulkClose } from './use-mobile-session-bulk-close' -import { useMobileSessionTabStripCache } from './use-mobile-session-tab-strip-cache' import { useMobileSessionPresentation } from './use-mobile-session-presentation' import { useMobileSessionPanelRouteActions } from './use-mobile-session-panel-route-actions' @@ -114,8 +113,7 @@ export function useMobileSessionController() { useMobileSessionCloseActions(contentCreateActions) ) const bulkClose = Object.assign(closeActions, useMobileSessionBulkClose(closeActions)) - const tabStripCache = Object.assign(bulkClose, useMobileSessionTabStripCache(bulkClose)) - const presentation = Object.assign(tabStripCache, useMobileSessionPresentation(tabStripCache)) + const presentation = Object.assign(bulkClose, useMobileSessionPresentation(bulkClose)) const panelRouteActions = Object.assign( presentation, useMobileSessionPanelRouteActions(presentation) diff --git a/mobile/src/session/use-mobile-session-presentation.ts b/mobile/src/session/use-mobile-session-presentation.ts index e43b59cabef..2565f729940 100644 --- a/mobile/src/session/use-mobile-session-presentation.ts +++ b/mobile/src/session/use-mobile-session-presentation.ts @@ -3,11 +3,9 @@ import { classifyConnection, verdictDisplayLabel } from '../transport/connection import { computeActiveTerminalKeyboardLift } from '../terminal/terminal-keyboard-avoidance-lift' import { useInitialSessionTerminalAutoCreate } from './use-initial-session-terminal-autocreate' import { MOBILE_SESSION_STATUS_LABELS } from './mobile-session-route-helpers' -import { selectMobileSessionReconnectViewState } from './mobile-session-reconnect-view-state' -import { getMobileSessionTabStripRows } from './mobile-session-tab-strip-entries' -import type { MobileSessionTabStripCacheModel } from './use-mobile-session-tab-strip-cache' +import type { MobileSessionBulkCloseModel } from './use-mobile-session-bulk-close' -export function useMobileSessionPresentation(scope: MobileSessionTabStripCacheModel) { +export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) { const { created, worktreeId, @@ -26,8 +24,6 @@ export function useMobileSessionPresentation(scope: MobileSessionTabStripCacheMo terminalKeyboardMetrics, toastOpacityRef, hostEndpoint, - activeSessionTabId, - cachedTabStrip, initialSessionAutoCreateRef, terminalFrameHeightRef, handleCreateTerminal, @@ -62,23 +58,6 @@ export function useMobileSessionPresentation(scope: MobileSessionTabStripCacheMo const showConnectionRetry = connectionVerdict.kind === 'warning' || connectionVerdict.kind === 'unreachable' - // Why: a reconnect to a workspace this phone has already drawn should re-draw it, not blank - // the screen while the RPCs land. See mobile-session-reconnect-view-state. - const reconnectViewState = selectMobileSessionReconnectViewState({ - connState, - verdictKind: connectionVerdict.kind, - terminalsLoaded, - liveTabCount: visibleTabs.length, - activeHandle, - cachedPreview: cachedTabStrip - }) - const tabStripRows = getMobileSessionTabStripRows({ - liveTabs: visibleTabs, - activeSessionTabId, - preview: - reconnectViewState.kind === 'reconnecting-with-cache' ? reconnectViewState.preview : null - }) - const terminalSummary = connState === 'connected' ? showLoadingState @@ -109,8 +88,6 @@ export function useMobileSessionPresentation(scope: MobileSessionTabStripCacheMo return { showLoadingState, showEmptyState, - reconnectViewState, - tabStripRows, connectionVerdict, showConnectionRetry, terminalSummary, @@ -120,5 +97,5 @@ export function useMobileSessionPresentation(scope: MobileSessionTabStripCacheMo } } -export type MobileSessionPresentationModel = MobileSessionTabStripCacheModel & +export type MobileSessionPresentationModel = MobileSessionBulkCloseModel & ReturnType diff --git a/mobile/src/session/use-mobile-session-tab-strip-cache.ts b/mobile/src/session/use-mobile-session-tab-strip-cache.ts deleted file mode 100644 index d0207afd83c..00000000000 --- a/mobile/src/session/use-mobile-session-tab-strip-cache.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { useEffect, useState } from 'react' -import { - getSessionTabStripCacheKey, - loadCachedSessionTabStrip, - readCachedSessionTabStrip, - saveCachedSessionTabStrip -} from '../cache/session-tab-strip-cache' -import { - toMobileSessionTabStripPreview, - type MobileSessionTabStripPreview -} from './mobile-session-tab-strip-entries' -import type { MobileSessionBulkCloseModel } from './use-mobile-session-bulk-close' - -/** - * Keeps the last drawn tab strip for this workspace on the device, so a reconnect has something - * to render before the first snapshot lands. See mobile-session-reconnect-view-state. - */ -export function useMobileSessionTabStripCache(scope: MobileSessionBulkCloseModel) { - const { hostId, worktreeId, connState, terminalsLoaded } = scope - const { visibleTabs, activeSessionTabId, activeHandle } = scope - const cacheKey = getSessionTabStripCacheKey(hostId, worktreeId) - // Why: state settles a commit behind the key it was read for, so carry the key with it — - // otherwise the first render after a workspace switch draws the previous workspace's strip. - const [loaded, setLoaded] = useState<{ - key: string | null - preview: MobileSessionTabStripPreview | null - }>(() => ({ key: cacheKey, preview: readCachedSessionTabStrip(cacheKey) })) - - useEffect(() => { - // Synchronous first, so an in-session revisit never blinks through the uncached branch. - setLoaded({ key: cacheKey, preview: readCachedSessionTabStrip(cacheKey) }) - let disposed = false - void loadCachedSessionTabStrip(cacheKey).then((preview) => { - if (!disposed) { - setLoaded({ key: cacheKey, preview }) - } - }) - return () => { - disposed = true - } - }, [cacheKey]) - const cachedTabStrip = loaded.key === cacheKey ? loaded.preview : null - - // Only a host-confirmed strip is worth persisting, and an emptied workspace has to be written - // too — skipping it would leave yesterday's tabs to be drawn over a session that no longer has - // them. The one reading we do not trust is a live terminal with no tab record behind it, which - // is the same case the empty state refuses to claim (use-mobile-session-presentation). - // react-doctor-disable-next-line react-doctor/effect-needs-cleanup - useEffect(() => { - if (connState !== 'connected' || !terminalsLoaded) { - return - } - if (visibleTabs.length === 0 && activeHandle !== null) { - return - } - saveCachedSessionTabStrip( - cacheKey, - toMobileSessionTabStripPreview(visibleTabs, activeSessionTabId) - ) - }, [activeHandle, activeSessionTabId, cacheKey, connState, terminalsLoaded, visibleTabs]) - - return { cachedTabStrip } -} - -export type MobileSessionTabStripCacheModel = MobileSessionBulkCloseModel & - ReturnType diff --git a/mobile/src/transport/host-removal-lifecycle.test.ts b/mobile/src/transport/host-removal-lifecycle.test.ts index 3dca9514362..6c96ef1c446 100644 --- a/mobile/src/transport/host-removal-lifecycle.test.ts +++ b/mobile/src/transport/host-removal-lifecycle.test.ts @@ -17,12 +17,6 @@ vi.mock('./host-store', () => ({ })) import { removeHostAndCloseClient } from './host-removal-lifecycle' -import { - getSessionTabStripCacheKey, - readCachedSessionTabStrip, - resetSessionTabStripCacheForTests, - saveCachedSessionTabStrip -} from '../cache/session-tab-strip-cache' import { getHostNotificationSession, resetHostNotificationSessionsForTests @@ -33,7 +27,6 @@ describe('host removal lifecycle', () => { removeHostMock.mockReset() asyncStorage.removeItem.mockClear() resetHostNotificationSessionsForTests() - resetSessionTabStripCacheForTests() }) it('closes the client only after metadata removal commits', async () => { @@ -95,25 +88,4 @@ describe('host removal lifecycle', () => { expect(asyncStorage.removeItem).toHaveBeenCalledWith('orca:mobileNotificationsWatermark:host-1') }) - - it('drops the removed host cached tab strip and keeps every other host', async () => { - // Why: the strip is plaintext and nothing else in the app ever expires an entry, so a - // forgotten host would keep its tab titles on disk and get them rewritten by the next - // save for any surviving host. - removeHostMock.mockResolvedValue(undefined) - const removed = getSessionTabStripCacheKey('host-1', 'wt-1') - const kept = getSessionTabStripCacheKey('host-2', 'wt-1') - const strip = { - tabs: [{ id: 'tab-1', type: 'terminal' as const, title: 'Terminal', agentId: null }], - activeTabId: 'tab-1' - } - saveCachedSessionTabStrip(removed, strip) - saveCachedSessionTabStrip(kept, strip) - - await removeHostAndCloseClient('host-1', vi.fn()) - // Fire-and-forget, like clearWatermark above; let its microtasks land. - await vi.waitFor(() => expect(readCachedSessionTabStrip(removed)).toBeNull()) - - expect(readCachedSessionTabStrip(kept)?.tabs).toHaveLength(1) - }) }) diff --git a/mobile/src/transport/host-removal-lifecycle.ts b/mobile/src/transport/host-removal-lifecycle.ts index 3883cfb9140..cd0a09cb67e 100644 --- a/mobile/src/transport/host-removal-lifecycle.ts +++ b/mobile/src/transport/host-removal-lifecycle.ts @@ -1,4 +1,3 @@ -import { deleteCachedSessionTabStripForHost } from '../cache/session-tab-strip-cache' import { clearWatermark, forgetHostNotificationSession @@ -18,7 +17,4 @@ export async function removeHostAndCloseClient( // re-pair of the same host would inherit a watermark for a counter it never saw. forgetHostNotificationSession(hostId) void clearWatermark(hostId) - // Why: the cached tab strip is plaintext and host-scoped, so forgetting the host has to drop - // it here too — nothing else in the app ever expires an entry. - void deleteCachedSessionTabStripForHost(hostId) } diff --git a/mobile/src/transport/mobile-direct-return-probe.ts b/mobile/src/transport/mobile-direct-return-probe.ts index ac84f35ae86..3ae31edd07f 100644 --- a/mobile/src/transport/mobile-direct-return-probe.ts +++ b/mobile/src/transport/mobile-direct-return-probe.ts @@ -26,7 +26,6 @@ export class DirectReturnProbe { host: () => HostProfile canSchedule: () => boolean canAttempt: () => boolean - // Takes the supervisor's operation mutex, now held for the cutover only. beginOperation: () => void migrate: ( client: RpcClient, @@ -71,12 +70,9 @@ export class DirectReturnProbe { } const controller = new AbortController() this.activeProbe = controller - let owned = false + this.hooks.beginOperation() let successful: Awaited> = null try { - // Why: the dial is a pure observation on its own socket — holding the - // supervisor's mutex across its 12s budget stalled every relay recovery - // that landed during a foreground return. Only the cutover needs the mutex. successful = await openAuthenticatedDirectEndpoint( this.hooks.host(), this.deps.openDirect, @@ -90,18 +86,10 @@ export class DirectReturnProbe { this.hooks.hysteresis.recordDirectFailure(this.deps.now()) return } - // Both early returns leave the candidate to the finally, which owns it until - // migration takes over — closing here too would double-close it. if (!this.hooks.hysteresis.recordDirectSuccess(this.deps.now())) { + successful.client.close() return } - if (!this.hooks.canAttempt()) { - // A relay dial owns the mutex; the streak survives, so the next probe - // promotes direct instead of this one. - return - } - this.hooks.beginOperation() - owned = true const candidate = successful // Migration owns the candidate, including closing it if cutover is canceled. successful = null @@ -121,11 +109,9 @@ export class DirectReturnProbe { } finally { this.activeProbe = null successful?.client.close() - // Why: a relay drop or backoff timer can arrive while the cutover owns the + // Why: a relay drop or backoff timer can arrive while the probe owns the // operation mutex; afterProbe releases it and replays deferred recovery. - if (owned) { - this.hooks.afterProbe() - } + this.hooks.afterProbe() this.schedule() } } diff --git a/mobile/src/transport/mobile-endpoint-lifecycle.ts b/mobile/src/transport/mobile-endpoint-lifecycle.ts index 1542de9da7d..7ec5f28b945 100644 --- a/mobile/src/transport/mobile-endpoint-lifecycle.ts +++ b/mobile/src/transport/mobile-endpoint-lifecycle.ts @@ -86,7 +86,7 @@ function createSupervisor( ): MobileEndpointSupervisor { return new MobileEndpointSupervisor(logical, host, { openDirect: (endpoint) => connect(endpoint, host.deviceToken, host.publicKeyB64, { onLog }), - openRelay: (relay, credential, confirmReqId, onHostCloseReason, isForeground) => + openRelay: (relay, credential, confirmReqId, onHostCloseReason) => connectMobileRelayRpcSession({ relay, resumeToken: credential.token, @@ -94,7 +94,6 @@ function createSupervisor( resumeConfirmReqId: confirmReqId, deviceToken: host.deviceToken, desktopPublicKeyB64: host.publicKeyB64, - isForeground, onHostCloseReason, onLog }), diff --git a/mobile/src/transport/mobile-endpoint-supervisor-contract.ts b/mobile/src/transport/mobile-endpoint-supervisor-contract.ts index 29ec807e649..2a784fd8895 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor-contract.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor-contract.ts @@ -12,9 +12,7 @@ export type MobileEndpointSupervisorDependencies = { relay: MobileRelayEndpoint, credential: { token: string; version: number }, confirmReqId: string, - onHostCloseReason?: (reason: RelayHostCloseReason) => void, - // Gates the session's idle liveness sweep; a backgrounded app spends no probes. - isForeground?: () => boolean + onHostCloseReason?: (reason: RelayHostCloseReason) => void ) => MobileRelayRpcSession resolveRelay: typeof resolveMobileRelayEndpoint readBundle: (hostId: string) => Promise diff --git a/mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts b/mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts index 0e8f32ee5e3..3ee52fc7ddf 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.ts @@ -1,6 +1,5 @@ import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' import { MobileEndpointSupervisor } from './mobile-endpoint-supervisor' -import { MobileEndpointHysteresis } from './mobile-endpoint-hysteresis' import { dependencies, FakeLogicalClient, @@ -9,17 +8,6 @@ import { host } from './mobile-endpoint-supervisor-test-fakes' -// A cell that authenticates and then answers the confirm for a different relay host -// — what a rehomed desktop produces. The session fails after the logical cutover. -function confirmRejectingRelaySession(logical: FakeLogicalClient): FakeRelaySession { - const session = new FakeRelaySession('connected', new Error('relay resume confirmation missing')) - session.whenResumeConfirmed = async () => { - session.publishState('disconnected') - logical.publishState('disconnected') - } - return session -} - vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' })) vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) })) @@ -60,98 +48,4 @@ describe('mobile endpoint supervisor direct probe', () => { expect(logical.getActivePath()).toBe('relay') supervisor.stop() }) - - it('recovers the relay at once while the probe is still dialing direct', async () => { - const logical = new FakeLogicalClient('connected', 'relay') - // A black-holed LAN endpoint: the dial sits unanswered for its whole 12s budget. - const direct = new FakeSession('connecting') - const openRelay = vi.fn(() => new FakeRelaySession('connected')) - const deps = dependencies({ openDirect: vi.fn(() => direct), openRelay }) - const supervisor = new MobileEndpointSupervisor(logical, host, deps) - await supervisor.start() - - await vi.advanceTimersByTimeAsync(15_000) - expect(deps.openDirect).toHaveBeenCalledOnce() - logical.publishState('disconnected') - await vi.advanceTimersByTimeAsync(0) - - // Why: the dial is a pure observation, so it no longer owns the operation - // mutex — recovery does not wait out the probe's budget. - expect(openRelay).toHaveBeenCalledOnce() - expect(logical.getState()).toBe('connected') - expect(logical.getActivePath()).toBe('relay') - supervisor.stop() - }) - - it('backs off a dial whose resume confirm fails after the cutover', async () => { - const recordMigration = vi.spyOn(MobileEndpointHysteresis.prototype, 'recordMigration') - const logical = new FakeLogicalClient('disconnected', 'lan') - const openRelay = vi.fn(() => confirmRejectingRelaySession(logical)) - const deps = dependencies({ openRelay, randomBytes: () => new Uint8Array([128, 0]) }) - const supervisor = new MobileEndpointSupervisor(logical, host, deps) - - await supervisor.start() - // Two sockets per pass: a confirm mismatch reads as a stale cell assignment, so - // the existing director fallback re-resolves and dials the authoritative target. - expect(openRelay).toHaveBeenCalledTimes(2) - expect(logical.migrateTo).toHaveBeenCalledTimes(2) - - // Why: `connected` is published at authentication, so the cutover happens before - // the confirm answers. A confirm that then fails must still book the shared - // cooldown — reporting it as an established dial redials in a tight loop. - await vi.advanceTimersByTimeAsync(0) - expect(openRelay).toHaveBeenCalledTimes(2) - - // 250ms, then 500ms, then 1000ms: the streak grows instead of resetting, which - // it could not do if setActiveSession had run for this dying session. - await vi.advanceTimersByTimeAsync(249) - expect(openRelay).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1) - expect(openRelay).toHaveBeenCalledTimes(4) - await vi.advanceTimersByTimeAsync(250) - expect(openRelay).toHaveBeenCalledTimes(4) - await vi.advanceTimersByTimeAsync(250) - expect(openRelay).toHaveBeenCalledTimes(6) - await vi.advanceTimersByTimeAsync(999) - expect(openRelay).toHaveBeenCalledTimes(6) - await vi.advanceTimersByTimeAsync(1) - expect(openRelay).toHaveBeenCalledTimes(8) - - // No session whose confirm failed is ever booked as a migration. - expect(recordMigration).not.toHaveBeenCalled() - supervisor.stop() - }) - - it('replays a relay recovery that landed while the direct cutover owned the mutex', async () => { - const logical = new FakeLogicalClient('connected', 'relay') - const openRelay = vi.fn(() => new FakeRelaySession('connected')) - const deps = dependencies({ openDirect: vi.fn(() => new FakeSession('connected')), openRelay }) - const supervisor = new MobileEndpointSupervisor(logical, host, deps) - await supervisor.start() - - let release!: () => void - const cutover = new Promise((resolve) => { - release = resolve - }) - // The candidate loses the cutover, so the logical client stays on the relay path. - logical.migrateTo.mockImplementationOnce(async (candidate) => { - await cutover - candidate.close() - }) - // Three authenticated probes plus the observation and dwell windows. - await vi.advanceTimersByTimeAsync(60_000) - expect(logical.migrateTo).toHaveBeenCalledOnce() - - logical.publishState('disconnected') - await vi.advanceTimersByTimeAsync(0) - expect(openRelay).not.toHaveBeenCalled() - - release() - await vi.advanceTimersByTimeAsync(0) - - // The queued request is replayed by afterProbe, never dropped. - expect(openRelay).toHaveBeenCalledOnce() - expect(logical.getState()).toBe('connected') - supervisor.stop() - }) }) diff --git a/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts b/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts index cc4d91ea9da..80f4438c160 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts @@ -65,7 +65,6 @@ export class FakeRelaySession extends FakeSession implements MobileRelayRpcSessi renewed: this.renewed, resumeExpiresAt: this.resumeExpiry }) - whenResumeConfirmed = () => Promise.resolve() getFailure = () => this.failure } diff --git a/mobile/src/transport/mobile-endpoint-supervisor.test.ts b/mobile/src/transport/mobile-endpoint-supervisor.test.ts index 028387d8232..10ef892a479 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor.test.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor.test.ts @@ -189,7 +189,6 @@ describe('mobile endpoint supervisor', () => { resolved, expect.any(Object), expect.any(String), - expect.any(Function), expect.any(Function) ) expect(deps.saveHost).toHaveBeenCalledWith( @@ -563,7 +562,6 @@ describe('mobile endpoint supervisor', () => { relay, expect.objectContaining({ version: 3 }), expect.any(String), - expect.any(Function), expect.any(Function) ) supervisor.stop() @@ -612,7 +610,6 @@ describe('mobile endpoint supervisor', () => { relay, expect.objectContaining({ version: 3 }), expect.any(String), - expect.any(Function), expect.any(Function) ) supervisor.stop() diff --git a/mobile/src/transport/mobile-endpoint-supervisor.ts b/mobile/src/transport/mobile-endpoint-supervisor.ts index 372fd7372a2..9ba12f35112 100644 --- a/mobile/src/transport/mobile-endpoint-supervisor.ts +++ b/mobile/src/transport/mobile-endpoint-supervisor.ts @@ -16,7 +16,6 @@ import { } from './mobile-relay-credential-rotation' import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle' import { MobileEndpointNudgeRouter } from './mobile-endpoint-nudge-router' -import { RelayRecoveryIntentQueue } from './relay-recovery-intent-queue' import { MobileRelayDirectGraceTimer } from './mobile-relay-direct-grace-timer' import { MobileRelaySessionEstablisher } from './mobile-relay-session-establisher' import * as recoveryPresentation from './mobile-relay-recovery-presentation' @@ -39,7 +38,7 @@ export class MobileEndpointSupervisor { private bundle: MobileRelayCredentialBundle | null = null private stopped = false private operationInFlight = false - private readonly pending = new RelayRecoveryIntentQueue() + private pendingReplace = false private readonly nudgeRouter: MobileEndpointNudgeRouter private credentialRotationInFlight = false private relayRotationPending = false @@ -129,8 +128,11 @@ export class MobileEndpointSupervisor { }, afterProbe: () => { this.operationInFlight = false - const queued = this.pending.takeRecovery() || this.pending.hasReplacement() - if (queued || this.relayRotationPending || this.logical.getState() !== 'connected') { + if ( + this.pendingReplace || + this.relayRotationPending || + this.logical.getState() !== 'connected' + ) { void this.recoverRelay(this.relayRotationPending) } } @@ -193,7 +195,6 @@ export class MobileEndpointSupervisor { stop(): void { this.stopped = true - this.pending.clear() this.directProbe.stop() this.unsubscribeState?.() this.unsubscribeState = null @@ -214,14 +215,13 @@ export class MobileEndpointSupervisor { return } if (this.operationInFlight) { - // Why: a direct cutover or a slow post-migration write can own the mutex when - // a handoff lands. Every request is queued — an owning replacement keeps its - // force/owns intent, anything else replays as a plain recovery — so the - // holder's release replays it instead of dropping it. - this.pending.queue(forceReplacement, ownsRecovery) + // Why: a 12s direct probe can own the mutex when a network handoff lands; + // afterProbe replays the queued replacement so the signal is never lost. + this.pendingReplace ||= forceReplacement && ownsRecovery return } - if (this.pending.takeReplacement()) { + if (this.pendingReplace) { + this.pendingReplace = false forceReplacement = true ownsRecovery = true } @@ -236,7 +236,7 @@ export class MobileEndpointSupervisor { if (ownsRecovery) { // Why: never tear down a session no dial has disproven — the intent stays // queued so the armed retry runs forced once the cooldown lapses. - this.pending.holdReplacement() + this.pendingReplace = true } this.logRelay('recovery deferred by cooldown or gate') return @@ -260,7 +260,7 @@ export class MobileEndpointSupervisor { if (ownsRecovery) { // Why: no dial happened — keep the session and the intent; the reprobe // runs forced and replaces make-before-break once a credential exists. - this.pending.holdReplacement() + this.pendingReplace = true } return } @@ -273,7 +273,7 @@ export class MobileEndpointSupervisor { const dialed = await this.sessionEstablisher.dialEligible(selection.credentials) if (dialed.outcome === 'established') { // Why: a fresh socket satisfies any replacement intent queued mid-dial. - this.pending.clearReplacement() + this.pendingReplace = false retryAfterOperation = this.logical.getState() !== 'connected' return } @@ -293,12 +293,11 @@ export class MobileEndpointSupervisor { } } finally { this.operationInFlight = false - const queued = this.pending.takeRecovery() if (forceReplacement && this.relayRotationPending && this.isActive()) { this.leaseRotation.armRetry(this.relayReconnect.retryDelayMs(5000)) } // Why: the active relay can drop while migration follow-up still owns the mutex. - if ((retryAfterOperation || queued) && this.isActive()) { + if (retryAfterOperation && this.isActive()) { void this.recoverRelay() } } diff --git a/mobile/src/transport/mobile-relay-credential-rotation.ts b/mobile/src/transport/mobile-relay-credential-rotation.ts index ef2630c8a67..9b8a038e8e4 100644 --- a/mobile/src/transport/mobile-relay-credential-rotation.ts +++ b/mobile/src/transport/mobile-relay-credential-rotation.ts @@ -142,15 +142,11 @@ export async function persistResumeConfirmation(args: { session: { getResumeConfirmation(): DeviceResumeConfirmed | null getResumeExpiresAt(): number | null - whenResumeConfirmed(): Promise } bundle: MobileRelayCredentialBundle usedCredentialVersion: number writeBundle: (bundle: MobileRelayCredentialBundle) => Promise }): Promise<{ bundle: MobileRelayCredentialBundle; leaseExpiry: number | null }> { - // Why: 'connected' is published at E2EE authentication now, so the confirm round - // trip can still be in flight here — its answer is what makes the bundle durable. - await args.session.whenResumeConfirmed() const confirmation = args.session.getResumeConfirmation() let bundle = args.bundle if (confirmation) { diff --git a/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts b/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts index fb8d2b5ffea..b811721e562 100644 --- a/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts +++ b/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts @@ -32,10 +32,7 @@ const relay = { e2eeFraming: 2 as const } -async function authenticateSession( - onLog?: ConnectionLogSink, - isForeground: () => boolean = () => true -) { +async function authenticateSession(onLog?: ConnectionLogSink) { const session = connectMobileRelayRpcSession({ relay, resumeToken: 'resume-secret', @@ -44,7 +41,6 @@ async function authenticateSession( deviceToken: 'device-token', desktopPublicKeyB64: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', requestTimeoutMs: 30_000, - isForeground, onLog }) fakes.linkOptions!.onHello({ @@ -56,12 +52,12 @@ async function authenticateSession( acceptedAs: 'current', resumeExpiresAt: Date.now() + 300_000 }) - // Authentication publishes 'connected' and puts both advisories on the wire. fakes.linkOptions!.onAuthenticated() - const [confirmation, capabilities] = sentRequests() + await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) + const confirmation = sentRequests()[0]! fakes.linkOptions!.onText( JSON.stringify({ - id: confirmation!.id, + id: confirmation.id, ok: true, result: { v: 1, @@ -78,16 +74,17 @@ async function authenticateSession( _meta: { runtimeId: 'runtime-1' } }) ) + await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledTimes(2)) + const capabilities = sentRequests()[1]! fakes.linkOptions!.onText( JSON.stringify({ - id: capabilities!.id, + id: capabilities.id, ok: true, result: {}, _meta: { runtimeId: 'runtime-1' } }) ) - await session.whenResumeConfirmed() - expect(session.getState()).toBe('connected') + await vi.waitFor(() => expect(session.getState()).toBe('connected')) fakes.sendText.mockClear() return session } @@ -98,13 +95,6 @@ function sentRequests(): Array<{ id: string; method: string }> { ) } -function answerProbe(): void { - const probe = sentRequests().at(-1)! - fakes.linkOptions!.onText( - JSON.stringify({ id: probe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } }) - ) -} - describe('mobile relay RPC session liveness', () => { beforeEach(() => { vi.useFakeTimers() @@ -114,66 +104,16 @@ describe('mobile relay RPC session liveness', () => { }) afterEach(() => vi.useRealTimers()) - it('sweeps an idle foregrounded relay once per idle interval', async () => { + it('sends no periodic traffic while an authenticated relay is idle', async () => { const session = await authenticateSession() - await vi.advanceTimersByTimeAsync(24_999) - expect(fakes.sendText).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1) - expect(sentRequests().map(({ method }) => method)).toEqual(['status.get']) - answerProbe() - - // Inbound traffic re-arms the sweep rather than stacking probes on it. - await vi.advanceTimersByTimeAsync(24_999) - expect(fakes.sendText).toHaveBeenCalledOnce() - await vi.advanceTimersByTimeAsync(1) - expect(fakes.sendText).toHaveBeenCalledTimes(2) - expect(session.getState()).toBe('connected') - session.close() - }) - - it('spends no idle probe while the app is backgrounded', async () => { - let foreground = true - const session = await authenticateSession(undefined, () => foreground) - foreground = false - - await vi.advanceTimersByTimeAsync(120_000) + await vi.advanceTimersByTimeAsync(60_000) expect(fakes.sendText).not.toHaveBeenCalled() expect(session.getState()).toBe('connected') - - // The resume that follows probes at once instead of waiting out the sweep. - foreground = true - session.notifyForeground('app-resume') - expect(sentRequests().map(({ method }) => method)).toEqual(['status.get']) session.close() }) - it('terminates a relay whose socket died in the background on two 2s resume misses', async () => { - const onLog = vi.fn() - const session = await authenticateSession(onLog) - - session.notifyForeground('app-resume') - expect(fakes.sendText).toHaveBeenCalledOnce() - // Why: the first frame after a resume rides a cold radio, so one slow answer is - // tolerated — but the verdict still lands at 4s instead of the old 8s. - await vi.advanceTimersByTimeAsync(2_000) - expect(session.getState()).toBe('connected') - expect(fakes.sendText).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1_999) - expect(session.getState()).toBe('connected') - await vi.advanceTimersByTimeAsync(1) - - expect(session.getState()).toBe('disconnected') - expect(fakes.close).toHaveBeenCalledOnce() - expect(onLog).toHaveBeenCalledWith( - expect.objectContaining({ - code: 'liveness-timeout', - detail: expect.stringMatching(/^probe-timeout; 2\/2 probes missed;/) - }) - ) - }) - it('disconnects after two fair foreground misses', async () => { const onLog = vi.fn() const session = await authenticateSession(onLog) @@ -221,25 +161,22 @@ describe('mobile relay RPC session liveness', () => { expect(secondId).not.toBe(firstId) }) - it('rate-limits focus nudges but never an app resume', async () => { + it('rate-limits foreground sequences without suppressing a retry', async () => { const session = await authenticateSession() session.notifyForeground('focus') - answerProbe() + const firstProbe = sentRequests()[0]! + fakes.linkOptions!.onText( + JSON.stringify({ id: firstProbe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } }) + ) session.notifyForeground('focus') await vi.advanceTimersByTimeAsync(9_999) - expect(fakes.sendText).toHaveBeenCalledOnce() - - // The resume owns the only evidence that the suspended socket is still alive. session.notifyForeground('app-resume') - expect(fakes.sendText).toHaveBeenCalledTimes(2) - answerProbe() - session.notifyForeground('focus') - expect(fakes.sendText).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(10_000) + expect(fakes.sendText).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(1) session.notifyForeground('focus') - expect(fakes.sendText).toHaveBeenCalledTimes(3) + expect(fakes.sendText).toHaveBeenCalledTimes(2) session.close() }) @@ -252,9 +189,9 @@ describe('mobile relay RPC session liveness', () => { session.close() }) - it('does not probe when work follows inbound silence', async () => { + it('does not probe when work follows prolonged inbound silence', async () => { const session = await authenticateSession() - await vi.advanceTimersByTimeAsync(20_000) + await vi.advanceTimersByTimeAsync(60_000) const pending = session.sendRequest('terminal.send', { terminal: 'term', text: 'hi' }) const outcome = pending.catch(() => undefined) diff --git a/mobile/src/transport/mobile-relay-rpc-session.test.ts b/mobile/src/transport/mobile-relay-rpc-session.test.ts index b4861ec3fc6..4bf617faf50 100644 --- a/mobile/src/transport/mobile-relay-rpc-session.test.ts +++ b/mobile/src/transport/mobile-relay-rpc-session.test.ts @@ -22,10 +22,6 @@ const fakes = vi.hoisted(() => ({ close: vi.fn() })) -vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) -vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' })) -vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) })) - vi.mock('./mobile-relay-e2ee-link', () => ({ MobileRelayE2eeLink: class { constructor(options: NonNullable) { @@ -37,8 +33,6 @@ vi.mock('./mobile-relay-e2ee-link', () => ({ })) import { connectMobileRelayRpcSession } from './mobile-relay-rpc-session' -import { persistResumeConfirmation } from './mobile-relay-credential-rotation' -import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle' const relay = { v: 1 as const, @@ -49,13 +43,6 @@ const relay = { e2eeFraming: 2 as const } -type SentRequest = { - id: string - method: string - deviceToken: string - params: Record | undefined -} - function openSession() { return connectMobileRelayRpcSession({ relay, @@ -68,11 +55,8 @@ function openSession() { }) } -function sentRequests(): SentRequest[] { - return fakes.sendText.mock.calls.map(([value]) => JSON.parse(value as string) as SentRequest) -} - -function receiveHello(): void { +async function confirmResume() { + const session = openSession() fakes.linkOptions!.onHello({ type: 'relay-hello', ok: true, @@ -82,31 +66,21 @@ function receiveHello(): void { acceptedAs: 'current', resumeExpiresAt: Date.now() + 300_000 }) -} - -// E2EE authentication alone publishes 'connected'; the confirm and the capability -// advisory are already on the wire by the time it returns. -function authenticateSession() { - const session = openSession() - receiveHello() expect(session.getState()).toBe('handshaking') fakes.linkOptions!.onAuthenticated() - const [confirmationRequest, capabilityRequest] = sentRequests() - return { - session, - confirmationRequest: confirmationRequest!, - capabilityRequest: capabilityRequest! + await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) + const request = JSON.parse(fakes.sendText.mock.calls[0]![0] as string) as { + id: string + method: string + params: unknown } -} - -function answerConfirm(request: SentRequest, relayHostId = relay.relayHostId): void { fakes.linkOptions!.onText( JSON.stringify({ id: request.id, ok: true, result: { v: 1, - relay: { ...relay, relayHostId }, + relay, resumeConfirmation: { v: 1, reqId: 'confirm-1', @@ -119,32 +93,39 @@ function answerConfirm(request: SentRequest, relayHostId = relay.relayHostId): v _meta: { runtimeId: 'runtime-1' } }) ) + await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledTimes(2)) + const capabilityRequest = JSON.parse(fakes.sendText.mock.calls[1]![0] as string) as { + id: string + method: string + deviceToken: string + params: { clientCapabilities?: string[] } + } + return { session, confirmationRequest: request, capabilityRequest } } -function answerCapability(request: SentRequest, supported = true): void { +async function authenticateSession(capabilitySupported = true) { + const { session, confirmationRequest, capabilityRequest } = await confirmResume() + expect(session.getState()).toBe('handshaking') fakes.linkOptions!.onText( JSON.stringify( - supported - ? { id: request.id, ok: true, result: request.params, _meta: { runtimeId: 'runtime-1' } } + capabilitySupported + ? { + id: capabilityRequest.id, + ok: true, + result: capabilityRequest.params, + _meta: { runtimeId: 'runtime-1' } + } : { - id: request.id, + id: capabilityRequest.id, ok: false, error: { code: 'method_not_found', message: 'Unknown method' }, _meta: { runtimeId: 'runtime-1' } } ) ) -} - -// Both advisories answered and the send log cleared, so a test can read its own frames. -async function settledSession(capabilitySupported = true) { - const authenticated = authenticateSession() - answerConfirm(authenticated.confirmationRequest) - answerCapability(authenticated.capabilityRequest, capabilitySupported) - await authenticated.session.whenResumeConfirmed() - expect(authenticated.session.getState()).toBe('connected') + await vi.waitFor(() => expect(session.getState()).toBe('connected')) fakes.sendText.mockClear() - return authenticated + return { session, confirmationRequest, capabilityRequest } } describe('mobile relay RPC session', () => { @@ -156,7 +137,7 @@ describe('mobile relay RPC session', () => { afterEach(() => vi.useRealTimers()) it('releases stream listeners on failure even when close follows it', async () => { - const { session } = await settledSession() + const { session } = await authenticateSession() const listener = vi.fn() session.subscribe('runtime.clientEvents.subscribe', {}, listener) await Promise.resolve() @@ -185,8 +166,8 @@ describe('mobile relay RPC session', () => { expect(listener).toHaveBeenCalledTimes(1) }) - it('sends the resume confirm by request ID and the capability advisory concurrently', async () => { - const { session, confirmationRequest, capabilityRequest } = await settledSession() + it('requires exact resume observations and confirms by request ID before becoming connected', async () => { + const { session, confirmationRequest, capabilityRequest } = await authenticateSession() expect(fakes.linkOptions).toMatchObject({ endpoint: relay, @@ -211,103 +192,21 @@ describe('mobile relay RPC session', () => { }) it('connects when an older runtime rejects capability negotiation', async () => { - const { session } = await settledSession(false) + const { session } = await authenticateSession(false) expect(session.getState()).toBe('connected') expect(session.getFailure()).toBeNull() }) it('connects when the relay never answers capability negotiation', async () => { - const { session, confirmationRequest } = authenticateSession() - answerConfirm(confirmationRequest) + const { session } = await confirmResume() - // Why: the advisory's own deadline used to fail the confirm, so a link too slow to + // Why: the advisory's own deadline used to fail confirmResume, so a link too slow to // answer within the request timeout never published 'connected' — it just redialled. - await session.whenResumeConfirmed() - expect(session.getState()).toBe('connected') + await vi.waitFor(() => expect(session.getState()).toBe('connected'), { timeout: 5_000 }) expect(session.getFailure()).toBeNull() }) - it('publishes connected at authentication, ahead of the confirm answer', async () => { - const states: string[] = [] - const session = openSession() - session.onStateChange((state) => states.push(state)) - receiveHello() - fakes.linkOptions!.onAuthenticated() - - // Why: the transport carries traffic from here; two serialized advisory round - // trips used to add ~200ms to every phone reconnect before anything rendered. - expect(session.getState()).toBe('connected') - expect(states).toEqual(['handshaking', 'connected']) - expect(session.getResumeConfirmation()).toBeNull() - expect(sentRequests().map(({ method }) => method)).toEqual([ - 'pairing.getEndpoints', - 'runtime.clientCapabilities.update' - ]) - - const [confirmationRequest] = sentRequests() - answerConfirm(confirmationRequest!) - await session.whenResumeConfirmed() - expect(session.getResumeConfirmation()).toMatchObject({ reqId: 'confirm-1' }) - session.close() - }) - - it('fails a session whose confirm answers for another relay host after connected', async () => { - const { session, confirmationRequest } = authenticateSession() - expect(session.getState()).toBe('connected') - - answerConfirm(confirmationRequest, 'ZZZZZZZZZZZZZZZZ') - await session.whenResumeConfirmed() - - // A late failure is fine; a lost one is not. - expect(session.getState()).toBe('disconnected') - expect(session.getFailure()?.message).toBe('relay resume confirmation missing') - expect(fakes.close).toHaveBeenCalledOnce() - }) - - it('fails a session whose confirm never answers', async () => { - vi.useFakeTimers() - try { - const { session } = authenticateSession() - expect(session.getState()).toBe('connected') - - await vi.advanceTimersByTimeAsync(1_000) - - expect(session.getState()).toBe('disconnected') - expect(session.getFailure()?.message).toBe('relay RPC timed out: pairing.getEndpoints') - } finally { - vi.useRealTimers() - } - }) - - it('hands the landed confirmation to resume persistence', async () => { - const { session, confirmationRequest } = authenticateSession() - const bundle: MobileRelayCredentialBundle = { - v: 1, - hostId: 'host-1', - deviceToken: 'device-token', - current: { token: 'A'.repeat(43), hash: 'B'.repeat(43), version: 3, expiresAt: 1 } - } - const writeBundle = vi.fn(async () => {}) - // Why: persistence runs right after the migration, while the confirm is still - // in flight — it must wait for the answer instead of reading a null. - const persisting = persistResumeConfirmation({ - session, - bundle, - usedCredentialVersion: 3, - writeBundle - }) - expect(writeBundle).not.toHaveBeenCalled() - - answerConfirm(confirmationRequest) - const applied = await persisting - - expect(writeBundle).toHaveBeenCalledOnce() - expect(applied.bundle.current.expiresAt).toBe(session.getResumeExpiresAt()) - expect(applied.leaseExpiry).toBe(session.getResumeExpiresAt()) - session.close() - }) - // Why: ConnectionState stays 'connecting' until relay-hello, so the migration bound // needs a separate signal to tell "cell never answered the upgrade" from "cell took // relay-auth and is still resolving the assignment". @@ -332,7 +231,7 @@ describe('mobile relay RPC session', () => { expect(session.getDialStage()).toBe('handshaking') fakes.linkOptions!.onAuthenticated() expect(session.getDialStage()).toBe('confirming') - expect(fakes.sendText).toHaveBeenCalledTimes(2) + await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) expect(stages).toEqual(['awaiting-hello', 'handshaking', 'confirming']) session.close() }) @@ -355,7 +254,7 @@ describe('mobile relay RPC session', () => { }) it('routes terminal and browser binary streams after confirmation', async () => { - const { session } = await settledSession() + const { session } = await authenticateSession() const terminalListener = vi.fn() session.subscribe('terminal.subscribe', { terminal: 'term-1' }, terminalListener) await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) @@ -412,7 +311,7 @@ describe('mobile relay RPC session', () => { }) it('rejects pending RPC work when the physical link fails', async () => { - const { session } = await settledSession() + const { session } = await authenticateSession() const pending = session.sendRequest('status.get') await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) fakes.linkOptions!.onError(new Error('relay transport error')) @@ -424,7 +323,7 @@ describe('mobile relay RPC session', () => { }) it('marks in-flight requests delivery-unknown when the session closes', async () => { - const { session } = await settledSession() + const { session } = await authenticateSession() const pending = session.sendRequest('terminal.send', { terminal: 'term', text: 'hi' }) await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce()) session.close() @@ -434,7 +333,7 @@ describe('mobile relay RPC session', () => { }) it('marks a relay RPC timeout delivery-unknown', async () => { - const { session } = await settledSession() + const { session } = await authenticateSession() vi.useFakeTimers() try { const pending = session.sendRequest('terminal.send', { terminal: 'term', text: 'hi' }) diff --git a/mobile/src/transport/mobile-relay-rpc-session.ts b/mobile/src/transport/mobile-relay-rpc-session.ts index f74aaadefaa..67b50ea591e 100644 --- a/mobile/src/transport/mobile-relay-rpc-session.ts +++ b/mobile/src/transport/mobile-relay-rpc-session.ts @@ -17,17 +17,9 @@ import type { RelayHostCloseReason } from '../../../src/shared/relay-host-close- import type { RpcClient } from './rpc-client' import type { ConnectionLogSink, ConnectionState, RpcResponse } from './types' -// Ordinary foreground checks: two 4s misses, at most one voluntary probe per 10s. -const RELAY_PROBE = { timeoutMs: 4_000, missedProbeLimit: 2, minIntervalMs: 10_000 } -// A socket that died while the process was suspended must be admitted before the -// user reads the screen as broken. Two 2s misses, not one: the first frame after a -// resume rides a cold radio, and a single slow answer is not proof of a dead link. -const RELAY_RESUME_PROBE = { timeoutMs: 2_000, missedProbeLimit: 2 } -// Bounds the confirm exactly as migrateTo's own wait used to, so the supervisor's -// mutex is never held for the full request timeout waiting on a silent cell. -const RELAY_CONFIRM_TIMEOUT_MS = 12_000 -// Foreground-only sweep so a silently-dead relay surfaces without a user action. -const RELAY_IDLE_PROBE_MS = 25_000 +const RELAY_PROBE_TIMEOUT_MS = 4_000 +const RELAY_MISSED_PROBE_LIMIT = 2 +const RELAY_FOREGROUND_PROBE_MIN_INTERVAL_MS = 10_000 let relayRpcSessionSequence = 0 export type MobileRelayRpcSession = RpcClient & @@ -37,10 +29,6 @@ export type MobileRelayRpcSession = RpcClient & getAttachDeadlineAt(): number | null getResumeExpiresAt(): number | null getResumeConfirmation(): DeviceResumeConfirmed | null - // Settles once the resume confirm has answered or failed the session. Never - // rejects. Anyone reading getResumeConfirmation()/getResumeExpiresAt() must - // await it: 'connected' is published at authentication, ahead of the confirm. - whenResumeConfirmed(): Promise getFailure(): Error | null } @@ -52,8 +40,6 @@ export function connectMobileRelayRpcSession(args: { deviceToken: string desktopPublicKeyB64: string requestTimeoutMs?: number - // Gates the idle liveness sweep; a backgrounded app must not spend probes. - isForeground?: () => boolean createSocket?: (url: string) => WebSocket onHostCloseReason?: (reason: RelayHostCloseReason) => void onLog?: ConnectionLogSink @@ -66,7 +52,6 @@ export function connectMobileRelayRpcSession(args: { let attachDeadlineAt: number | null = null let resumeExpiresAt: number | null = null let resumeConfirmation: DeviceResumeConfirmed | null = null - let resumeConfirmed: Promise | null = null let failure: Error | null = null let closed = false let logSequence = 0 @@ -101,7 +86,7 @@ export function connectMobileRelayRpcSession(args: { dialStage.advance('handshaking') publishState('handshaking') }, - onAuthenticated: () => publishAuthenticated(), + onAuthenticated: () => void confirmResume(), onText: (plaintext) => { livenessWatchdog.noteAuthenticatedInbound(livenessIdentity) handleText(plaintext) @@ -140,7 +125,7 @@ export function connectMobileRelayRpcSession(args: { }, notifyForeground: (reason) => { if (state === 'connected' && reason !== 'network-change') { - livenessWatchdog.probeNow(livenessIdentity, reason === 'app-resume' ? 'resume' : 'nudge') + livenessWatchdog.probeNow(livenessIdentity) } }, close() { @@ -159,18 +144,14 @@ export function connectMobileRelayRpcSession(args: { getAttachDeadlineAt: () => attachDeadlineAt, getResumeExpiresAt: () => resumeExpiresAt, getResumeConfirmation: () => resumeConfirmation, - whenResumeConfirmed: () => resumeConfirmed ?? Promise.resolve(), getFailure: () => failure } const livenessWatchdog = new RpcSessionLivenessWatchdog({ transport: 'relay', - idleProbeMs: RELAY_IDLE_PROBE_MS, - probeTimeoutMs: RELAY_PROBE.timeoutMs, - missedProbeLimit: RELAY_PROBE.missedProbeLimit, - voluntaryProbeMinIntervalMs: RELAY_PROBE.minIntervalMs, - urgentProbeTimeoutMs: RELAY_RESUME_PROBE.timeoutMs, - urgentMissedProbeLimit: RELAY_RESUME_PROBE.missedProbeLimit, - shouldIdleProbe: () => args.isForeground?.() ?? true, + idleProbeMs: null, + probeTimeoutMs: RELAY_PROBE_TIMEOUT_MS, + missedProbeLimit: RELAY_MISSED_PROBE_LIMIT, + voluntaryProbeMinIntervalMs: RELAY_FOREGROUND_PROBE_MIN_INTERVAL_MS, sendProbe: () => state === 'connected' && sendFrame({ id: pending.nextId(), method: 'status.get', params: undefined }), @@ -189,33 +170,13 @@ export function connectMobileRelayRpcSession(args: { }) return client - // Why: the transport carries traffic the moment E2EE authenticates. The resume - // confirm and the capability advisory ride it concurrently instead of putting - // two serialized round trips in front of 'connected'. - function publishAuthenticated(): void { - if (closed) { - return - } - dialStage.advance('confirming') - resumeConfirmed = confirmResume() - // Why: an unanswered advisory says nothing, but a frame that never reached the - // wire proves the socket cannot carry traffic — that alone still fails. - void settleMobileRuntimeCapabilities((method, params) => - sendRpc(method, params, requestTimeoutMs, true) - ).catch((error: unknown) => fail(asError(error))) - lastConnectedAt = Date.now() - livenessWatchdog.start(livenessIdentity) - publishState('connected') - } - - // Off the critical path but never optional: a failed confirm or a relayHostId - // that is not ours still fails the session, only later than it used to. async function confirmResume(): Promise { + dialStage.advance('confirming') try { const response = await sendRpc( 'pairing.getEndpoints', { resumeConfirmReqId: args.resumeConfirmReqId }, - Math.min(requestTimeoutMs, RELAY_CONFIRM_TIMEOUT_MS), + requestTimeoutMs, true ) if (!response.ok) { @@ -227,6 +188,13 @@ export function connectMobileRelayRpcSession(args: { } resumeConfirmation = result.resumeConfirmation resumeExpiresAt = result.resumeConfirmation.resumeExpiresAt + lastConnectedAt = Date.now() + // Why: an unanswered advisory must not keep a slow relay from ever reaching connected. + await settleMobileRuntimeCapabilities((method, params) => + sendRpc(method, params, requestTimeoutMs, true) + ) + livenessWatchdog.start(livenessIdentity) + publishState('connected') } catch (error) { fail(asError(error)) } diff --git a/mobile/src/transport/mobile-relay-runtime-failover.test.ts b/mobile/src/transport/mobile-relay-runtime-failover.test.ts index 7098746587a..ce7cca3fd9f 100644 --- a/mobile/src/transport/mobile-relay-runtime-failover.test.ts +++ b/mobile/src/transport/mobile-relay-runtime-failover.test.ts @@ -88,7 +88,6 @@ class FakeRelaySession extends FakeSession implements MobileRelayRpcSession { this.dialStage.onDialStageChange(listener) getResumeExpiresAt = () => Date.now() + 30 * 24 * 3_600_000 getResumeConfirmation = () => null - whenResumeConfirmed = () => Promise.resolve() getFailure = () => this.failure } @@ -278,7 +277,6 @@ describe('relay runtime recovery without direct connectivity', () => { relay, expect.objectContaining({ version: 3 }), expect.any(String), - expect.any(Function), expect.any(Function) ) expect(logical.getActivePath()).toBe('relay') @@ -369,7 +367,6 @@ describe('relay runtime recovery without direct connectivity', () => { relay, expect.objectContaining({ version: 2 }), expect.any(String), - expect.any(Function), expect.any(Function) ) expect(logical.getActivePath()).toBe('relay') @@ -400,7 +397,6 @@ describe('relay runtime recovery without direct connectivity', () => { relay, expect.objectContaining({ version: 1 }), expect.any(String), - expect.any(Function), expect.any(Function) ) expect(logical.getActivePath()).toBe('relay') diff --git a/mobile/src/transport/mobile-relay-session-establisher.ts b/mobile/src/transport/mobile-relay-session-establisher.ts index 9ec8ebb3a37..9a04ae44137 100644 --- a/mobile/src/transport/mobile-relay-session-establisher.ts +++ b/mobile/src/transport/mobile-relay-session-establisher.ts @@ -110,8 +110,7 @@ export class MobileRelaySessionEstablisher { if (reason === RELAY_HOST_CLOSE_REASON.SIGNED_OUT) { args.logical.setHostSignedOut(true) } - }, - args.isForeground + } ) try { // Why: backgrounding or a direct winner withdraws this dial before cutover. @@ -127,17 +126,6 @@ export class MobileRelaySessionEstablisher { } return { ok: false, error: session.getFailure() ?? toError(error) } } - // Why: migrateTo now resolves at E2EE authentication, so the resume confirm can - // still fail this session after the cutover. Booking a dying session as an - // established dial skips backoff and redials in a tight loop — the supervisor's - // bookkeeping waits for the verdict even though the UI is already connected. - await session.whenResumeConfirmed() - if (session.getState() !== 'connected') { - if (!args.isActive() || directWon(args.logical)) { - return { ok: false, error: new RelayDialAbortedError() } - } - return { ok: false, error: session.getFailure() ?? new Error('relay lost at confirm') } - } args.controller.setActiveSession(session) if (!args.isForeground()) { args.controller.suspendActiveRelay(args.logical) diff --git a/mobile/src/transport/relay-recovery-intent-queue.ts b/mobile/src/transport/relay-recovery-intent-queue.ts deleted file mode 100644 index c34e40b8990..00000000000 --- a/mobile/src/transport/relay-recovery-intent-queue.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Recovery requests that arrive while the supervisor's operation mutex is held. -// Two latches, because the intents are not interchangeable: an owning forced -// replacement books the shared cooldown and may bring a stale session down, while -// every other request must replay as a plain recovery. Nothing is ever dropped. -export class RelayRecoveryIntentQueue { - private replacement = false - private recovery = false - - queue(forceReplacement: boolean, ownsRecovery: boolean): void { - if (forceReplacement && ownsRecovery) { - this.replacement = true - return - } - this.recovery = true - } - - holdReplacement(): void { - this.replacement = true - } - - hasReplacement(): boolean { - return this.replacement - } - - clearReplacement(): void { - this.replacement = false - } - - takeReplacement(): boolean { - const queued = this.replacement - this.replacement = false - return queued - } - - takeRecovery(): boolean { - const queued = this.recovery - this.recovery = false - return queued - } - - clear(): void { - this.replacement = false - this.recovery = false - } -} diff --git a/mobile/src/transport/rpc-session-liveness-watchdog.ts b/mobile/src/transport/rpc-session-liveness-watchdog.ts index b54aa0679b6..36525f60fb0 100644 --- a/mobile/src/transport/rpc-session-liveness-watchdog.ts +++ b/mobile/src/transport/rpc-session-liveness-watchdog.ts @@ -13,19 +13,11 @@ type WatchdogOptions = { probeTimeoutMs?: number missedProbeLimit?: number voluntaryProbeMinIntervalMs?: number - // Bounds for probeImmediately(); default to the ordinary probe bounds. - urgentProbeTimeoutMs?: number - urgentMissedProbeLimit?: number - // Gates the idle sweep only. False re-arms without probing — a backgrounded app - // must not spend a probe, and its resume probes immediately anyway. - shouldIdleProbe?: () => boolean now?: () => number setTimer?: typeof setTimeout clearTimer?: typeof clearTimeout } -type ProbeProfile = { timeoutMs: number; missedProbeLimit: number } - export type LivenessTimeoutEvidence = { transport: 'direct' | 'relay' reason: 'probe-send-failed' | 'probe-timeout' @@ -41,10 +33,9 @@ export class RpcSessionLivenessWatchdog { private missedProbes = 0 private lastInboundAt = 0 private lastVoluntaryProbeAt: number | null = null - private profile: ProbeProfile private readonly idleProbeMs: number | null - private readonly ordinaryProfile: ProbeProfile - private readonly urgentProfile: ProbeProfile + private readonly probeTimeoutMs: number + private readonly missedProbeLimit: number private readonly voluntaryProbeMinIntervalMs: number private readonly now: () => number private readonly setTimer: typeof setTimeout @@ -52,15 +43,8 @@ export class RpcSessionLivenessWatchdog { constructor(private readonly options: WatchdogOptions) { this.idleProbeMs = options.idleProbeMs === undefined ? LIVENESS_IDLE_MS : options.idleProbeMs - this.ordinaryProfile = { - timeoutMs: options.probeTimeoutMs ?? LIVENESS_PROBE_TIMEOUT_MS, - missedProbeLimit: options.missedProbeLimit ?? MISSED_PROBE_LIMIT - } - this.urgentProfile = { - timeoutMs: options.urgentProbeTimeoutMs ?? this.ordinaryProfile.timeoutMs, - missedProbeLimit: options.urgentMissedProbeLimit ?? this.ordinaryProfile.missedProbeLimit - } - this.profile = this.ordinaryProfile + this.probeTimeoutMs = options.probeTimeoutMs ?? LIVENESS_PROBE_TIMEOUT_MS + this.missedProbeLimit = options.missedProbeLimit ?? MISSED_PROBE_LIMIT this.voluntaryProbeMinIntervalMs = options.voluntaryProbeMinIntervalMs ?? 0 this.now = options.now ?? Date.now this.setTimer = options.setTimer ?? setTimeout @@ -74,7 +58,6 @@ export class RpcSessionLivenessWatchdog { this.missedProbes = 0 this.lastInboundAt = this.now() this.lastVoluntaryProbeAt = null - this.profile = this.ordinaryProfile this.armIdle(identity) } @@ -104,24 +87,19 @@ export class RpcSessionLivenessWatchdog { this.armIdle(identity) } - // 'resume' is evidence the socket may have died while the process was suspended: - // it ignores the voluntary minimum, runs on the urgent bounds, and replaces any - // probe already in flight so the verdict lands on the short clock. - probeNow(identity: RpcSessionIdentity, urgency: 'nudge' | 'resume' = 'nudge'): void { - const urgent = urgency === 'resume' - if (this.identity !== identity || (this.probing && !urgent)) { + probeNow(identity: RpcSessionIdentity): void { + if (this.identity !== identity || this.probing) { return } const now = this.now() if ( - !urgent && this.lastVoluntaryProbeAt !== null && now - this.lastVoluntaryProbeAt < this.voluntaryProbeMinIntervalMs ) { return } this.lastVoluntaryProbeAt = now - this.startProbe(identity, urgent ? this.urgentProfile : this.ordinaryProfile) + this.startProbe(identity) } stop(identity: RpcSessionIdentity): void { @@ -134,7 +112,6 @@ export class RpcSessionLivenessWatchdog { this.missedProbes = 0 this.lastInboundAt = 0 this.lastVoluntaryProbeAt = null - this.profile = this.ordinaryProfile } private armIdle(identity: RpcSessionIdentity, delayMs = this.idleProbeMs): void { @@ -147,10 +124,6 @@ export class RpcSessionLivenessWatchdog { if (this.identity !== identity) { return } - if (this.options.shouldIdleProbe && !this.options.shouldIdleProbe()) { - this.armIdle(identity) - return - } const idleMs = this.now() - this.lastInboundAt if (this.idleProbeMs !== null && idleMs < this.idleProbeMs) { this.armIdle(identity, Math.max(1, this.idleProbeMs - Math.max(0, idleMs))) @@ -160,12 +133,11 @@ export class RpcSessionLivenessWatchdog { }, delayMs) } - private startProbe(identity: RpcSessionIdentity, profile = this.ordinaryProfile): void { + private startProbe(identity: RpcSessionIdentity): void { if (this.identity !== identity) { return } this.clearActiveTimer() - this.profile = profile this.probing = true const sentAt = this.now() let sent = false @@ -178,7 +150,7 @@ export class RpcSessionLivenessWatchdog { this.terminateCurrent(identity, 'probe-send-failed') return } - this.timer = this.setTimer(() => this.handleProbeTimeout(identity, sentAt), profile.timeoutMs) + this.timer = this.setTimer(() => this.handleProbeTimeout(identity, sentAt), this.probeTimeoutMs) } private handleProbeTimeout(identity: RpcSessionIdentity, sentAt: number): void { @@ -186,28 +158,27 @@ export class RpcSessionLivenessWatchdog { if (this.identity !== identity) { return } - const profile = this.profile const elapsedMs = this.now() - sentAt - if (elapsedMs < 0 || elapsedMs > profile.timeoutMs * 1.5) { + if (elapsedMs < 0 || elapsedMs > this.probeTimeoutMs * 1.5) { console.log('[net] activity-probe unfair window skipped', { transport: this.options.transport, elapsedMs, - timeoutMs: profile.timeoutMs + timeoutMs: this.probeTimeoutMs }) - this.startProbe(identity, profile) + this.startProbe(identity) return } this.missedProbes += 1 - if (this.missedProbes >= profile.missedProbeLimit) { + if (this.missedProbes >= this.missedProbeLimit) { this.terminateCurrent(identity, 'probe-timeout') return } console.log('[net] activity-probe timeout tolerated', { transport: this.options.transport, missedProbes: this.missedProbes, - missedProbeLimit: profile.missedProbeLimit + missedProbeLimit: this.missedProbeLimit }) - this.startProbe(identity, profile) + this.startProbe(identity) } private terminateCurrent( @@ -223,13 +194,13 @@ export class RpcSessionLivenessWatchdog { console.log('[net] activity-probe TIMEOUT — forcing reconnect', { transport: this.options.transport, missedProbes: this.missedProbes, - missedProbeLimit: this.profile.missedProbeLimit + missedProbeLimit: this.missedProbeLimit }) this.options.onTimeout?.({ transport: this.options.transport, reason, missedProbes: this.missedProbes, - missedProbeLimit: this.profile.missedProbeLimit, + missedProbeLimit: this.missedProbeLimit, lastInboundAgeMs: Math.max(0, this.now() - this.lastInboundAt) }) this.options.terminate(identity) diff --git a/mobile/src/transport/unpaired-host-credential-deletion.test.ts b/mobile/src/transport/unpaired-host-credential-deletion.test.ts deleted file mode 100644 index cd6ebe4a2fd..00000000000 --- a/mobile/src/transport/unpaired-host-credential-deletion.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const asyncStorage = vi.hoisted(() => ({ - getItem: vi.fn(async () => null), - setItem: vi.fn(async () => undefined), - removeItem: vi.fn(async () => undefined) -})) -const deletions = vi.hoisted(() => ({ - deviceToken: vi.fn(async () => undefined), - credentialBundle: vi.fn(async () => undefined), - directUpgradeJournal: vi.fn(async () => undefined), - clearWriteRevision: vi.fn() -})) - -vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) -vi.mock('./host-device-token-store', () => ({ deleteHostDeviceToken: deletions.deviceToken })) -vi.mock('./mobile-relay-credential-bundle', () => ({ - deleteMobileRelayCredentialBundle: deletions.credentialBundle -})) -vi.mock('./mobile-relay-direct-upgrade-journal', () => ({ - deleteMobileRelayDirectUpgradeJournal: deletions.directUpgradeJournal -})) -vi.mock('./host-credential-write-revision', () => ({ - clearHostCredentialWriteRevision: deletions.clearWriteRevision, - getHostCredentialWriteRevision: () => 0 -})) - -import { createUnpairedHostCredentialDeletion } from './unpaired-host-credential-deletion' -import { - getSessionTabStripCacheKey, - readCachedSessionTabStrip, - resetSessionTabStripCacheForTests, - saveCachedSessionTabStrip -} from '../cache/session-tab-strip-cache' - -const strip = { - tabs: [{ id: 'tab-1', type: 'terminal' as const, title: 'Terminal', agentId: null }], - activeTabId: 'tab-1' -} - -function createDeletion(storedHostIds: string[] = []) { - return createUnpairedHostCredentialDeletion({ - waitForHostMutations: async () => undefined, - hasStoredHost: async (hostId) => storedHostIds.includes(hostId), - onDeleted: vi.fn() - }) -} - -beforeEach(() => { - asyncStorage.getItem.mockClear() - asyncStorage.setItem.mockClear() - for (const mock of Object.values(deletions)) { - mock.mockClear() - } - resetSessionTabStripCacheForTests() -}) - -describe('unpaired host credential deletion', () => { - it('takes the cached tab strip with the credentials, leaving other hosts alone', async () => { - // Why: the strip is not a credential, but it is host-scoped plaintext written from the - // session screen. Without this sweep it outlives the pairing that produced it. - const unpaired = getSessionTabStripCacheKey('host-1', 'wt-1') - const other = getSessionTabStripCacheKey('host-2', 'wt-1') - saveCachedSessionTabStrip(unpaired, strip) - saveCachedSessionTabStrip(other, strip) - - await createDeletion()('host-1', 0) - - expect(readCachedSessionTabStrip(unpaired)).toBeNull() - expect(readCachedSessionTabStrip(other)?.tabs).toHaveLength(1) - }) - - it('leaves the strip alone when the host turned out to still be paired', async () => { - const stillPaired = getSessionTabStripCacheKey('host-1', 'wt-1') - saveCachedSessionTabStrip(stillPaired, strip) - - await createDeletion(['host-1'])('host-1', 0) - - expect(readCachedSessionTabStrip(stillPaired)?.tabs).toHaveLength(1) - expect(deletions.deviceToken).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/transport/unpaired-host-credential-deletion.ts b/mobile/src/transport/unpaired-host-credential-deletion.ts index 06220824b78..cc9c27e49ad 100644 --- a/mobile/src/transport/unpaired-host-credential-deletion.ts +++ b/mobile/src/transport/unpaired-host-credential-deletion.ts @@ -1,4 +1,3 @@ -import { deleteCachedSessionTabStripForHost } from '../cache/session-tab-strip-cache' import { deleteHostDeviceToken } from './host-device-token-store' import { clearHostCredentialWriteRevision, @@ -53,13 +52,6 @@ export function createUnpairedHostCredentialDeletion(dependencies: DeletionDepen return } assertWriteRevisionUnchanged(hostId, writeRevision) - // The cached tab strip is not a credential, but it is host-scoped plaintext that outlives - // the pairing unless this sweep takes it too. - await deleteCachedSessionTabStripForHost(hostId) - if (await shouldSkip(hostId, writeRevision)) { - return - } - assertWriteRevisionUnchanged(hostId, writeRevision) clearHostCredentialWriteRevision(hostId) dependencies.onDeleted(hostId) } From db13cff8324020ff652412645a3b4bb1413dcfdd Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 05:03:26 -0400 Subject: [PATCH 12/37] relay: give the asia-east2 cells the regional rehome identity (#19239) `relay_region_rehome_source_cell_ids` listed only the 16 US cells, and that list is the sole thing that stamps ORCA_RELAY_REHOME_DIRECTOR_SERVICE_ACCOUNT and ORCA_RELAY_REHOME_AUDIENCE into a cell's startup script. A cell reports regionalRehomeProtocol 1 only when both are present, so c27-c29 have always reported 0. That leaves them ineligible as rehome sources and, once the worker is bidirectional, as targets too, which strands the US desktops homed there. This is a prerequisite only. Merge and roll it ONLY AFTER the bidirectional rehome director change is deployed. Two live gates still hard-code the primary region and would reject an Asia source no matter what the template stamps: `cloud/apps/relay/src/app.ts` line 610 fails the trust probe with 409 when the source cell's region is not RELAY_DEFAULT_REGION, and `cloud/apps/relay/src/assignment-store.ts` line 5476 skips such a cell as source_ineligible during rehome source selection. The bidirectional lane removes both. The topology check asserted every source sits in the primary region. That mirrored those two gates rather than protecting anything Terraform owns, so it is now advisory: it requires only a configured, unfenced cell with an explicit connection limit, and the comment records that region eligibility belongs to the director's own source and target predicates. Every cell's region is already constrained by the assert above it. The same-cap census test cross-checked membership against us-central1. Every reviewed serving cell now carries the trust, so it asserts protocol 1 for all, plus one non-source cell to keep the validator's protocol-0 branch covered. Roll sequencing, because this apply is not self-contained: - After the apply the Asia templates carry the two rehome lines, and the `unexpectedRehome` rule at `cloud/dev/scripts/validate-relay-capacity-plan.mjs` lines 243-247 rejects a protocol-0 plan that contains them. So c27-c29 have no dispatchable protocol-0 same-cap roll until the director gate is gone or this is reverted. - The same-cap job runs the per-host trust probe after isolate, drain, and the targeted apply. A 409 there leaves the cell serving but isolated and migration-only, which is what happened to c13 on 2026-09-06. - The only safe path: deploy the bidirectional rehome director, then dispatch `Deploy Relay Production Same-Cap` canary-apply for one Asia cell with target-rehome-protocol 1 and rollback-rehome-protocol 0, then batch-apply the remaining two. That job runs its own targeted template and MIG apply. - Never reach these cells with an untargeted root apply. The current plan carries 60 changes and 50 destroys of unrelated standing drift. --- .../relay-same-cap-script-census.test.mjs | 28 +++++++++++++++++-- .../terraform/environments/production.tfvars | 6 +++- cloud/infra/terraform/relay-gce-cells.tf | 5 ++-- cloud/infra/terraform/variables.tf | 2 +- 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/cloud/dev/scripts/relay-same-cap-script-census.test.mjs b/cloud/dev/scripts/relay-same-cap-script-census.test.mjs index 743aef7fc2d..7d5e4fee73e 100644 --- a/cloud/dev/scripts/relay-same-cap-script-census.test.mjs +++ b/cloud/dev/scripts/relay-same-cap-script-census.test.mjs @@ -179,9 +179,10 @@ describe('same-cap roll scripts accept every same-cap cell', () => { it('validates a correct plan for every wave cell at that cell\'s rehome protocol', () => { for (const cellId of SAME_CAP_CELLS) { - const [region, cap] = resolveCellShape(cellId).stdout.trim().split(' ') + const [, cap] = resolveCellShape(cellId).stdout.trim().split(' ') const protocol = REHOME_SOURCE_CELLS.has(cellId) ? 1 : 0 - assert.equal(protocol, region === 'us-central1' ? 1 : 0, cellId) + // Every reviewed serving cell carries rehome trust now, in either region. + assert.equal(protocol, 1, cellId) const config = { mode: 'same-cap-cell', cellId, @@ -211,6 +212,29 @@ describe('same-cap roll scripts accept every same-cap cell', () => { } }) + it('validates a protocol-0 plan for a cell outside the rehome source list', () => { + const cellId = 'production-gce-c17' + assert.equal(REHOME_SOURCE_CELLS.has(cellId), false) + const config = { + mode: 'same-cap-cell', + cellId, + hardCap: 1000, + unobservedBound: 60, + image: TARGET_IMAGE, + rollbackImage: ROLLBACK_IMAGE, + rehomeDirectorServiceAccount: DIRECTOR_IDENTITY, + rehomeAudience: AUDIENCE, + regionalRehomeProtocol: '0' + } + const plan = rollPlan({ cellId, cap: 1000, protocol: 0 }) + assert.deepEqual(validateCapacityPlan(plan, config), { mode: 'same-cap-cell', changes: 2 }) + // Protocol 1 must reject a plan with no rehome lines, or the absent-line rule decides nothing. + assert.throws( + () => validateCapacityPlan(plan, { ...config, regionalRehomeProtocol: '1' }), + /reviewed image and capacity/ + ) + }) + it('leaves the US-only capacity job on the default allowlist', () => { assert.doesNotMatch(capacityWorkflow, /--approved-cells/) }) diff --git a/cloud/infra/terraform/environments/production.tfvars b/cloud/infra/terraform/environments/production.tfvars index 8e442c75900..e1522b3827e 100644 --- a/cloud/infra/terraform/environments/production.tfvars +++ b/cloud/infra/terraform/environments/production.tfvars @@ -402,7 +402,11 @@ relay_region_rehome_source_cell_ids = [ "production-gce-c23", "production-gce-c24", "production-gce-c25", - "production-gce-c26" + "production-gce-c26", + # Asia cells carry the same trust so mis-homed hosts can be drained back off them. + "production-gce-c27", + "production-gce-c28", + "production-gce-c29" ] # Slack #orca-relay-alerts, created out of band on 2026-08-05. Declared here because an apply diff --git a/cloud/infra/terraform/relay-gce-cells.tf b/cloud/infra/terraform/relay-gce-cells.tf index a4505ba2e37..5023b7e1d50 100644 --- a/cloud/infra/terraform/relay-gce-cells.tf +++ b/cloud/infra/terraform/relay-gce-cells.tf @@ -82,14 +82,15 @@ check "relay_gce_fixed_one_topology" { assert { condition = alltrue([ + # Region is not asserted here: the director's own rehome source and target predicates + # own eligibility, so this pins only cell shape. for cell_id in var.relay_region_rehome_source_cell_ids : try( - var.relay_gce_cells[cell_id].region == var.region && var.relay_gce_cells[cell_id].connection_hard_cap != null && !contains(var.relay_gce_fenced_cells, cell_id), false ) ]) - error_message = "Regional rehome sources must be configured, unfenced primary-region GCE cells with explicit connection limits." + error_message = "Regional rehome sources must be configured, unfenced GCE cells with explicit connection limits." } assert { diff --git a/cloud/infra/terraform/variables.tf b/cloud/infra/terraform/variables.tf index 91f67e8ebe0..57d73fe75b4 100644 --- a/cloud/infra/terraform/variables.tf +++ b/cloud/infra/terraform/variables.tf @@ -245,7 +245,7 @@ variable "relay_regional_placement_enabled" { variable "relay_region_rehome_source_cell_ids" { type = set(string) - description = "Reviewed US Relay cells allowed to advertise and accept the regional rehome source protocol." + description = "Reviewed Relay cells, in any configured region, allowed to advertise and accept the regional rehome source protocol." default = [] } From 91d7783f2b1a91ed89c47c55c67b143a4bc54427 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 05:06:38 -0400 Subject: [PATCH 13/37] fix(relay): state pending-conn details to hosts that advertise the capability (cell side) (#19266) The cell announces a connection with a single conn-open. When the desktop's control socket dies mid-accept the phone waited out the 10s attach deadline and was closed HOST_OFFLINE, even though the desktop was online. host-hello-ack already restates those connections in pendingConns, but only by connId and connTicket, which is not enough for the desktop to dial: kind and relayDeviceId decide the pairing authority a connection carries and the E2EE device binding, so neither may be guessed. The cell now states kind and relayDeviceId on each pending entry, but only to a host that advertised it can read them: a shipped host parses those entries strictly, so an unannounced key fails the whole ack parse and kills a working control. The advertisement rides the control upgrade as x-orca-host-capabilities, not host-hello, because HostHelloSchema is strict on the cell too and any new hello key is refused by every already-deployed cell. The capability is keyed by socket, not by session: a rebind can land a successor whose decoder is older or newer than the one that opened the session, and the ack must follow the socket that will actually read it. With no capable host in the fleet the emitted ack is byte-identical to today's. The desktop half that consumes the new fields is #19238. --- .../relay/src/host-session-registry.test.ts | 113 ++++++++++++++++++ cloud/apps/relay/src/host-session-registry.ts | 22 +++- cloud/apps/relay/src/relay-server.ts | 5 +- .../relay-contract/src/contract.test.ts | 49 +++++++- .../relay-contract/src/control-messages.ts | 29 ++++- 5 files changed, 213 insertions(+), 5 deletions(-) diff --git a/cloud/apps/relay/src/host-session-registry.test.ts b/cloud/apps/relay/src/host-session-registry.test.ts index f632d5d4358..920faa6f4b8 100644 --- a/cloud/apps/relay/src/host-session-registry.test.ts +++ b/cloud/apps/relay/src/host-session-registry.test.ts @@ -3,6 +3,7 @@ import { ASSIGNMENT_LIMITS, CONTROL_CONTINUITY_LIMITS, RELAY_CLOSE_CODE, + RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS, RELAY_PROTOCOL_LIMITS } from '@orca-cloud/relay-contract' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -1005,3 +1006,115 @@ describe('control lease recovery after the session is gone', () => { } }) }) + +describe('host hello ack pending connections', () => { + const DETAILS = new Set([RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS]) + const LEGACY_ENTRY = { connId: 'conn-1', connTicket: 'T'.repeat(43) } + const DETAILED_ENTRY = { ...LEGACY_ENTRY, kind: 'invite', relayDeviceId: 'device-1' } + + beforeEach(() => vi.useFakeTimers()) + afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + }) + + function newRegistry(): ReturnType { + return createRegistry( + vi + .fn() + .mockResolvedValue('control:production-gce-c3:1') + ) + } + + function addPendingConnection(session: HostSession): void { + session.pendingConns.set('conn-1', { + ...LEGACY_ENTRY, + reservation: { + userId: identity.sub, + relayHostId: identity.relayHostId, + credentialKind: 'invite', + relayDeviceId: 'device-1' + }, + client: new FakeSocket() as unknown as WebSocket, + attachTimer: setTimeout(() => {}, 60_000), + credentialActivityId: null + } as unknown as Parameters[1]) + } + + function sentAck(socket: FakeSocket): Record { + const acks = socket.send.mock.calls + .map((call) => JSON.parse(String(call[0])) as Record) + .filter((message) => message.type === 'host-hello-ack') + return acks.at(-1)! + } + + function sessionOf(registry: HostSessionRegistry): HostSession { + return registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })! + } + + async function ackFor(capabilities?: ReadonlySet): Promise> { + const { registry, activate } = newRegistry() + const socket = new FakeSocket() + registry.acceptControl( + socket as unknown as WebSocket, + identity, + undefined, + capabilities ?? new Set() + ) + await activate(socket as unknown as WebSocket, identity, null, 1, false, 1) + const session = sessionOf(registry) + addPendingConnection(session) + socket.send.mockClear() + ;(registry as unknown as { sendHelloAck(session: HostSession): void }).sendHelloAck(session) + return sentAck(socket) + } + + async function ackAfterRebind( + first: ReadonlySet, + successor: ReadonlySet + ): Promise<{ opening: Record; rebound: Record }> { + const { registry, activate } = newRegistry() + const opening = new FakeSocket() + registry.acceptControl(opening as unknown as WebSocket, identity, undefined, first) + await activate(opening as unknown as WebSocket, identity, null, 1, false, 1) + const session = sessionOf(registry) + addPendingConnection(session) + opening.send.mockClear() + ;(registry as unknown as { sendHelloAck(session: HostSession): void }).sendHelloAck(session) + + const rebound = new FakeSocket() + registry.acceptControl(rebound as unknown as WebSocket, identity, undefined, successor) + await activate(rebound as unknown as WebSocket, identity, session, 1, true, 1) + return { opening: sentAck(opening), rebound: sentAck(rebound) } + } + + it('states the pending kind and device to a host that advertised it can read them', async () => { + const ack = await ackFor(DETAILS) + + expect(ack.pendingConns).toEqual([DETAILED_ENTRY]) + }) + + it('restates only the identifiers to a host that never advertised the capability', async () => { + // A shipped host parses these entries strictly, so an unannounced key fails + // the whole ack parse and kills a control that was working. + const ack = await ackFor() + + expect(ack.pendingConns).toEqual([LEGACY_ENTRY]) + }) + + it('downgrades the restated entry when the successor control drops the capability', async () => { + // The capability belongs to the socket, not the session: a rebind can land a + // control whose decoder is older than the one that opened the session. + const { opening, rebound } = await ackAfterRebind(DETAILS, new Set()) + + expect(opening.pendingConns).toEqual([DETAILED_ENTRY]) + expect(rebound.pendingConns).toEqual([LEGACY_ENTRY]) + }) + + it('upgrades the restated entry when the successor control adds the capability', async () => { + const { opening, rebound } = await ackAfterRebind(new Set(), DETAILS) + + expect(opening.pendingConns).toEqual([LEGACY_ENTRY]) + expect(rebound.pendingConns).toEqual([DETAILED_ENTRY]) + }) +}) diff --git a/cloud/apps/relay/src/host-session-registry.ts b/cloud/apps/relay/src/host-session-registry.ts index 9a3d27faf92..8f40bd6651c 100644 --- a/cloud/apps/relay/src/host-session-registry.ts +++ b/cloud/apps/relay/src/host-session-registry.ts @@ -14,6 +14,7 @@ import { HostChallengeAckSchema, HostHelloSchema, InviteCreateSchema, + RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS, RELAY_PROTOCOL_LIMITS, RELAY_CLOSE_CODE, type RelayHostCloseReason, @@ -178,6 +179,7 @@ export class HostSessionRegistry { // but a signed-out desktop never comes back, so the phone that asks minutes // later would otherwise find nothing to explain its rejection with. private readonly hostCloseReasons = new HostCloseReasonMemory(() => this.now()) + private readonly hostCapabilities = new WeakMap>() private draining = false constructor( @@ -552,8 +554,12 @@ export class HostSessionRegistry { acceptControl( socket: WebSocket, identity: RelayTokenClaims, - connectionInclusionWatermark?: number + connectionInclusionWatermark?: number, + hostCapabilities?: ReadonlySet ): void { + // Keyed by socket, not session: a rebind swaps the session's socket, and the + // successor's own advertisement is the only one that describes its decoder. + if (hostCapabilities?.size) this.hostCapabilities.set(socket, hostCapabilities) if (this.draining) { socket.close(RELAY_CLOSE_CODE.DRAINING, 'relay draining') return @@ -1177,6 +1183,12 @@ export class HostSessionRegistry { private sendHelloAck(session: HostSession): void { if (!session.socket) return + // Without these a host that missed the conn-open cannot dial the pending + // connection: it would have to guess the pairing kind and the device the + // relay authorized. Only sent to a host that said it can read them. + const details = this.hostCapabilities + .get(session.socket) + ?.has(RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS) send(session.socket, 'host-hello-ack', { v: 1, generation: session.generation, @@ -1185,7 +1197,13 @@ export class HostSessionRegistry { activeConnIds: [...session.activeConnIds], pendingConns: [...session.pendingConns.values()].map((pending) => ({ connId: pending.connId, - connTicket: pending.connTicket + connTicket: pending.connTicket, + ...(details + ? { + kind: pending.reservation.credentialKind, + relayDeviceId: pending.reservation.relayDeviceId + } + : {}) })) }) } diff --git a/cloud/apps/relay/src/relay-server.ts b/cloud/apps/relay/src/relay-server.ts index 6331b584b1b..77a15a1d259 100644 --- a/cloud/apps/relay/src/relay-server.ts +++ b/cloud/apps/relay/src/relay-server.ts @@ -2,7 +2,9 @@ import { createAdaptorServer } from '@hono/node-server' import { hasAdmissionCapacity, HostDataAuthSchema, + parseRelayHostCapabilities, RELAY_ADMISSION_BUDGETS, + RELAY_HOST_CAPABILITIES_HEADER, RELAY_CLOSE_CODE, RELAY_DEFAULT_REGION, RELAY_PROTOCOL_LIMITS, @@ -486,7 +488,8 @@ export function createRelayServer( sessions.acceptControl( webSocket, identity, - controlUpgrade?.inclusionWatermark + controlUpgrade?.inclusionWatermark, + parseRelayHostCapabilities(request.headers[RELAY_HOST_CAPABILITIES_HEADER]) ) }) } catch { diff --git a/cloud/packages/relay-contract/src/contract.test.ts b/cloud/packages/relay-contract/src/contract.test.ts index 805cb8ea698..391a0877c65 100644 --- a/cloud/packages/relay-contract/src/contract.test.ts +++ b/cloud/packages/relay-contract/src/contract.test.ts @@ -6,7 +6,10 @@ import { HostChallengeSchema, HostDataAuthSchema, HostHelloAckSchema, - HostHelloSchema + HostHelloSchema, + parseRelayHostCapabilities, + RELAY_HOST_CAPABILITIES_HEADER, + RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS } from './control-messages.js' import { DeviceCredentialInstallSchema, @@ -345,3 +348,47 @@ describe('relay protocol contract', () => { ).toBe(false) }) }) + +describe('pending connection details capability', () => { + it('reads a pending entry with or without the stated kind and device', () => { + const ack = { + v: 1 as const, + generation: 3, + controlResumeSecret: 'R'.repeat(43), + leaseExpiresAt: 1_800_000_000_000, + activeConnIds: [] + } + const identifiers = { connId: 'conn-1', connTicket: 'T'.repeat(43) } + expect(HostHelloAckSchema.safeParse({ ...ack, pendingConns: [identifiers] }).success).toBe(true) + expect( + HostHelloAckSchema.safeParse({ + ...ack, + pendingConns: [{ ...identifiers, kind: 'resume', relayDeviceId: 'device-1' }] + }).success + ).toBe(true) + // Still strict otherwise: an unannounced key must not slip through as data. + expect( + HostHelloAckSchema.safeParse({ + ...ack, + pendingConns: [{ ...identifiers, reservationId: 'injected' }] + }).success + ).toBe(false) + }) + + it('pins the header and token the desktop mirrors by hand', () => { + // The desktop cannot import this package; drift silently disables the + // feature, so both literals are asserted on each side. + expect(RELAY_HOST_CAPABILITIES_HEADER).toBe('x-orca-host-capabilities') + expect(RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS).toBe('pending-conn-details') + }) + + it('reads the advertised capabilities from a control upgrade header', () => { + expect( + parseRelayHostCapabilities(` ${RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS} , future-thing`) + ).toEqual(new Set([RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS, 'future-thing'])) + // A host that predates the header sends nothing; absence is never capable. + expect(parseRelayHostCapabilities(undefined).size).toBe(0) + expect(parseRelayHostCapabilities('').size).toBe(0) + expect(parseRelayHostCapabilities('x'.repeat(65)).size).toBe(0) + }) +}) diff --git a/cloud/packages/relay-contract/src/control-messages.ts b/cloud/packages/relay-contract/src/control-messages.ts index 0d5f8d1b851..0daf21e7c28 100644 --- a/cloud/packages/relay-contract/src/control-messages.ts +++ b/cloud/packages/relay-contract/src/control-messages.ts @@ -44,8 +44,35 @@ export const HostChallengeAckSchema = z .object({ challengeId: OpaqueIdSchema, proofB64: Base6432ByteSchema }) .strict() +// Advertised on the control upgrade rather than in host-hello: HostHelloSchema +// is strict, so a new hello key is refused by every already-deployed cell. +export const RELAY_HOST_CAPABILITIES_HEADER = 'x-orca-host-capabilities' +// The host accepts kind/relayDeviceId on a pendingConns entry. A host that does +// not advertise this parses those entries strictly and would drop the whole ack. +export const RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS = 'pending-conn-details' + +export function parseRelayHostCapabilities( + header: string | string[] | undefined +): ReadonlySet { + const raw = Array.isArray(header) ? header.join(',') : (header ?? '') + return new Set( + raw + .split(',') + .map((token) => token.trim()) + .filter((token) => token.length > 0 && token.length <= 64) + .slice(0, 16) + ) +} + +// kind/relayDeviceId are optional so an entry stays readable by a host that +// predates them; the cell only emits them to a host that advertised support. const PendingConnectionSchema = z - .object({ connId: OpaqueIdSchema, connTicket: Base64Url32ByteSchema }) + .object({ + connId: OpaqueIdSchema, + connTicket: Base64Url32ByteSchema, + kind: ConnectionKindSchema.optional(), + relayDeviceId: OpaqueIdSchema.optional() + }) .strict() export const HostHelloAckSchema = z From 9c8f4c398c3f8ba267cca14e0b65c3f6f87f2aa4 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 05:06:42 -0400 Subject: [PATCH 14/37] fix(relay): bound control RTT samples per ping and per flush window (#19268) * fix(relay): bound control RTT samples per ping and per flush window An authenticated host chose how many round-trip samples a cell recorded: every pong carrying a recent plausible `t` was forwarded to the process-wide window, which grew unbounded until the 30s flush copied and sorted it for percentiles. Time a pong only when it echoes the `t` of the ping still outstanding on that session, so a flood yields at most one sample per ping the cell actually sent. A pong that lost the race to the next ping is dropped for timing but still counts as proof of life for the silence watchdog. Bound the process-wide window with a 1024-sample reservoir (Algorithm R) so the percentiles stay unbiased, keep `controlRttSamplesDelta` meaning round trips observed, and publish `controlRttSamplesDroppedDelta` for the ones the reservoir did not keep. Replace the leak guard's blanket `"credential":` string rewrite with an exact, path-scoped rename of the two schema keys that spell a policed word, and make the guard case-insensitive now that nothing legitimate trips it. Follow-up to #19232. * test(relay): prove the RTT reservoir samples the whole window --- .../src/host-session-client-accept.test.ts | 82 +++++++++++++----- cloud/apps/relay/src/host-session-registry.ts | 14 ++- .../relay/src/relay-observability.test.ts | 85 +++++++++++++++++-- cloud/apps/relay/src/relay-observability.ts | 21 ++++- cloud/infra/terraform/relay-observability.tf | 3 +- 5 files changed, 170 insertions(+), 35 deletions(-) diff --git a/cloud/apps/relay/src/host-session-client-accept.test.ts b/cloud/apps/relay/src/host-session-client-accept.test.ts index 5beef7723f5..0cec6531e3f 100644 --- a/cloud/apps/relay/src/host-session-client-accept.test.ts +++ b/cloud/apps/relay/src/host-session-client-accept.test.ts @@ -413,6 +413,17 @@ describe('successful client accept timing', () => { }) }) +// Fires one heartbeat and returns the `t` of the ping it sent, which is the only +// echo the registry will time. +async function advanceToPing(control: FakeSocket, clock: { now: number }): Promise { + clock.now += RELAY_PROTOCOL_LIMITS.controlPingIntervalMs + await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) + const ping = control.send.mock.calls + .filter((call) => String(call[0]).includes('"type":"ping"')) + .at(-1)! + return (JSON.parse(String(ping[0])) as { t: number }).t +} + describe('control round-trip sampling', () => { beforeEach(() => vi.useFakeTimers()) afterEach(() => { @@ -421,8 +432,8 @@ describe('control round-trip sampling', () => { }) it('logs a host once at the fourth sample and not again within the hour', async () => { - let now = 1_700_000_000_000 - const h = harness({ now: () => now }) + const clock = { now: 1_700_000_000_000 } + const h = harness({ now: () => clock.now }) const control = await activeHost(h) const log = vi.spyOn(console, 'log').mockImplementation(() => undefined) const rttLines = (): string[] => @@ -431,17 +442,9 @@ describe('control round-trip sampling', () => { .filter((entry) => entry.includes('orca_relay_host_control_rtt')) // One heartbeat, then the desktop's echo of that ping's own `t` 40 ms later. const roundTrip = async (): Promise => { - now += RELAY_PROTOCOL_LIMITS.controlPingIntervalMs - await vi.advanceTimersByTimeAsync(RELAY_PROTOCOL_LIMITS.controlPingIntervalMs) - const ping = JSON.parse( - String( - control.send.mock.calls - .filter((call) => String(call[0]).includes('"type":"ping"')) - .at(-1)![0] - ) - ) as { t: number } - now += 40 - control.emit('message', JSON.stringify({ type: 'pong', t: ping.t }), false) + const pingAt = await advanceToPing(control, clock) + clock.now += 40 + control.emit('message', JSON.stringify({ type: 'pong', t: pingAt }), false) } try { for (let round = 0; round < 3; round++) await roundTrip() @@ -466,8 +469,8 @@ describe('control round-trip sampling', () => { expect(h.observer.recordControlRtt).toHaveBeenCalledTimes(12) expect(rttLines()).toHaveLength(1) - const elapsedStart = now - while (now - elapsedStart < 60 * 60 * 1000) await roundTrip() + const elapsedStart = clock.now + while (clock.now - elapsedStart < 60 * 60 * 1000) await roundTrip() expect(rttLines()).toHaveLength(2) } finally { log.mockRestore() @@ -476,25 +479,58 @@ describe('control round-trip sampling', () => { } }) - it('ignores a pong whose echoed timestamp is missing or implausible', async () => { - let now = 1_700_000_000_000 - const h = harness({ now: () => now }) + it('ignores a pong that answers no outstanding ping', async () => { + const clock = { now: 1_700_000_000_000 } + const h = harness({ now: () => clock.now }) const control = await activeHost(h) try { + // Nothing has been pinged yet, so even a plausible echo is not a round trip. control.emit('message', JSON.stringify({ type: 'pong' }), false) control.emit('message', JSON.stringify({ type: 'pong', t: 'later' }), false) - control.emit('message', JSON.stringify({ type: 'pong', t: now + 5_000 }), false) - control.emit('message', JSON.stringify({ type: 'pong', t: now - 600_000 }), false) + control.emit('message', JSON.stringify({ type: 'pong', t: clock.now }), false) + control.emit('message', JSON.stringify({ type: 'pong', t: clock.now - 10 }), false) expect(h.observer.recordControlRtt).not.toHaveBeenCalled() - // The silence watchdog still sees every one of them as proof of life. - now += 10 - control.emit('message', JSON.stringify({ type: 'pong', t: now - 10 }), false) + + const pingAt = await advanceToPing(control, clock) + // A guessed timestamp is not the outstanding ping's `t`, so it is dropped. + control.emit('message', JSON.stringify({ type: 'pong', t: pingAt - 1 }), false) + control.emit('message', JSON.stringify({ type: 'pong', t: pingAt + 1 }), false) + expect(h.observer.recordControlRtt).not.toHaveBeenCalled() + + clock.now += 10 + control.emit('message', JSON.stringify({ type: 'pong', t: pingAt }), false) expect(h.observer.recordControlRtt).toHaveBeenCalledWith(10) } finally { h.registry.drain(0) vi.advanceTimersByTime(0) } }) + + it('records one sample per ping however many pongs a host floods', async () => { + const clock = { now: 1_700_000_000_000 } + const h = harness({ now: () => clock.now }) + const control = await activeHost(h) + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined) + try { + const pingAt = await advanceToPing(control, clock) + clock.now += 12 + for (let flood = 0; flood < 5_000; flood++) { + control.emit('message', JSON.stringify({ type: 'pong', t: pingAt }), false) + control.emit('message', JSON.stringify({ type: 'pong', t: clock.now }), false) + } + // One answered ping is one process-wide sample and one per-session sample, so + // neither the metric window nor the hourly log line can be flooded. + expect(h.observer.recordControlRtt).toHaveBeenCalledTimes(1) + expect(h.observer.recordControlRtt).toHaveBeenCalledWith(12) + expect( + log.mock.calls.filter((call) => String(call[0]).includes('orca_relay_host_control_rtt')) + ).toHaveLength(0) + } finally { + log.mockRestore() + h.registry.drain(0) + vi.advanceTimersByTime(0) + } + }) }) describe('control lease jitter', () => { diff --git a/cloud/apps/relay/src/host-session-registry.ts b/cloud/apps/relay/src/host-session-registry.ts index 8f40bd6651c..3b4e616a692 100644 --- a/cloud/apps/relay/src/host-session-registry.ts +++ b/cloud/apps/relay/src/host-session-registry.ts @@ -90,6 +90,8 @@ export type HostSession = { orphanTimer: ReturnType | null heartbeatTimer: ReturnType | null lastPongAt: number + // The `t` of the ping still waiting for its echo; null once one has answered it. + pendingPingAt: number | null controlRttSamplesMs: number[] controlRttLoggedAt: number | null activityRenewalDueAt: number @@ -521,10 +523,13 @@ export class HostSessionRegistry { } } - // Every desktop build already echoes the ping's `t`; anything else is dropped - // rather than trusted, so no new wire field is required. + // Every desktop build already echoes the ping's `t`, so a pong is only timed when + // it answers the outstanding ping: at most one sample per ping this cell sent, + // however many a host floods. A pong that lost the race to the next ping is + // dropped here but still counts as proof of life for the silence watchdog. private recordControlRtt(session: HostSession, echoedPingAt: unknown): void { - if (typeof echoedPingAt !== 'number' || !Number.isFinite(echoedPingAt)) return + if (typeof echoedPingAt !== 'number' || echoedPingAt !== session.pendingPingAt) return + session.pendingPingAt = null const now = this.now() const rttMs = now - echoedPingAt if (rttMs < 0 || rttMs > CONTROL_RTT_MAX_PLAUSIBLE_MS) return @@ -918,6 +923,7 @@ export class HostSessionRegistry { existing.appVersion = appVersion existing.leaseExpiresAt = this.controlLeaseExpiresAt() existing.lastPongAt = this.now() + existing.pendingPingAt = null existing.activityRenewalDueAt = this.now() + RELAY_PROTOCOL_LIMITS.controlPingIntervalMs this.wireActiveControl(existing) @@ -971,6 +977,7 @@ export class HostSessionRegistry { orphanTimer: null, heartbeatTimer: null, lastPongAt: this.now(), + pendingPingAt: null, controlRttSamplesMs: [], controlRttLoggedAt: null, activityRenewalDueAt: this.now() + RELAY_PROTOCOL_LIMITS.controlPingIntervalMs, @@ -1178,6 +1185,7 @@ export class HostSessionRegistry { session.socket.close(RELAY_CLOSE_CODE.DRAINING, 'control lease expired') return } + session.pendingPingAt = now send(session.socket, 'ping', { t: now }) } diff --git a/cloud/apps/relay/src/relay-observability.test.ts b/cloud/apps/relay/src/relay-observability.test.ts index 22802b7f8aa..ea6734412be 100644 --- a/cloud/apps/relay/src/relay-observability.test.ts +++ b/cloud/apps/relay/src/relay-observability.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest' import type { RelayDatabase } from './database.js' import { observeRelayDatabase } from './observed-relay-database.js' import { + CONTROL_RTT_RESERVOIR_LIMIT, observedRelayRequests, RelayObservability, type RelayProcessCounts @@ -23,10 +24,35 @@ const counts: RelayProcessCounts = { databasePoolWaitMsMax: 1_250 } -// An accept stage is named `credential`, so the leak guard has to see past the -// bucket name to the values it exists to police. -function scrubStageNames(entries: Array>): string { - return JSON.stringify(entries).replaceAll('"credential":', '"stage":') +// Two schema keys legitimately spell a policed word: the abandoned-accept bucket +// is keyed by stage name and one stage is `credential`. Rename those exact keys in +// a clone instead of rewriting the JSON, so a stray raw field or value anywhere +// else still trips the guard below. +const SCHEMA_KEY_ALIASES: Record = { + clientAcceptCredentialMsP95: 'clientAcceptStageTwoMsP95' +} + +function scrubSchemaKeys(entries: Array>): string { + return JSON.stringify( + entries.map((entry) => + Object.fromEntries( + Object.entries(entry).map(([key, value]) => [ + SCHEMA_KEY_ALIASES[key] ?? key, + key === 'clientAcceptsAbandonedByStageDelta' ? renameStageKeys(value) : value + ]) + ) + ) + ) +} + +function renameStageKeys(bucket: unknown): unknown { + if (bucket === null || typeof bucket !== 'object') return bucket + return Object.fromEntries( + Object.entries(bucket).map(([stage, count]) => [ + stage === 'credential' ? 'stageTwo' : stage, + count + ]) + ) } describe('relay observability', () => { @@ -205,7 +231,7 @@ describe('relay observability', () => { controlActivityRecoveryFailuresDelta: 0, httpLatencyMsMax: 0 }) - expect(scrubStageNames(entries)).not.toMatch(/token|credential|userId|relayHostId/) + expect(scrubSchemaKeys(entries)).not.toMatch(/token|credential|userId|relayHostId/i) }) it('aggregates control and splice closes as bounded per-reason deltas', () => { @@ -300,7 +326,54 @@ describe('relay observability', () => { expect(entries[1]).not.toHaveProperty(omitted) expect(entries[0]).toHaveProperty(omitted) } - expect(scrubStageNames(entries)).not.toMatch(/token|credential|userId|relayHostId/) + expect(scrubSchemaKeys(entries)).not.toMatch(/token|credential|userId|relayHostId/i) + }) + + it('caps the control round-trip reservoir and reports what it dropped', () => { + const entries: Array> = [] + const observability = new RelayObservability( + { role: 'cell', cellId: 'production-gce-c28', region: 'asia-east2' }, + (entry) => entries.push(entry) + ) + const flooded = CONTROL_RTT_RESERVOIR_LIMIT * 20 + for (let sample = 0; sample < flooded; sample++) { + observability.recordControlRtt(10 + (sample % 40)) + } + observability.flush(counts) + + // Dropped is observed minus retained, so this pins the retained window at the cap. + expect(entries[0]).toMatchObject({ + controlRttSamplesDelta: flooded, + controlRttSamplesDroppedDelta: flooded - CONTROL_RTT_RESERVOIR_LIMIT + }) + // The kept samples are real observations, not a truncated or synthesised window. + expect(entries[0]!.controlRttMsP50 as number).toBeGreaterThanOrEqual(10) + expect(entries[0]!.controlRttMsMax as number).toBeLessThanOrEqual(49) + + observability.flush(counts) + expect(entries[1]).toMatchObject({ + controlRttSamplesDelta: 0, + controlRttSamplesDroppedDelta: 0 + }) + expect(entries[1]).not.toHaveProperty('controlRttMsP50') + }) + + it('samples the whole flooded window rather than its first samples', () => { + const entries: Array> = [] + const observability = new RelayObservability( + { role: 'cell', cellId: 'production-gce-c28', region: 'asia-east2' }, + (entry) => entries.push(entry) + ) + const half = CONTROL_RTT_RESERVOIR_LIMIT * 10 + for (let sample = 0; sample < half; sample++) observability.recordControlRtt(10) + for (let sample = 0; sample < half; sample++) observability.recordControlRtt(900) + observability.flush(counts) + + // Keeping the first N instead would publish a window of nothing but 10s. Each + // reservoir slot ends up drawn from the late half with ~1/2 probability, so + // fewer than the 5% the p95 needs is out of reach of this suite. + expect(entries[0]!.controlRttMsP95).toBe(900) + expect(entries[0]!.controlRttMsMax).toBe(900) }) it('observes successful and failed database calls including transactions', async () => { diff --git a/cloud/apps/relay/src/relay-observability.ts b/cloud/apps/relay/src/relay-observability.ts index 9f937afdb6e..5e85758ca56 100644 --- a/cloud/apps/relay/src/relay-observability.ts +++ b/cloud/apps/relay/src/relay-observability.ts @@ -116,12 +116,17 @@ type RelayMetricDeltas = { clientAcceptTotalsMs: number[] clientAcceptStageSamplesMs: Record controlRttSamplesMs: number[] + controlRttObserved: number controlRenewalLatenciesMs: number[] controlRenewalsByOutcome: Record controlActivityRecoveries: number controlActivityRecoveryFailures: number } +// A host chooses how often it answers a ping, so the process-wide window is a +// reservoir: the heap cost of a flood is capped and the percentiles stay unbiased. +export const CONTROL_RTT_RESERVOIR_LIMIT = 1024 + type MetricWriter = (entry: Record) => void const emptyDeltas = (): RelayMetricDeltas => ({ @@ -156,6 +161,7 @@ const emptyDeltas = (): RelayMetricDeltas => ({ basis: [] }, controlRttSamplesMs: [], + controlRttObserved: 0, controlRenewalLatenciesMs: [], controlRenewalsByOutcome: {}, controlActivityRecoveries: 0, @@ -298,7 +304,15 @@ export class RelayObservability implements RelayRuntimeObserver { } recordControlRtt(rttMs: number): void { - this.deltas.controlRttSamplesMs.push(rttMs) + const samples = this.deltas.controlRttSamplesMs + const observedBefore = this.deltas.controlRttObserved++ + if (samples.length < CONTROL_RTT_RESERVOIR_LIMIT) { + samples.push(rttMs) + return + } + // Algorithm R: every round trip in the window keeps an equal chance of being kept. + const slot = Math.floor(Math.random() * (observedBefore + 1)) + if (slot < CONTROL_RTT_RESERVOIR_LIMIT) samples[slot] = rttMs } start(readCounts: () => RelayProcessCounts, intervalMs = 30_000): void { @@ -386,7 +400,10 @@ export class RelayObservability implements RelayRuntimeObserver { clientAcceptAttachMsP95: acceptStageP95('attach'), clientAcceptBasisMsP95: acceptStageP95('basis') }), - controlRttSamplesDelta: deltas.controlRttSamplesMs.length, + // Every round trip observed in the window, including the ones the reservoir + // above declined to keep; the percentiles summarise only what it kept. + controlRttSamplesDelta: deltas.controlRttObserved, + controlRttSamplesDroppedDelta: deltas.controlRttObserved - deltas.controlRttSamplesMs.length, ...(deltas.controlRttSamplesMs.length === 0 ? {} : { diff --git a/cloud/infra/terraform/relay-observability.tf b/cloud/infra/terraform/relay-observability.tf index 4c6722d3532..498c342f7c2 100644 --- a/cloud/infra/terraform/relay-observability.tf +++ b/cloud/infra/terraform/relay-observability.tf @@ -68,7 +68,8 @@ locals { control_rtt_ms_p50 = { field = "controlRttMsP50", description = "Control-socket ping round trip p50 in the interval. The desktop echoes the pong on its main thread, so only the median reads as distance; the p95 and max below are dominated by desktop stalls." } control_rtt_ms_p95 = { field = "controlRttMsP95", description = "Control-socket ping round trip p95 in the interval; a desktop-stall signal, not a distance one." } control_rtt_ms_max = { field = "controlRttMsMax", description = "Maximum control-socket ping round trip in the interval; a desktop-stall signal, not a distance one." } - control_rtt_samples = { field = "controlRttSamplesDelta", description = "Control-socket round-trip samples in the interval; the percentiles above are omitted when this is zero." } + control_rtt_samples = { field = "controlRttSamplesDelta", description = "Control-socket round trips observed in the interval, one per ping answered; the percentiles above are omitted when this is zero." } + control_rtt_samples_dropped = { field = "controlRttSamplesDroppedDelta", description = "Observed round trips the bounded percentile reservoir did not keep; non-zero means the percentiles above summarise a uniform sample of the interval." } client_accepts_completed = { field = "clientAcceptCompletedDelta", description = "Phone accepts that reached relay-hello in the interval; the percentiles below are omitted when this is zero." } client_accept_total_ms_p50 = { field = "clientAcceptTotalMsP50", description = "Successful phone-accept duration p50, dial to relay-hello." } client_accept_total_ms_p95 = { field = "clientAcceptTotalMsP95", description = "Successful phone-accept duration p95, dial to relay-hello." } From 1bf30670d4868dcaa2315d34b212fd7ab4aa84dd Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 05:48:19 -0400 Subject: [PATCH 15/37] fix(relay-ops): let the rehome trust probe approve the asia-east2 cells (#19275) --- .../dev/scripts/probe-relay-rehome-trust.mjs | 4 +++- .../scripts/probe-relay-rehome-trust.test.mjs | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/cloud/dev/scripts/probe-relay-rehome-trust.mjs b/cloud/dev/scripts/probe-relay-rehome-trust.mjs index 9a7d505d4bb..2208131e58a 100644 --- a/cloud/dev/scripts/probe-relay-rehome-trust.mjs +++ b/cloud/dev/scripts/probe-relay-rehome-trust.mjs @@ -1,7 +1,9 @@ import { pathToFileURL } from 'node:url' import { fetchAdminOnceMore } from './relay-admin-transient-retry.mjs' -const PRODUCTION_CELL = /^production-gce-c(?:7|8|9|10|13|14|15|16|19|20|21|22|23|24|25|26)$/ +// Every general cell that carries the rehome identity: the sixteen US cells and the +// three asia-east2 cells that drain mis-homed hosts back the other way. +const PRODUCTION_CELL = /^production-gce-c(?:7|8|9|10|13|14|15|16|19|20|21|22|23|24|25|26|27|28|29)$/ const DIRECTOR_ORIGIN = 'https://relay.onorca.dev' export function parseRehomeTrustProbeArguments(argv, environment = process.env) { diff --git a/cloud/dev/scripts/probe-relay-rehome-trust.test.mjs b/cloud/dev/scripts/probe-relay-rehome-trust.test.mjs index 7d7b2cd95ac..789d33c40b6 100644 --- a/cloud/dev/scripts/probe-relay-rehome-trust.test.mjs +++ b/cloud/dev/scripts/probe-relay-rehome-trust.test.mjs @@ -111,3 +111,23 @@ test('fails when both trust-probe attempts return a transient 503', async () => ) assert.equal(calls, 2) }) + +test('approves the asia-east2 rehome sources and still rejects unlisted cells', () => { + for (const cellId of ['production-gce-c27', 'production-gce-c28', 'production-gce-c29']) { + const parsed = parseRehomeTrustProbeArguments( + argv.map((value) => (value === 'production-gce-c7' ? cellId : value)), + environment + ) + assert.equal(parsed.cellId, cellId) + } + for (const cellId of ['production-gce-c1', 'production-gce-c17', 'production-gce-c30']) { + assert.throws( + () => + parseRehomeTrustProbeArguments( + argv.map((value) => (value === 'production-gce-c7' ? cellId : value)), + environment + ), + /--cell-id is not approved/ + ) + } +}) From 9d29e6878e7092ea5b5c74864d3f14e0fb0d8026 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 7 Sep 2026 03:28:33 -0700 Subject: [PATCH 16/37] fix(codex): distinguish personal and enterprise accounts sharing an email (#19279) * fix(codex): distinguish same-email accounts in the switcher * fix(codex): scope switcher disambiguation to the visible runtime group Review follow-ups: wrap labels at word boundaries instead of mid-word, disambiguate against the accounts a group actually renders, and tolerate a missing email arriving from persisted settings or a remote summary. --- .../codex-accounts/codex-auth-identity.ts | 33 ++++- .../codex-auth-workspace-identity.test.ts | 106 ++++++++++++++++ .../runtime-home-per-account-homes.test.ts | 115 +++++++++--------- .../service-add-account-from-home.test.ts | 70 ++++++++++- .../accounts-pane-codex-account-row.tsx | 14 ++- .../status-bar/CodexSwitcherMenu.tsx | 4 +- .../status-bar/codex-status-sign-in.test.tsx | 36 ++++++ .../status-bar/status-bar-codex-accounts.ts | 7 +- .../status-bar-runtime-groups.test.ts | 73 +++++++++++ .../lib/codex-account-display-label.test.ts | 60 +++++++++ .../src/lib/codex-account-display-label.ts | 47 +++++++ src/renderer/src/lib/codex-session-restart.ts | 19 ++- .../codex-stale-pane-account-identity.test.ts | 4 +- 13 files changed, 504 insertions(+), 84 deletions(-) create mode 100644 src/main/codex-accounts/codex-auth-workspace-identity.test.ts create mode 100644 src/renderer/src/lib/codex-account-display-label.test.ts create mode 100644 src/renderer/src/lib/codex-account-display-label.ts diff --git a/src/main/codex-accounts/codex-auth-identity.ts b/src/main/codex-accounts/codex-auth-identity.ts index 0455b5e481f..105dbdbdb88 100644 --- a/src/main/codex-accounts/codex-auth-identity.ts +++ b/src/main/codex-accounts/codex-auth-identity.ts @@ -182,10 +182,10 @@ export function readCodexAuthIdentity(contents: string): CodexAuthIdentity | nul readStringClaim(authClaims, 'chatgpt_account_id') ?? readStringClaim(payload, 'chatgpt_account_id') ), - workspaceLabel: normalizeField( - readStringClaim(authClaims, 'workspace_name') ?? - readStringClaim(profileClaims, 'workspace_name') - ), + workspaceLabel: + normalizeField(readStringClaim(authClaims, 'workspace_name')) ?? + normalizeField(readStringClaim(profileClaims, 'workspace_name')) ?? + readPlanWorkspaceLabel(authClaims), workspaceAccountId: normalizeField( readStringClaim(authClaims, 'workspace_account_id') ?? tokenAccountId ?? @@ -194,6 +194,31 @@ export function readCodexAuthIdentity(contents: string): CodexAuthIdentity | nul } } +function readPlanWorkspaceLabel(authClaims: Record | null): string | null { + // Codex tokens commonly omit workspace_name but identify the account's plan. + switch (normalizeField(readStringClaim(authClaims, 'chatgpt_plan_type'))?.toLowerCase()) { + case 'free': + return 'Personal (Free)' + case 'go': + return 'Personal (Go)' + case 'plus': + return 'Personal (Plus)' + case 'pro': + return 'Personal (Pro)' + case 'team': + return 'Team' + case 'business': + return 'Business' + case 'enterprise': + return 'Enterprise' + case 'edu': + return 'Education' + case undefined: + default: + return null + } +} + function readFreshnessFromAuthContents(contents: string): number | null { const raw = parseJsonRecord(contents) if (!raw) { diff --git a/src/main/codex-accounts/codex-auth-workspace-identity.test.ts b/src/main/codex-accounts/codex-auth-workspace-identity.test.ts new file mode 100644 index 00000000000..8a1a18ffc81 --- /dev/null +++ b/src/main/codex-accounts/codex-auth-workspace-identity.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from 'vitest' +import type { CodexManagedAccount } from '../../shared/managed-account-types' +import { + codexAuthMatchesManagedAccount, + codexAuthMatchesSystemDefaultIdentity, + readCodexAuthIdentity +} from './codex-auth-identity' + +const email = 'same@example.com' + +function auth( + accountId: string, + claims: Record, + profileClaims: Record = {} +): string { + const payload = Buffer.from( + JSON.stringify({ + email, + 'https://api.openai.com/auth': { chatgpt_account_id: accountId, ...claims }, + 'https://api.openai.com/profile': profileClaims + }) + ).toString('base64url') + return JSON.stringify({ + tokens: { account_id: accountId, id_token: `header.${payload}.signature` } + }) +} + +describe('Codex personal and organization workspace identity', () => { + it.each([ + ['free', 'Personal (Free)'], + ['go', 'Personal (Go)'], + ['plus', 'Personal (Plus)'], + ['pro', 'Personal (Pro)'], + ['team', 'Team'], + ['business', 'Business'], + ['enterprise', 'Enterprise'], + ['edu', 'Education'] + ])('uses the %s plan when the token omits the workspace name', (plan, label) => { + expect(readCodexAuthIdentity(auth('provider-1', { chatgpt_plan_type: plan }))).toEqual({ + email, + providerAccountId: 'provider-1', + workspaceAccountId: 'provider-1', + workspaceLabel: label + }) + }) + + it.each([undefined, null, '', 'future-plan', 42])( + 'does not infer personal membership from an unknown plan %s', + (plan) => { + expect( + readCodexAuthIdentity(auth('provider-1', { chatgpt_plan_type: plan }))?.workspaceLabel + ).toBeNull() + } + ) + + it('preserves an explicit organization name over the plan label', () => { + expect( + readCodexAuthIdentity( + auth('provider-1', { workspace_name: ' Acme ', chatgpt_plan_type: 'enterprise' }) + )?.workspaceLabel + ).toBe('Acme') + }) + + it('uses the profile workspace name when the auth workspace name is blank', () => { + expect( + readCodexAuthIdentity( + auth( + 'provider-1', + { workspace_name: ' ', chatgpt_plan_type: 'enterprise' }, + { workspace_name: 'Acme' } + ) + )?.workspaceLabel + ).toBe('Acme') + }) + + it('keeps same-email personal and enterprise credentials isolated in both directions', () => { + const personal = auth('personal-provider', { chatgpt_plan_type: 'plus' }) + const enterprise = auth('enterprise-provider', { chatgpt_plan_type: 'enterprise' }) + for (const [selectedAuth, otherAuth] of [ + [personal, enterprise], + [enterprise, personal] + ]) { + const identity = readCodexAuthIdentity(selectedAuth)! + const account: CodexManagedAccount = { + ...identity, + id: 'orca-account', + email, + managedHomePath: 'managed-home', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + } + expect(codexAuthMatchesManagedAccount(selectedAuth, account, selectedAuth)).toBe(true) + expect(codexAuthMatchesManagedAccount(otherAuth, account, selectedAuth)).toBe(false) + expect(codexAuthMatchesSystemDefaultIdentity(otherAuth, selectedAuth)).toBe(false) + } + expect(readCodexAuthIdentity(personal)?.workspaceLabel).toBe('Personal (Plus)') + expect(readCodexAuthIdentity(enterprise)?.workspaceLabel).toBe('Enterprise') + }) + + it('does not treat a matching plan label as proof of account ownership', () => { + const first = auth('enterprise-a', { chatgpt_plan_type: 'enterprise' }) + const second = auth('enterprise-b', { chatgpt_plan_type: 'enterprise' }) + expect(codexAuthMatchesSystemDefaultIdentity(first, second)).toBe(false) + }) +}) diff --git a/src/main/codex-accounts/runtime-home-per-account-homes.test.ts b/src/main/codex-accounts/runtime-home-per-account-homes.test.ts index 7877482f355..dd948433962 100644 --- a/src/main/codex-accounts/runtime-home-per-account-homes.test.ts +++ b/src/main/codex-accounts/runtime-home-per-account-homes.test.ts @@ -87,64 +87,67 @@ describe('CodexRuntimeHomeService', () => { expect(service.getHostCodexHomePathsForSessionDiscovery()).toContain(managedHomePath) }) - it('gives two managed accounts distinct homes without racing one auth.json', async () => { - writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') - const account1Auth = createCodexAuthJson('one@example.com', 'acct-1', 'one') - const account2Auth = createCodexAuthJson('two@example.com', 'acct-2', 'two') - const home1 = createManagedAuth(testState.userDataDir, 'account-1', account1Auth) - const home2 = createManagedAuth(testState.userDataDir, 'account-2', account2Auth) - const settings = createSettings({ - shellStartupEnvProbeSupported: true, - codexManagedAccounts: [ - { - id: 'account-1', - email: 'one@example.com', - managedHomePath: home1, - providerAccountId: 'acct-1', - workspaceLabel: null, - workspaceAccountId: 'acct-1', - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - }, - { - id: 'account-2', - email: 'two@example.com', - managedHomePath: home2, - providerAccountId: 'acct-2', - workspaceLabel: null, - workspaceAccountId: 'acct-2', - createdAt: 2, - updatedAt: 2, - lastAuthenticatedAt: 2 - } - ], - activeCodexManagedAccountId: 'account-1', - activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } - }) - const store = createStore(settings) - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const service = new CodexRuntimeHomeService(store as never) - - // A pane for account-1 launches, then the user switches and a second pane - // for account-2 launches concurrently — each gets its OWN CODEX_HOME. - expect(service.prepareForCodexLaunch()).toBe(home1) - settings.activeCodexManagedAccountId = 'account-2' - settings.activeCodexManagedAccountIdsByRuntime = { host: 'account-2', wsl: {} } - expect(service.prepareForCodexLaunch()).toBe(home2) - expect( - service.prepareForCodexLaunch(undefined, undefined, { - unavailableManagedHomePath: home1 + it.each(['two@example.com', 'one@example.com'])( + 'isolates account homes when the second email is %s', + async (secondEmail) => { + writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') + const account1Auth = createCodexAuthJson('one@example.com', 'acct-1', 'one') + const account2Auth = createCodexAuthJson(secondEmail, 'acct-2', 'two') + const home1 = createManagedAuth(testState.userDataDir, 'account-1', account1Auth) + const home2 = createManagedAuth(testState.userDataDir, 'account-2', account2Auth) + const settings = createSettings({ + shellStartupEnvProbeSupported: true, + codexManagedAccounts: [ + { + id: 'account-1', + email: 'one@example.com', + managedHomePath: home1, + providerAccountId: 'acct-1', + workspaceLabel: null, + workspaceAccountId: 'acct-1', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + }, + { + id: 'account-2', + email: secondEmail, + managedHomePath: home2, + providerAccountId: 'acct-2', + workspaceLabel: null, + workspaceAccountId: 'acct-2', + createdAt: 2, + updatedAt: 2, + lastAuthenticatedAt: 2 + } + ], + activeCodexManagedAccountId: 'account-1', + activeCodexManagedAccountIdsByRuntime: { host: 'account-1', wsl: {} } }) - ).toBe(home2) - expect(store.updateSettings).not.toHaveBeenCalled() + const store = createStore(settings) + const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) - // Nothing is hot-swapped, so the still-running account-1 pane keeps seeing - // account-1's credentials — the single-auth.json race (GAP-5) is gone. - expect(readFileSync(join(home1, 'auth.json'), 'utf-8')).toBe(account1Auth) - expect(readFileSync(join(home2, 'auth.json'), 'utf-8')).toBe(account2Auth) - expect(existsSync(getRuntimeCodexAuthPath())).toBe(false) - }) + // A pane for account-1 launches, then the user switches and a second pane + // for account-2 launches concurrently — each gets its OWN CODEX_HOME. + expect(service.prepareForCodexLaunch()).toBe(home1) + settings.activeCodexManagedAccountId = 'account-2' + settings.activeCodexManagedAccountIdsByRuntime = { host: 'account-2', wsl: {} } + expect(service.prepareForCodexLaunch()).toBe(home2) + expect( + service.prepareForCodexLaunch(undefined, undefined, { + unavailableManagedHomePath: home1 + }) + ).toBe(home2) + expect(store.updateSettings).not.toHaveBeenCalled() + + // Nothing is hot-swapped, so the still-running account-1 pane keeps seeing + // account-1's credentials — the single-auth.json race (GAP-5) is gone. + expect(readFileSync(join(home1, 'auth.json'), 'utf-8')).toBe(account1Auth) + expect(readFileSync(join(home2, 'auth.json'), 'utf-8')).toBe(account2Auth) + expect(existsSync(getRuntimeCodexAuthPath())).toBe(false) + } + ) it('materializes resources and config into the per-account home on launch', async () => { writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') diff --git a/src/main/codex-accounts/service-add-account-from-home.test.ts b/src/main/codex-accounts/service-add-account-from-home.test.ts index 16c060c8a55..8247e5fadd0 100644 --- a/src/main/codex-accounts/service-add-account-from-home.test.ts +++ b/src/main/codex-accounts/service-add-account-from-home.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { @@ -29,6 +29,74 @@ vi.mock('node:os', async () => { describe('CodexAccountService.addAccountFromHome', () => { registerCodexAccountsTestHomes() + it('imports and switches personal and enterprise accounts sharing an email independently', async () => { + vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) + const sourceHomes = [ + mkdtempSync(join(tmpdir(), 'orca-codex-personal-')), + mkdtempSync(join(tmpdir(), 'orca-codex-enterprise-')) + ] + const email = 'same@example.com' + const credentials = ['plus', 'enterprise'].map((plan) => { + const parsed = JSON.parse(createCodexAuthJson(email, `provider-${plan}`, `refresh-${plan}`)) + const payload = Buffer.from( + JSON.stringify({ + email, + 'https://api.openai.com/auth': { + chatgpt_account_id: `provider-${plan}`, + chatgpt_plan_type: plan + } + }) + ).toString('base64url') + parsed.tokens.id_token = `header.${payload}.signature` + return JSON.stringify(parsed) + }) + + try { + sourceHomes.forEach((home, index) => { + writeFileSync(join(home, 'auth.json'), credentials[index], 'utf-8') + }) + const store = createStore(createSettings()) + const runtimeHome = createRuntimeHome() + const { CodexAccountService } = await import('./service') + const service = new CodexAccountService( + store as never, + createRateLimits() as never, + runtimeHome as never + ) + + await service.addAccountFromHome(sourceHomes[0]) + const result = await service.addAccountFromHome(sourceHomes[1]) + const accounts = store.getSettings().codexManagedAccounts + expect(result.accounts).toHaveLength(2) + expect(new Set(accounts.map((account) => account.id)).size).toBe(2) + expect(new Set(accounts.map((account) => account.managedHomePath)).size).toBe(2) + expect(accounts.map((account) => account.email)).toEqual([email, email]) + expect(accounts.map((account) => account.workspaceLabel)).toEqual([ + 'Personal (Plus)', + 'Enterprise' + ]) + expect(accounts.map((account) => account.providerAccountId)).toEqual([ + 'provider-plus', + 'provider-enterprise' + ]) + + for (const account of accounts) { + const selected = await service.selectAccount(account.id) + expect(selected.activeAccountId).toBe(account.id) + expect(store.getSettings().activeCodexManagedAccountIdsByRuntime?.host).toBe(account.id) + accounts.forEach((entry, index) => { + expect(readFileSync(join(entry.managedHomePath, 'auth.json'), 'utf-8')).toBe( + credentials[index] + ) + }) + } + expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalledTimes(4) + } finally { + sourceHomes.forEach((home) => rmSync(home, { recursive: true, force: true })) + vi.doUnmock('../codex-cli/command') + } + }) + it('registers a managed Codex account by importing an authenticated CODEX_HOME', async () => { vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) const sourceHome = mkdtempSync(join(tmpdir(), 'orca-codex-source-')) diff --git a/src/renderer/src/components/settings/accounts-pane-codex-account-row.tsx b/src/renderer/src/components/settings/accounts-pane-codex-account-row.tsx index 21bef8fb17c..182b8de5aee 100644 --- a/src/renderer/src/components/settings/accounts-pane-codex-account-row.tsx +++ b/src/renderer/src/components/settings/accounts-pane-codex-account-row.tsx @@ -1,6 +1,7 @@ import { Loader2, RefreshCw, Trash2 } from 'lucide-react' import type { CodexRateLimitAccountsState } from '../../../../shared/managed-account-types' import { translate } from '@/i18n/i18n' +import { getCodexAccountDisplayDetail } from '@/lib/codex-account-display-label' import { selectCodexProviderAccount } from '@/runtime/runtime-provider-accounts-client' import { Badge } from '../ui/badge' import { Button } from '../ui/button' @@ -48,6 +49,7 @@ export function renderCodexAccountRow( accountId: account.id }) const needsReauthentication = Boolean(accountAuthWarning) + const accountDetail = getCodexAccountDisplayDetail(account, codexAccounts.accounts) const isReauthing = codexAction === `reauth:${account.id}` const isRemoving = codexAction === `remove:${account.id}` const isBusy = codexAction !== 'idle' || accountRuntimeUnavailable @@ -111,6 +113,12 @@ export function renderCodexAccountRow( needsReauthentication ? 'text-destructive' : 'text-muted-foreground' }`} > + {accountDetail ? ( + <> + {accountDetail} + + + ) : null} {needsReauthentication ? ( {translate( @@ -118,12 +126,8 @@ export function renderCodexAccountRow( 'Codex reported this sign-in is out of date' )} - ) : account.workspaceLabel ? ( - {account.workspaceLabel} - ) : null} - {needsReauthentication || account.workspaceLabel ? ( - ) : null} + {needsReauthentication ? : null} {formatAccountTimestamp(account.lastAuthenticatedAt)} diff --git a/src/renderer/src/components/status-bar/CodexSwitcherMenu.tsx b/src/renderer/src/components/status-bar/CodexSwitcherMenu.tsx index 0a4bccdc29a..33818340d24 100644 --- a/src/renderer/src/components/status-bar/CodexSwitcherMenu.tsx +++ b/src/renderer/src/components/status-bar/CodexSwitcherMenu.tsx @@ -239,7 +239,9 @@ export function CodexSwitcherMenu({ >
- {target.label} + + {target.label} + {target.active ? ( {translate( diff --git a/src/renderer/src/components/status-bar/codex-status-sign-in.test.tsx b/src/renderer/src/components/status-bar/codex-status-sign-in.test.tsx index 446019b86be..86912a2e50e 100644 --- a/src/renderer/src/components/status-bar/codex-status-sign-in.test.tsx +++ b/src/renderer/src/components/status-bar/codex-status-sign-in.test.tsx @@ -207,6 +207,42 @@ describe('status bar Codex sign-in action', () => { cleanup() }) + it.each([null, 'Enterprise'])( + 'selects the exact same-email account when workspace labels collide: %s', + async (workspaceLabel) => { + storeSettings.codexManagedAccounts = storeSettings.codexManagedAccounts.map((account) => ({ + ...account, + email: 'same@example.com', + workspaceLabel + })) + const { selectCodexProviderAccount } = + await import('@/runtime/runtime-provider-accounts-client') + vi.mocked(selectCodexProviderAccount).mockResolvedValueOnce({ + accounts: storeSettings.codexManagedAccounts, + activeAccountId: 'account-2', + activeAccountIdsByRuntime: { host: 'account-2', wsl: {} } + }) + + await renderSwitcherAndOpenAccounts('System default') + const detail = workspaceLabel ? `${workspaceLabel} · ` : '' + expect(screen.getByText(`same@example.com (${detail}account-1)`)).toBeTruthy() + fireEvent.click(screen.getByText(`same@example.com (${detail}account-2)`)) + + await waitFor(() => + expect(selectCodexProviderAccount).toHaveBeenCalledWith(storeSettings, { + accountId: 'account-2', + runtime: 'host', + wslDistro: null + }) + ) + expect(markLiveCodexSessionsForRestart).toHaveBeenCalledWith( + expect.objectContaining({ + nextAccountId: 'account-2' + }) + ) + } + ) + it('activates the signed-in account and runs the same restart workflow a switch runs', async () => { reauthenticate.mockResolvedValue(codexSnapshot('account-2')) diff --git a/src/renderer/src/components/status-bar/status-bar-codex-accounts.ts b/src/renderer/src/components/status-bar/status-bar-codex-accounts.ts index 62720392825..d72e4d1702d 100644 --- a/src/renderer/src/components/status-bar/status-bar-codex-accounts.ts +++ b/src/renderer/src/components/status-bar/status-bar-codex-accounts.ts @@ -1,6 +1,7 @@ import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { CodexRateLimitAccountsState } from '../../../../shared/managed-account-types' import { translate } from '@/i18n/i18n' +import { getCodexAccountDisplayLabel } from '@/lib/codex-account-display-label' import { getCodexStatusRuntimeKey, getCodexStatusRuntimeLabel, @@ -12,10 +13,6 @@ import { type CodexStatusAccount = CodexRateLimitAccountsState['accounts'][number] -function getCodexAccountDisplayLabel(account: CodexStatusAccount): string { - return account.workspaceLabel ? `${account.email} (${account.workspaceLabel})` : account.email -} - function getSingleConcreteCodexWslDistro(state: CodexRateLimitAccountsState): string | null { const keys = new Set() for (const [key, accountId] of Object.entries(state.activeAccountIdsByRuntime?.wsl ?? {})) { @@ -96,7 +93,7 @@ export function buildCodexStatusSwitchGroups( }, ...accountsForTarget.map((account) => ({ id: account.id, - label: getCodexAccountDisplayLabel(account), + label: getCodexAccountDisplayLabel(account, accountsForTarget), active: account.id === activeId, runtimeTarget: target })) diff --git a/src/renderer/src/components/status-bar/status-bar-runtime-groups.test.ts b/src/renderer/src/components/status-bar/status-bar-runtime-groups.test.ts index 5e0c4a162de..c323861f85f 100644 --- a/src/renderer/src/components/status-bar/status-bar-runtime-groups.test.ts +++ b/src/renderer/src/components/status-bar/status-bar-runtime-groups.test.ts @@ -15,6 +15,79 @@ import { const hostLabel = navigator.userAgent.includes('Windows') ? 'Windows' : 'This device' describe('status bar runtime switch groups', () => { + it.each(['host', 'wsl'] as const)( + 'keeps same-email accounts independently selectable in the %s runtime', + (runtime) => { + const state: CodexRateLimitAccountsState = { + accounts: ['account-a', 'account-b'].map((id) => ({ + id, + email: 'same@example.com', + managedHomeRuntime: runtime, + wslDistro: runtime === 'wsl' ? 'Ubuntu' : null, + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + })), + activeAccountId: runtime === 'host' ? 'account-b' : null, + activeAccountIdsByRuntime: { + host: runtime === 'host' ? 'account-b' : null, + wsl: runtime === 'wsl' ? { Ubuntu: 'account-b' } : {} + } + } + const target = { runtime, wslDistro: runtime === 'wsl' ? 'Ubuntu' : null } + const group = buildCodexStatusSwitchGroups(state, target).find( + (entry) => entry.runtimeTarget.runtime === runtime + )! + expect(group.targets.slice(1)).toEqual([ + { + id: 'account-a', + label: 'same@example.com (account-a)', + active: false, + runtimeTarget: target + }, + { + id: 'account-b', + label: 'same@example.com (account-b)', + active: true, + runtimeTarget: target + } + ]) + } + ) + + it('keeps one email plain when its only same-email peer sits in another runtime group', () => { + const state: CodexRateLimitAccountsState = { + accounts: [ + { + id: 'account-host', + email: 'same@example.com', + managedHomeRuntime: 'host', + wslDistro: null, + workspaceLabel: 'Personal (Plus)', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + }, + { + id: 'account-wsl', + email: 'same@example.com', + managedHomeRuntime: 'wsl', + wslDistro: 'Ubuntu', + workspaceLabel: 'Personal (Plus)', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + } + ], + activeAccountId: null, + activeAccountIdsByRuntime: { host: null, wsl: { Ubuntu: null } } + } + const groups = buildCodexStatusSwitchGroups(state, { runtime: 'host', wslDistro: null }) + expect(groups.flatMap((group) => group.targets.slice(1).map((target) => target.label))).toEqual( + ['same@example.com (Personal (Plus))', 'same@example.com (Personal (Plus))'] + ) + }) + it('collapses WSL default into the single concrete Codex distro', () => { const state: CodexRateLimitAccountsState = { accounts: [ diff --git a/src/renderer/src/lib/codex-account-display-label.test.ts b/src/renderer/src/lib/codex-account-display-label.test.ts new file mode 100644 index 00000000000..64c99a48f0e --- /dev/null +++ b/src/renderer/src/lib/codex-account-display-label.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest' +import { + getCodexAccountDisplayLabel, + type CodexDisplayAccount +} from './codex-account-display-label' + +const email = 'same@example.com' +const labels = (accounts: CodexDisplayAccount[]) => + accounts.map((account) => getCodexAccountDisplayLabel(account, accounts)) + +describe('Codex account display labels', () => { + it('names personal and enterprise workspaces sharing an email', () => { + expect( + labels([ + { id: 'personal', email, workspaceLabel: 'Personal (Plus)' }, + { id: 'enterprise', email, workspaceLabel: 'Enterprise' } + ]) + ).toEqual([`${email} (Personal (Plus))`, `${email} (Enterprise)`]) + }) + + it.each([null, 'Enterprise'])( + 'disambiguates missing or duplicate workspace names: %s', + (workspaceLabel) => { + const accounts = [ + { id: '12345678-a', email, workspaceLabel }, + { id: '12345678-b', email, workspaceLabel } + ] + const result = labels(accounts) + expect(new Set(result).size).toBe(2) + expect(result[0]).toContain('12345678-a') + expect(result[1]).toContain('12345678-b') + expect(labels(accounts.toReversed())).toEqual(result.toReversed()) + } + ) + + it('handles legacy and remote summaries without workspace metadata', () => { + expect( + labels([ + { id: 'account-a', email }, + { id: 'account-b', email: email.toUpperCase() } + ]) + ).toEqual([`${email} (account-a)`, `${email.toUpperCase()} (account-b)`]) + }) + + it('keeps unambiguous accounts concise', () => { + expect(labels([{ id: 'account-a', email }])).toEqual([email]) + expect(labels([{ id: 'account-a', email, workspaceLabel: 'Acme' }])).toEqual([ + `${email} (Acme)` + ]) + }) + + it('does not collide with a workspace name that looks like an ID suffix', () => { + const result = labels([ + { id: '12345678-a', email }, + { id: '87654321-b', email }, + { id: 'abcdefgh-c', email, workspaceLabel: '12345678' } + ]) + expect(new Set(result).size).toBe(3) + }) +}) diff --git a/src/renderer/src/lib/codex-account-display-label.ts b/src/renderer/src/lib/codex-account-display-label.ts new file mode 100644 index 00000000000..01b7b701026 --- /dev/null +++ b/src/renderer/src/lib/codex-account-display-label.ts @@ -0,0 +1,47 @@ +export type CodexDisplayAccount = { + id: string + email: string + workspaceLabel?: string | null +} + +// Emails round-trip through persisted settings and remote summaries; tolerate a missing one. +export function normalizeCodexAccountEmail(email: string | null | undefined): string { + return (email ?? '').trim().toLowerCase() +} + +export function getCodexAccountDisplayDetail( + account: CodexDisplayAccount, + accounts: readonly CodexDisplayAccount[] +): string | null { + const workspace = account.workspaceLabel?.trim() || null + const email = normalizeCodexAccountEmail(account.email) + const peers = accounts.filter( + (entry) => entry.id !== account.id && normalizeCodexAccountEmail(entry.email) === email + ) + const workspaces = [workspace, ...peers.map((entry) => entry.workspaceLabel?.trim() || null)] + if ( + peers.length === 0 || + (workspaces.every(Boolean) && new Set(workspaces).size === workspaces.length) + ) { + return workspace + } + + // Extend the stored account ID prefix until even same-prefix accounts are distinguishable. + let length = Math.min(8, account.id.length) + while ( + length < account.id.length && + peers.some((entry) => entry.id.slice(0, length) === account.id.slice(0, length)) + ) { + length += 1 + } + const identifier = account.id.slice(0, length) + return workspace ? `${workspace} · ${identifier}` : identifier +} + +export function getCodexAccountDisplayLabel( + account: CodexDisplayAccount, + accounts: readonly CodexDisplayAccount[] +): string { + const detail = getCodexAccountDisplayDetail(account, accounts) + return detail ? `${account.email} (${detail})` : account.email +} diff --git a/src/renderer/src/lib/codex-session-restart.ts b/src/renderer/src/lib/codex-session-restart.ts index d3a111e86db..c2f1119ca54 100644 --- a/src/renderer/src/lib/codex-session-restart.ts +++ b/src/renderer/src/lib/codex-session-restart.ts @@ -6,6 +6,10 @@ import { type RuntimeTerminalProcessInspection } from '@/runtime/runtime-terminal-inspection' import { translate } from '@/i18n/i18n' +import { + getCodexAccountDisplayLabel, + normalizeCodexAccountEmail +} from './codex-account-display-label' import { isShellProcess } from '../../../shared/shell-process-detection' import { isCodexForegroundProcess, @@ -326,13 +330,7 @@ export async function markRestoredStaleCodexSessionsForRestart(args?: { return scans.map((scan) => (notifiedPtyIds.has(scan.ptyId) ? { ...scan, notified: true } : scan)) } -/** - * Names an account for the restart prompt. - * - * Why the collision check: one OpenAI login added under two ChatGPT workspaces - * gives both accounts the same email, and "switch from x@y to x@y" names - * neither. The workspace is appended only when it is what tells them apart. - */ +// Same-email accounts need the same workspace or ID distinction as the switcher. export function resolveCodexRestartPromptAccountLabel( accounts: readonly { id: string; email: string; workspaceLabel?: string | null }[], accountId: string | null | undefined @@ -344,12 +342,11 @@ export function resolveCodexRestartPromptAccountLabel( if (!account) { return translate('auto.lib.codex.session.restart.9f0b1c2d3e', 'Codex account') } + const email = normalizeCodexAccountEmail(account.email) const sharesEmail = accounts.some( - (entry) => entry.id !== account.id && entry.email === account.email + (entry) => entry.id !== account.id && normalizeCodexAccountEmail(entry.email) === email ) - return sharesEmail && account.workspaceLabel - ? `${account.email} (${account.workspaceLabel})` - : account.email + return sharesEmail ? getCodexAccountDisplayLabel(account, accounts) : account.email } async function createCodexAccountLabelResolver(): Promise<(accountId: string | null) => string> { diff --git a/src/renderer/src/lib/codex-stale-pane-account-identity.test.ts b/src/renderer/src/lib/codex-stale-pane-account-identity.test.ts index aeeb1c674c9..1389d88cd89 100644 --- a/src/renderer/src/lib/codex-stale-pane-account-identity.test.ts +++ b/src/renderer/src/lib/codex-stale-pane-account-identity.test.ts @@ -80,7 +80,7 @@ describe('stale Codex panes are decided by account id, not label', () => { } }) - it('keeps the prompt when the two accounts resolve to the same label', async () => { + it('distinguishes same-email accounts even without workspace names', async () => { vi.mocked(window.api.codexAccounts.listStalePanes).mockResolvedValue([ { ptyId: 'pty-1', launchAccountId: 'account-a', activeAccountId: 'account-b' } ]) @@ -88,6 +88,8 @@ describe('stale Codex panes are decided by account id, not label', () => { const scans = await markRestoredStaleCodexSessionsForRestart() expect(noticeFor('pty-1')).toMatchObject({ + previousAccountLabel: `${SHARED_EMAIL} (account-a)`, + nextAccountLabel: `${SHARED_EMAIL} (account-b)`, previousAccountId: 'account-a', nextAccountId: 'account-b' }) From 8cd0abf76acd830bd96b5b7df2f266e2f4480fb3 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Mon, 7 Sep 2026 07:39:38 -0400 Subject: [PATCH 17/37] test(relay): prove the capability header reaches acceptControl over a real upgrade (#19274) The unit tests cover parseRelayHostCapabilities, the sendHelloAck gating, and the header literal separately, but nothing joined them: a typo in the header name read off the upgrade request passed the entire suite. This drives a real control upgrade carrying the header, leaves an invite connection pending, and asserts the rebound control's ack. Renaming the header the server reads fails it. --- cloud/apps/relay/src/relay.blackbox.test.ts | 75 ++++++++++++++++++++- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/cloud/apps/relay/src/relay.blackbox.test.ts b/cloud/apps/relay/src/relay.blackbox.test.ts index 38134213e76..0202d964ee7 100644 --- a/cloud/apps/relay/src/relay.blackbox.test.ts +++ b/cloud/apps/relay/src/relay.blackbox.test.ts @@ -9,7 +9,9 @@ import { fileURLToPath } from 'node:url' import { exportJWK, generateKeyPair, jwtVerify, SignJWT } from 'jose' import { buildHostProofMacInput, - HOST_CHALLENGE_PLAINTEXT_DOMAIN + HOST_CHALLENGE_PLAINTEXT_DOMAIN, + RELAY_HOST_CAPABILITIES_HEADER, + RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS } from '@orca-cloud/relay-contract' import nacl from 'tweetnacl' import { afterAll, beforeAll, describe, expect, it } from 'vitest' @@ -282,11 +284,17 @@ async function openHostControl(input?: { previousGeneration?: number keyPair?: nacl.BoxKeyPair assignmentEpoch?: number + capabilities?: string }): Promise<{ socket: WebSocket; ack: Record; keyPair: nacl.BoxKeyPair }> { const keyPair = input?.keyPair ?? nacl.box.keyPair() const hostId = createHash('sha256').update(keyPair.publicKey).digest('base64url').slice(0, 16) const socket = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/host/control`, { - headers: { authorization: `Bearer ${await relayToken('orca-relay', hostId)}` }, + headers: { + authorization: `Bearer ${await relayToken('orca-relay', hostId)}`, + ...(input?.capabilities + ? { [RELAY_HOST_CAPABILITIES_HEADER]: input.capabilities } + : {}) + }, perMessageDeflate: false }) await new Promise((resolveOpen, reject) => { @@ -653,6 +661,69 @@ describe('served relay URL', () => { expect(result.reason).not.toContain('http') }) + it('restates a pending connection to the rebound control, detailed only when advertised', async () => { + // The one link the unit tests cannot reach: an upgrade that really carries + // x-orca-host-capabilities must reach acceptControl and change the ack. A + // typo in the header name here passes every other test in the suite. + const host = await openHostControl() + const hostId = createHash('sha256') + .update(host.keyPair.publicKey) + .digest('base64url') + .slice(0, 16) + const inviteResponse = nextMessage(host.socket) + host.socket.send( + JSON.stringify({ + type: 'invite-create', + reqId: 'capability-invite', + relayDeviceId: 'capability-device' + }) + ) + const invite = await inviteResponse + const phone = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/connect/${hostId}`, { + headers: forwardedHeaders() + }) + await new Promise((resolveOpen, reject) => { + phone.once('open', resolveOpen) + phone.once('error', reject) + }) + const connectionPromise = nextMessage(host.socket) + phone.send( + JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: invite.inviteToken }) + ) + // Never attached: the connection stays pending, which is what the ack restates. + const connection = await connectionPromise + expect(connection.type).toBe('conn-open') + + const capable = await openHostControl({ + keyPair: host.keyPair, + controlResumeSecret: String(host.ack.controlResumeSecret), + previousGeneration: 1, + capabilities: RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS + }) + expect(capable.ack.pendingConns).toEqual([ + { + connId: connection.connId, + connTicket: connection.connTicket, + kind: 'invite', + relayDeviceId: 'capability-device' + } + ]) + + const legacy = await openHostControl({ + keyPair: host.keyPair, + controlResumeSecret: String(capable.ack.controlResumeSecret), + previousGeneration: 1 + }) + // A shipped host parses these entries strictly, so an unannounced key would + // fail the whole ack and kill a control that was working. + expect(legacy.ack.pendingConns).toEqual([ + { connId: connection.connId, connTicket: connection.connTicket } + ]) + + phone.close() + legacy.socket.close() + }) + it('keeps a pending attach usable after a bad ticket and rejects ticket replay', async () => { const host = await openHostControl() const hostId = createHash('sha256') From a899f92402859440cff772e1babde707002f607c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 7 Sep 2026 09:18:38 -0700 Subject: [PATCH 18/37] feat(windows): enable structured Codex chat on native Windows (#18519) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(native-chat): enable Windows structured sessions * fix(codex): prove native Windows process identity * style(codex): format Windows session seam * fix Windows structured Codex admission * fix(windows): reprobe missing process identity capability * fix(windows): decide folder-workspace WSL routing before the click Review found pathUsesWslUnc exported but unused, and the folder composer hardcoding worktreeUsesWslPath:false. Together those meant a folder picked under a \\wsl.localhost\ parent routed to structured chat, then got refused by the host and fell back AFTER the click -- which defeats the lane's own design goal that create cannot fail after the click. The group's parentPath is in scope at submit and the workspace is created under it, so the parent decides WSL-ness pre-click. Wires pathUsesWslUnc there and adds tests for the helper, including the unhydrated-store case that previously threw. * fix(windows): collapse the gate derivation to one call, restoring max-lines CI static analysis failed: launch-agent-in-new-tab.ts crossed the 300-line oxlint ceiling. Adding a max-lines disable is forbidden, so the two gate derivations collapse into one readWindowsStructuredGateInputs() call -- a store-backed site now adds one line and one import name instead of two. Better shape anyway: one derivation entry point rather than two reads a call site must remember to pair. * fix(windows): engage the legacy fallback when the host THROWS a refusal Review found a P1 this merge composes: neither parent could reach it. At the lane head the only structured entry was launch-agent-in-new-tab (full store-backed WSL check); on main all win32 was refused. The merge enables win32 in creation flows that pass no projectRuntime, so a WSL folder workspace, a WSL-configured repo, or a repair-required runtime now routes structured -- and the host refuses correctly, but by THROWING rather than returning {ok:false, refusal}. Callers engage their legacy-terminal fallback on the refusal CLASS, so an unmapped throw arrives as a generic RPC rejection: no fallback, empty workspace, error toast, prompt stranded in the launch outbox. Pre-merge the same action opened a legacy terminal agent. Map the host's thrown definitive refusals onto the refusal class at the launch boundary, so every creation flow -- present and future -- degrades to the legacy terminal instead of stranding. Narrow predicate: unrelated failures (ECONNRESET, empty message, non-Error) still propagate untouched. Ablation-proven: removing the mapping reddens the fallback test. * fix(windows): teach the mobile RPC double the status probe the lane added CI's first-ever run on this lane caught a pre-existing lane defect. The lane changed status.get to resolve through runtime.getStatusAfterWindowsProcessStartTimeProbe(), but never taught the mobile-surface runtime double about it, so status.get failed for mobile clients with "not a function". The lane's own test list did not include this file and the lane had zero CI, so nothing ever ran it. The real runtime always implements the method; the double omitted it. * chore: merge current main and regenerate the localization runtime catalog CI static analysis failed on a stale en-runtime-required.json: main added onboarding integration-capability keys, and the generated catalog is checked against the PR MERGE result, not the branch alone -- so it read clean locally while failing in CI. Merging current main (90780acb85) and regenerating. Gates after the merge: pnpm tc 0, oxlint 0, changed-code quality 0/56, 7 gate/lane test files 69 tests green. * fix: route structured launches by execution host platform * fix: recover paired structured session mirror on host swap * Revert "fix: recover paired structured session mirror on host swap" This reverts commit 81bfca0007dbbbc150a9cfcc9a24e3d060c70850. * Revert "fix: route structured launches by execution host platform" This reverts commit 47abbd354acf45fd6acc69589ad55f6341493281. * fix(windows): refuse structured chat in a paired web client Reverts the two review-loop commits (restoring a tree byte-identical to the validated head) and closes the hole they were aiming at, without their cost. A paired web client's `platform` describes the browser's machine, not the host that will run the agent, so the Windows gate cannot be evaluated there. Before this, a browser on macOS driving a Windows runtime read "not win32", skipped the creation-time proof entirely and allowed structured chat — fail-OPEN, the dangerous direction, bypassing the guarantee this lane is built on. `isWebClient` is a required input like the other gate fields, so the compiler enumerated all seven call sites. Refusal is synchronous and fail-closed: no async round-trip, no null window, no cache to invalidate — unlike keying on an asynchronously-fetched host platform, which would have made every desktop launch wait on a round-trip to fix a paired-web-only hole. Paired web therefore gets the legacy chat until the host publishes eligibility itself; that is the proper fix and belongs in its own PR. Ablation-proven: removing the guard reddens both refusal tests; the desktop-unaffected test is a preservation check and passes either way. Gates: tc 0, oxlint 0. Known open: repos-onboarding-folder-startup.test.ts fails on this branch and passes on plain main — under investigation, NOT caused by this commit. * test(onboarding): mock the web-client check the store path now reaches The web-client refusal added `isWebClientLocation()` to the launch-route inputs, which this suite's store path reaches while adding the FIRST folder. The suite stubs `window` as `{ api }` with no `location`, so the function cleared its `typeof window === 'undefined'` guard and then threw on `window.location.pathname`. That threw inside addNonGitFolder's own catch, so folder-1 never activated; folder-2 then returned early (a project already existed) before reaching the call at all, leaving exactly one activation with no startup seed. Test artifact, not a product defect: a real renderer always has `window.location`, so the seeding path is intact for users. Mocking the module is the convention 7 other suites already use, and keeps product code free of defensive branches that only exist to satisfy a stub. Ablation-proven: removing the mock reproduces the original failure exactly. * fix(renderer): make the web-client check total over a partial window isWebClientLocation() guarded `typeof window === 'undefined'` and then assumed `window.location` existed. A window stubbed without a location cleared the guard and threw on `.pathname`. That matters because this branch put the call on the launch-routing path, where the throw is swallowed by the caller's catch and silently becomes a FAILED LAUNCH rather than a visible error. CI caught it as 9 failures in launch-work-item-direct.test.ts. I previously "fixed" this by mocking the module in the one suite I knew about. That was whack-a-mole against an unbounded set, and it missed this one. The defect is the partial-window assumption, so fix it there: the mock is removed from the onboarding suite and both suites now pass on the hardening alone. Ablation-proven: reverting to the unguarded form reddens 11 tests across the new unit suite and launch-work-item-direct. Gates: tc 0, oxlint 0, changed-code quality 0/58. * Move Codex's Windows structured-chat eligibility onto the host createSupport probe The renderer no longer decides Codex win32 eligibility: launchStructuredAgentSession probes agentSession.createSupport for both providers, the host answers via supportsCodexStructuredLocation (process start-time proof + WSL refusal), and the create path re-checks live. Deletes the client-side windows gate module and its routing inputs (windowsProcessStartTime, worktreeUsesWslPath, isWebClient, platform) from six call sites. Splits killCodexAppServerProcessTree out of codex-app-server-session to hold the max-lines ceiling without a disable. * fix(ci): keep pnpm lockfile stable * test(windows): align foreground snapshot flags * Restore main's pane-snapshot flag contract Main asks for CreationTime on both projections; this branch's hot-path isolation went away with the async probe it served. --------- Co-authored-by: Orca Worker Co-authored-by: Merge Sim Co-authored-by: Merge Sim --- .../rebuild-native-deps-node-pty.test.mjs | 22 +++ .../rebuild-native-deps-test-fixtures.mjs | 39 +++- .../windows-process-tree-gyp-rebuild.mjs | 42 ++++ .../windows-process-tree-gyp-rebuild.test.mjs | 47 +++++ config/tsconfig.cli.json | 1 + .../codex/codex-app-server-client.test.ts | 3 +- src/main/codex/codex-app-server-client.ts | 10 +- .../codex-app-server-process-tree-kill.ts | 76 +++++++ src/main/codex/codex-app-server-session.ts | 73 +------ ...codex-structured-launch-resolution.test.ts | 22 ++- .../codex-structured-launch-resolution.ts | 10 + .../codex-structured-location-support.test.ts | 47 +++++ .../codex-structured-location-support.ts | 8 +- .../codex/codex-structured-session-adapter.ts | 3 +- .../codex/codex-structured-session-state.ts | 2 + .../structured-agent-session-acquisition.ts | 78 ++++++++ .../structured-agent-session-attach-flow.ts | 132 ++++++------- ...uctured-agent-session-host-handoff.test.ts | 186 ++++++++++++++++++ .../structured-agent-session-host-handoff.ts | 10 + ...nt-session-processless-reservation.test.ts | 145 ++++++++++++++ ...ructured-agent-session-provider-support.ts | 32 ++- src/main/own-chromium-tree-kill-guard.test.ts | 2 +- ...refused-tree-kill-root-termination.test.ts | 2 +- ...ocess-identity-probe-windows-batch.test.ts | 42 ++++ .../agent-session-process-identity-probe.ts | 22 +++ src/main/runtime/orca-runtime-get-status.ts | 6 + ...lve-recovered-structured-tui-transcript.ts | 23 ++- .../orchestration-worker-start-mode.test.ts | 14 +- .../orchestration-worker-start-mode.ts | 3 - .../methods/orchestration/worker/workers.ts | 3 +- .../methods/structured-agent-session-gate.ts | 5 +- .../structured-agent-session-runtime.test.ts | 31 +++ ...ctured-agent-session-support-probe.test.ts | 39 ++++ ...-vault-session-resume-in-chat-workspace.ts | 2 - .../folder-workspace-composer-submit.ts | 7 +- .../composer-state/full-creation-execution.ts | 3 +- .../quick-creation-execution.ts | 2 - .../src/lib/agent-launch-routing.test.ts | 68 ++----- src/renderer/src/lib/agent-launch-routing.ts | 2 - .../src/lib/launch-agent-in-new-tab.ts | 1 - .../launch-structured-agent-session.test.ts | 182 ++++++++--------- .../lib/launch-structured-agent-session.ts | 11 +- ...unch-work-item-direct-route-preparation.ts | 1 - .../lib/onboarding-folder-agent-startup.ts | 1 - ...nt-session-launch-refusal-fallback.test.ts | 3 + ...ent-session-launch-resume-identity.test.ts | 15 +- .../src/lib/web-client-location.test.ts | 43 ++++ src/renderer/src/lib/web-client-location.ts | 7 +- ...windows-terminal-capabilities-race.test.ts | 80 ++++++++ .../lib/windows-terminal-capabilities.test.ts | 13 +- .../src/lib/windows-terminal-capabilities.ts | 2 + .../lib/windows-terminal-capability-read.ts | 12 +- ...indows-terminal-capability-reprobe.test.ts | 34 +++- .../windows-terminal-capability-reprobe.ts | 14 +- .../child-process-import-allowlist.txt | 1 - .../child-process-import-boundary.test.ts | 2 +- src/shared/runtime-session-contracts.ts | 2 + ...tructured-native-chat-launch-route.test.ts | 13 +- .../structured-native-chat-launch-route.ts | 8 - 59 files changed, 1324 insertions(+), 385 deletions(-) create mode 100644 src/main/codex/codex-app-server-process-tree-kill.ts create mode 100644 src/main/codex/codex-structured-location-support.test.ts create mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts create mode 100644 src/main/runtime/agent-session-process-identity-probe-windows-batch.test.ts create mode 100644 src/renderer/src/lib/web-client-location.test.ts create mode 100644 src/renderer/src/lib/windows-terminal-capabilities-race.test.ts diff --git a/config/scripts/rebuild-native-deps-node-pty.test.mjs b/config/scripts/rebuild-native-deps-node-pty.test.mjs index 871732dd53d..c3a8f9bbd83 100644 --- a/config/scripts/rebuild-native-deps-node-pty.test.mjs +++ b/config/scripts/rebuild-native-deps-node-pty.test.mjs @@ -173,6 +173,28 @@ describe('rebuild-native-deps patched node-pty rebuild', () => { } }) + it('refuses a Windows rebuild when the process creation-time patch is missing', () => { + const projectDir = mkTempProject() + + try { + writeFakeUsableElectronPackage(projectDir, { platform: 'win32' }) + writeFakeElectronRebuild(projectDir) + writeFakeNodePtyConptyPayload(projectDir, 'x64') + writeFakeWindowsProcessTreeWithNodeAddonApi(projectDir, { creationTimePatchApplied: false }) + + const result = runRebuildScript( + projectDir, + { npm_config_platform: 'win32', npm_config_arch: 'x64' }, + ['--platform=win32', '--arch=x64', '--force'] + ) + + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('process creation-time patch') + } finally { + removeTreeSync(projectDir) + } + }) + it('restores the ConPTY runtime payload after a Windows Electron rebuild', () => { const projectDir = mkTempProject() diff --git a/config/scripts/rebuild-native-deps-test-fixtures.mjs b/config/scripts/rebuild-native-deps-test-fixtures.mjs index 2cb7d8ba8b4..db5af45a454 100644 --- a/config/scripts/rebuild-native-deps-test-fixtures.mjs +++ b/config/scripts/rebuild-native-deps-test-fixtures.mjs @@ -374,13 +374,18 @@ export function writeFakeWindowsProcessTree(projectDir) { export function writeFakeWindowsProcessTreeWithNodeAddonApi( projectDir, - { commandLinePatchApplied = true } = {} + { commandLinePatchApplied = true, creationTimePatchApplied = true } = {} ) { const processTreeDir = join(projectDir, 'node_modules', '@vscode', 'windows-process-tree') const nodeAddonApiDir = join(processTreeDir, 'node_modules', 'node-addon-api') mkdirSync(nodeAddonApiDir, { recursive: true }) writeFileSync(join(processTreeDir, 'package.json'), '{"dependencies":{"node-addon-api":"*"}}\n') - writeFileSync(join(processTreeDir, 'index.js'), 'module.exports = {}\n') + writeFileSync( + join(processTreeDir, 'index.js'), + creationTimePatchApplied + ? 'exports.ProcessDataFlag = { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 }\n' + : 'exports.ProcessDataFlag = { None: 0, Memory: 1, CommandLine: 2 }\n' + ) mkdirSync(join(processTreeDir, 'src'), { recursive: true }) writeFileSync( join(processTreeDir, 'src', 'process_commandline.cc'), @@ -388,6 +393,36 @@ export function writeFakeWindowsProcessTreeWithNodeAddonApi( ? '// kProcessCommandLineInformation = 60\n' : unpatchedWindowsProcessTreeCommandLineSource() ) + writeFileSync( + join(processTreeDir, 'src', 'process.h'), + creationTimePatchApplied + ? 'enum ProcessDataFlags { NONE = 0, MEMORY = 1, COMMANDLINE = 2, CREATIONTIME = 4 };\nULONGLONG creationTimeMs;\n' + : 'enum ProcessDataFlags { NONE = 0, MEMORY = 1, COMMANDLINE = 2 };\n' + ) + writeFileSync( + join(processTreeDir, 'src', 'process.cc'), + creationTimePatchApplied + ? 'GetProcessCreationTime(pinfo);\nGetProcessTimes(hProcess, &creationTime, &exitTime, &kernelTime, &userTime);\n' + : 'GetProcessMemoryUsage(pinfo);\n' + ) + writeFileSync( + join(processTreeDir, 'src', 'process_worker.cc'), + creationTimePatchApplied ? 'object.Set("creationTimeMs", process.creationTimeMs);\n' : '\n' + ) + mkdirSync(join(processTreeDir, 'lib'), { recursive: true }) + writeFileSync( + join(processTreeDir, 'lib', 'index.js'), + creationTimePatchApplied ? 'exports.ProcessDataFlag["CreationTime"] = 4;\n' : '\n' + ) + writeFileSync( + join(processTreeDir, 'lib', 'index.ts'), + creationTimePatchApplied ? 'export enum ProcessDataFlag { CreationTime = 4 }\n' : '\n' + ) + mkdirSync(join(processTreeDir, 'typings'), { recursive: true }) + writeFileSync( + join(processTreeDir, 'typings', 'windows-process-tree.d.ts'), + creationTimePatchApplied ? 'creationTimeMs?: number\n' : '\n' + ) writeFileSync(join(nodeAddonApiDir, 'package.json'), '{"name":"node-addon-api"}\n') writeFileSync(join(nodeAddonApiDir, 'napi.h'), '// napi.h\n') writeFileSync(join(nodeAddonApiDir, 'napi-inl.h'), '// napi-inl.h\n') diff --git a/config/scripts/windows-process-tree-gyp-rebuild.mjs b/config/scripts/windows-process-tree-gyp-rebuild.mjs index 20d91e55497..6f21fb2a153 100644 --- a/config/scripts/windows-process-tree-gyp-rebuild.mjs +++ b/config/scripts/windows-process-tree-gyp-rebuild.mjs @@ -33,6 +33,17 @@ export const WINDOWS_PROCESS_TREE_PATCH_PATH = join( /** Only the patched reader defines this; the upstream one walks the PEB. */ const COMMAND_LINE_PATCH_MARKER = 'kProcessCommandLineInformation' +const CREATION_TIME_PATCH_MARKERS = [ + ['src/process.h', 'CREATIONTIME = 4'], + ['src/process.h', 'ULONGLONG creationTimeMs'], + ['src/process.cc', 'GetProcessCreationTime(pinfo)'], + ['src/process.cc', 'GetProcessTimes(hProcess, &creationTime'], + ['src/process_worker.cc', 'object.Set("creationTimeMs"'], + ['lib/index.js', '["CreationTime"] = 4'], + ['lib/index.ts', 'CreationTime = 4'], + ['typings/windows-process-tree.d.ts', 'creationTimeMs?: number'] +] + export const WINDOWS_PROCESS_TREE_NODE_ADDON_API_HEADERS = [ 'napi.h', 'napi-inl.h', @@ -83,6 +94,36 @@ export function inspectWindowsProcessTreeAddon(addonPath) { return readFileSync(addonPath).includes(FLAGGED_IMPORT) ? 'unpatched' : 'clean' } +export function assertWindowsProcessTreeCreationTimePatch( + packageDir = WINDOWS_PROCESS_TREE_PACKAGE_DIR +) { + for (const [relativePath, expected] of CREATION_TIME_PATCH_MARKERS) { + const filePath = join(packageDir, relativePath) + if (!existsSync(filePath)) { + throw new Error( + `${filePath} is missing, so the process creation-time patch cannot be verified. ` + + 'Run pnpm install.' + ) + } + if (!readFileSync(filePath, 'utf8').includes(expected)) { + throw new Error( + `${relativePath} does not contain the process creation-time patch (${expected}). ` + + 'Run pnpm install.' + ) + } + } +} + +export function assertWindowsProcessTreeRuntimeCreationTime(windowsProcessTree) { + if (windowsProcessTree?.ProcessDataFlag?.CreationTime !== 4) { + throw new Error( + '@vscode/windows-process-tree does not expose ProcessDataFlag.CreationTime, so native ' + + 'Windows structured agent-session process ownership cannot be PID-reuse safe. Rebuild it ' + + '(pnpm run rebuild:electron) rather than using the published prebuild.' + ) + } +} + /** * Refuse to compile or load the upstream command-line reader. * @@ -159,6 +200,7 @@ export function ensureWindowsProcessTreeCommandLinePatch( rmSync(windowsProcessTreeAddonPath(packageDir), { force: true }) repaired = true } + assertWindowsProcessTreeCreationTimePatch(packageDir) return repaired } diff --git a/config/scripts/windows-process-tree-gyp-rebuild.test.mjs b/config/scripts/windows-process-tree-gyp-rebuild.test.mjs index f2939b71179..56bd9a385c7 100644 --- a/config/scripts/windows-process-tree-gyp-rebuild.test.mjs +++ b/config/scripts/windows-process-tree-gyp-rebuild.test.mjs @@ -12,12 +12,15 @@ import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { + assertWindowsProcessTreeCreationTimePatch, + assertWindowsProcessTreeRuntimeCreationTime, inspectWindowsProcessTreeAddon, nodeGypRebuildInvocation, stageWindowsProcessTreeNodeAddonApiHeaders, WINDOWS_PROCESS_TREE_NODE_ADDON_API_HEADERS, WINDOWS_PROCESS_TREE_PACKAGE_DIR } from './windows-process-tree-gyp-rebuild.mjs' +import { writeFakeWindowsProcessTreeWithNodeAddonApi } from './rebuild-native-deps-test-fixtures.mjs' describe('windows-process-tree node-gyp rebuild', () => { it("resolves node-addon-api's gyp target from the rebuild cwd", () => { @@ -97,3 +100,47 @@ describe('inspecting a compiled windows-process-tree addon', () => { expect(inspectWindowsProcessTreeAddon(staged)).toBe('unpatched') }) }) + +describe('windows-process-tree CreationTime patch assertion', () => { + let dir + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-windows-process-tree-creation-time-')) + }) + afterEach(() => { + rmSync(dir, { recursive: true, force: true }) + }) + + it('accepts a package whose source and JS surfaces expose process creation time', () => { + writeFakeWindowsProcessTreeWithNodeAddonApi(dir) + + expect(() => + assertWindowsProcessTreeCreationTimePatch( + join(dir, 'node_modules', '@vscode', 'windows-process-tree') + ) + ).not.toThrow() + }) + + it('rejects a package missing the process creation-time patch', () => { + writeFakeWindowsProcessTreeWithNodeAddonApi(dir, { creationTimePatchApplied: false }) + + expect(() => + assertWindowsProcessTreeCreationTimePatch( + join(dir, 'node_modules', '@vscode', 'windows-process-tree') + ) + ).toThrow('process creation-time patch') + }) + + it('requires the runtime ProcessDataFlag.CreationTime enum', () => { + expect(() => + assertWindowsProcessTreeRuntimeCreationTime({ + ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2, CreationTime: 4 } + }) + ).not.toThrow() + expect(() => + assertWindowsProcessTreeRuntimeCreationTime({ + ProcessDataFlag: { None: 0, Memory: 1, CommandLine: 2 } + }) + ).toThrow('ProcessDataFlag.CreationTime') + }) +}) diff --git a/config/tsconfig.cli.json b/config/tsconfig.cli.json index 80cf4a511f2..a23d90e6a1e 100644 --- a/config/tsconfig.cli.json +++ b/config/tsconfig.cli.json @@ -32,6 +32,7 @@ "../src/main/codex/codex-app-server-capability-cache.ts", "../src/main/codex/codex-app-server-capability-signal.ts", "../src/main/codex/codex-app-server-client.ts", + "../src/main/codex/codex-app-server-process-tree-kill.ts", "../src/main/codex/codex-app-server-record-reader.ts", "../src/main/codex/codex-app-server-session.ts", "../src/main/codex/codex-config-mirror.ts", diff --git a/src/main/codex/codex-app-server-client.test.ts b/src/main/codex/codex-app-server-client.test.ts index b845d3a9694..ce98288bdf0 100644 --- a/src/main/codex/codex-app-server-client.test.ts +++ b/src/main/codex/codex-app-server-client.test.ts @@ -11,7 +11,8 @@ import { runCodexHookTrustGrantSession, type CodexHookTrustGrantRequest } from './codex-app-server-client' -import { killCodexAppServerProcessTree, runCodexAppServerSession } from './codex-app-server-session' +import { killCodexAppServerProcessTree } from './codex-app-server-process-tree-kill' +import { runCodexAppServerSession } from './codex-app-server-session' // Stub codex app-server speaking the same JSONL protocol: initialize → // initialized → hooks/list → config/batchWrite → hooks/list. Scenario-driven diff --git a/src/main/codex/codex-app-server-client.ts b/src/main/codex/codex-app-server-client.ts index 8c95562e66c..efdee5de8bf 100644 --- a/src/main/codex/codex-app-server-client.ts +++ b/src/main/codex/codex-app-server-client.ts @@ -1,4 +1,5 @@ -import { spawn } from 'node:child_process' +import type { ChildProcessHandle, ProcessSpec } from '../../shared/child-process/process-spec' +import { spawnProcess } from '../../shared/child-process/run-process' import { normalizeHookTrustKeyForLookup } from './config-toml-trust' import { runCodexAppServerSession, type CodexAppServerInvocation } from './codex-app-server-session' @@ -105,7 +106,12 @@ function collectHookListings(result: unknown): CodexHookListing[] { */ export async function runCodexHookTrustGrantSession( request: CodexHookTrustGrantRequest, - spawnImpl: typeof spawn = spawn + spawnImpl: ( + program: string, + args: string[], + options: Record + ) => ChildProcessHandle = (program, args, options) => + spawnProcess({ program, args, ...options } as ProcessSpec) ): Promise { return runCodexAppServerSession( request.invocation, diff --git a/src/main/codex/codex-app-server-process-tree-kill.ts b/src/main/codex/codex-app-server-process-tree-kill.ts new file mode 100644 index 00000000000..315246aaa9f --- /dev/null +++ b/src/main/codex/codex-app-server-process-tree-kill.ts @@ -0,0 +1,76 @@ +import { spawnProcess } from '../../shared/child-process/run-process' +import type { ChildProcessHandle, ProcessSpec } from '../../shared/child-process/process-spec' +import { admitProcessTreeKill } from '../../shared/child-process/process-tree-kill-gate' + +/** Spawn seam for tests; production always goes through the hardened spawnProcess wrapper. */ +export type CodexAppServerSpawn = ( + program: string, + args: string[], + options: Record +) => ChildProcessHandle + +export const spawnCodexAppServerProcess: CodexAppServerSpawn = (program, args, options) => + spawnProcess({ program, args, ...options } as ProcessSpec) + +export function killCodexAppServerProcessTree( + child: Pick, + options: { platform?: NodeJS.Platform; spawnImpl?: CodexAppServerSpawn } = {} +): void { + const platform = options.platform ?? process.platform + const spawnImpl = options.spawnImpl ?? spawnCodexAppServerProcess + if (platform === 'win32' && child.pid) { + if ( + !admitProcessTreeKill({ + pid: child.pid, + site: 'codex-app-server-session-deadline', + scope: 'win-taskkill-tree' + }) + ) { + // Refusal blocks the tree walk, not the termination: the root kill is + // handle-addressed, so it cannot reach the recycled pid we refused. + child.kill('SIGKILL') + return + } + try { + // Why: npm-installed Codex runs behind cmd.exe; killing only that wrapper + // leaves the app-server child alive after a timeout or failed shutdown. + const killer = spawnImpl('taskkill', ['/pid', String(child.pid), '/t', '/f'], { + stdio: 'ignore', + windowsHide: true + }) + let fellBack = false + const killDirectChild = (): void => { + if (!fellBack) { + fellBack = true + child.kill('SIGKILL') + } + } + killer.on('error', killDirectChild) + killer.on('exit', (code) => { + if (code !== 0) { + killDirectChild() + } + }) + killer.unref() + return + } catch { + // Fall through to the direct-child best effort when taskkill cannot start. + } + } + if (child.pid) { + try { + // npm/package-manager launchers insert a shim child on POSIX. Reap its + // direct descendants before signalling the wrapper itself. + const descendants = spawnImpl('pkill', ['-KILL', '-P', String(child.pid)], { + stdio: 'ignore' + }) + // A missing pkill surfaces as an async 'error' event, and an unhandled one + // takes down the main process. + descendants.on('error', () => undefined) + descendants.unref() + } catch { + // The direct kill below remains the fallback when pkill is unavailable. + } + } + child.kill('SIGKILL') +} diff --git a/src/main/codex/codex-app-server-session.ts b/src/main/codex/codex-app-server-session.ts index cef7f40c66b..6db33b4c85d 100644 --- a/src/main/codex/codex-app-server-session.ts +++ b/src/main/codex/codex-app-server-session.ts @@ -1,9 +1,13 @@ -import { spawn, type ChildProcess, type ChildProcessWithoutNullStreams } from 'node:child_process' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { waitForProcessExitUntil } from './codex-process-exit-deadline' import { stderrIndicatesMissingAppServer } from './codex-app-server-capability-signal' import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' +import { + killCodexAppServerProcessTree, + spawnCodexAppServerProcess, + type CodexAppServerSpawn +} from './codex-app-server-process-tree-kill' import { createCodexAppServerRecordReader } from './codex-app-server-record-reader' -import { admitProcessTreeKill } from '../../shared/child-process/process-tree-kill-gate' // Why: `codex app-server` is Orca's sanctioned RPC surface into Codex-owned // state (hook trust hashes, the sqlite thread index). This module owns the @@ -68,69 +72,6 @@ export type CodexAppServerRpc = { const JSON_RPC_METHOD_NOT_FOUND = -32601 const STDERR_TAIL_MAX_BYTES = 8192 -export function killCodexAppServerProcessTree( - child: Pick, - options: { platform?: NodeJS.Platform; spawnImpl?: typeof spawn } = {} -): void { - const platform = options.platform ?? process.platform - const spawnImpl = options.spawnImpl ?? spawn - if (platform === 'win32' && child.pid) { - if ( - !admitProcessTreeKill({ - pid: child.pid, - site: 'codex-app-server-session-deadline', - scope: 'win-taskkill-tree' - }) - ) { - // Refusal blocks the tree walk, not the termination: the root kill is - // handle-addressed, so it cannot reach the recycled pid we refused. - child.kill('SIGKILL') - return - } - try { - // Why: npm-installed Codex runs behind cmd.exe; killing only that wrapper - // leaves the app-server child alive after a timeout or failed shutdown. - const killer = spawnImpl('taskkill', ['/pid', String(child.pid), '/t', '/f'], { - stdio: 'ignore', - windowsHide: true - }) - let fellBack = false - const killDirectChild = (): void => { - if (!fellBack) { - fellBack = true - child.kill('SIGKILL') - } - } - killer.on('error', killDirectChild) - killer.on('exit', (code) => { - if (code !== 0) { - killDirectChild() - } - }) - killer.unref() - return - } catch { - // Fall through to the direct-child best effort when taskkill cannot start. - } - } - if (child.pid) { - try { - // npm/package-manager launchers insert a shim child on POSIX. Reap its - // direct descendants before signalling the wrapper itself. - const descendants = spawnImpl('pkill', ['-KILL', '-P', String(child.pid)], { - stdio: 'ignore' - }) - // A missing pkill surfaces as an async 'error' event, and an unhandled one - // takes down the main process. - descendants.on('error', () => undefined) - descendants.unref() - } catch { - // The direct kill below remains the fallback when pkill is unavailable. - } - } - child.kill('SIGKILL') -} - /** Codex answering "no such method" is the only response that proves the RPC * surface is absent rather than temporarily failing. */ export function isCodexMethodNotFoundError(error: unknown): boolean { @@ -152,7 +93,7 @@ export function isCodexMethodNotFoundError(error: unknown): boolean { export async function runCodexAppServerSession( invocation: CodexAppServerInvocation, body: (rpc: CodexAppServerRpc) => Promise, - spawnImpl: typeof spawn = spawn + spawnImpl: CodexAppServerSpawn = spawnCodexAppServerProcess ): Promise { // Why: a default-home grant must run against the real ~/.codex, so strip an // inherited CODEX_HOME (envToDelete) after applying the overlay, not before. diff --git a/src/main/codex/codex-structured-launch-resolution.test.ts b/src/main/codex/codex-structured-launch-resolution.test.ts index 484f7c1ee80..de83e74c6c8 100644 --- a/src/main/codex/codex-structured-launch-resolution.test.ts +++ b/src/main/codex/codex-structured-launch-resolution.test.ts @@ -44,7 +44,8 @@ function resolverFor( store: { getRecord: () => value } as unknown as AgentSessionRecordStore, resolveWorkspacePath, resolveCommand: () => '/usr/local/bin/codex', - resolveRollout + resolveRollout, + isWindowsProcessStartTimeAvailable: () => true }) } @@ -68,7 +69,8 @@ describe('codex structured launch resolution', () => { const resolveLaunch = createCodexStructuredLaunchResolver({ store: { getRecord: () => record() } as unknown as AgentSessionRecordStore, resolveWorkspacePath: async () => String.raw`C:\workspaces\orca`, - resolveCommand: () => command + resolveCommand: () => command, + isWindowsProcessStartTimeAvailable: () => true }) await expect(resolveLaunch({ identity: IDENTITY })).resolves.toMatchObject({ @@ -78,6 +80,22 @@ describe('codex structured launch resolution', () => { }) }) + it('fails closed before resolving a Windows launch without creation-time proof', async () => { + await withPlatform('win32', async () => { + const resolveWorkspacePath = vi.fn(async () => String.raw`C:\workspaces\orca`) + const resolveLaunch = createCodexStructuredLaunchResolver({ + store: { getRecord: () => record() } as unknown as AgentSessionRecordStore, + resolveWorkspacePath, + isWindowsProcessStartTimeAvailable: () => false + }) + + await expect(resolveLaunch({ identity: IDENTITY })).rejects.toThrow( + 'Windows process creation-time proof' + ) + expect(resolveWorkspacePath).not.toHaveBeenCalled() + }) + }) + it('resumes the last thread this session actually proved, not one a caller names', async () => { const launch = await resolverFor( record({ diff --git a/src/main/codex/codex-structured-launch-resolution.ts b/src/main/codex/codex-structured-launch-resolution.ts index b1cc7854808..d395ee87c12 100644 --- a/src/main/codex/codex-structured-launch-resolution.ts +++ b/src/main/codex/codex-structured-launch-resolution.ts @@ -13,6 +13,7 @@ import { resolveCodexCommand } from '../codex-cli/command' import type { AgentSessionRecordStore } from '../runtime/agent-session-record-store' import type { CodexStructuredLaunch } from './codex-structured-session-adapter' import { resolvePinnedCodexRolloutProof } from './codex-tui-rollout-proof' +import { isWindowsProcessStartTimeAvailable } from '../windows/windows-process-table' export type CodexStructuredLaunchResolverDeps = { store: AgentSessionRecordStore @@ -24,6 +25,8 @@ export type CodexStructuredLaunchResolverDeps = { /** Fresh shell/configured environment for this spawn; never written to the session record. */ resolveEnvironment?: () => Promise resolveRollout?: typeof resolvePinnedCodexRolloutProof + /** Test seam for the host capability; production uses the native process table. */ + isWindowsProcessStartTimeAvailable?: () => boolean } export function createCodexStructuredLaunchResolver( @@ -46,6 +49,13 @@ export function createCodexStructuredLaunchResolver( `codex structured sessions run on the local host, not ${location.executionHostId}` ) } + // Refuse before resolving launch data; a PID alone cannot prove Windows ownership. + if ( + process.platform === 'win32' && + !(deps.isWindowsProcessStartTimeAvailable ?? isWindowsProcessStartTimeAvailable)() + ) { + throw new Error('codex structured sessions require Windows process creation-time proof') + } if (accountHome.variable !== 'CODEX_HOME') { throw new Error(`codex sessions pin CODEX_HOME, not ${accountHome.variable}`) } diff --git a/src/main/codex/codex-structured-location-support.test.ts b/src/main/codex/codex-structured-location-support.test.ts new file mode 100644 index 00000000000..324568956d8 --- /dev/null +++ b/src/main/codex/codex-structured-location-support.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import type { AgentSessionExecutionLocation } from '../../shared/agent-session-record' +import { supportsCodexStructuredLocation } from './codex-structured-location-support' + +const LOCAL_WINDOWS_LOCATION: AgentSessionExecutionLocation = { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'folder' +} + +const WSL_WINDOWS_LOCATION: AgentSessionExecutionLocation = { + ...LOCAL_WINDOWS_LOCATION, + wslDistro: 'Ubuntu' +} + +function withPlatform(platform: NodeJS.Platform, run: () => T): T { + const original = process.platform + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + try { + return run() + } finally { + Object.defineProperty(process, 'platform', { configurable: true, value: original }) + } +} + +describe('Codex structured location support', () => { + it('uses the injected Windows identity capability for location admission', () => { + let proofAvailable = false + withPlatform('win32', () => { + expect(supportsCodexStructuredLocation(LOCAL_WINDOWS_LOCATION, () => proofAvailable)).toBe( + false + ) + proofAvailable = true + expect(supportsCodexStructuredLocation(LOCAL_WINDOWS_LOCATION, () => proofAvailable)).toBe( + true + ) + }) + }) + + it('rejects WSL locations while retaining native folder support on Windows', () => { + withPlatform('win32', () => { + expect(supportsCodexStructuredLocation(WSL_WINDOWS_LOCATION, () => true)).toBe(false) + expect(supportsCodexStructuredLocation(LOCAL_WINDOWS_LOCATION, () => true)).toBe(true) + }) + }) +}) diff --git a/src/main/codex/codex-structured-location-support.ts b/src/main/codex/codex-structured-location-support.ts index 915d9edaa83..ad0bbefa4d3 100644 --- a/src/main/codex/codex-structured-location-support.ts +++ b/src/main/codex/codex-structured-location-support.ts @@ -2,10 +2,14 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' import type { AgentSessionExecutionLocation } from '../../shared/agent-session-record' import { isWindowsProcessStartTimeAvailable } from '../windows/windows-process-table' -export function supportsCodexStructuredLocation(location: AgentSessionExecutionLocation): boolean { +export function supportsCodexStructuredLocation( + location: AgentSessionExecutionLocation, + // Injected by the adapter, which owns this dep for every other Codex gate too. + hasWindowsProcessStartTimeProof: () => boolean = isWindowsProcessStartTimeAvailable +): boolean { return ( location.executionHostId === LOCAL_EXECUTION_HOST_ID && location.wslDistro === null && - (process.platform !== 'win32' || isWindowsProcessStartTimeAvailable()) + (process.platform !== 'win32' || hasWindowsProcessStartTimeProof()) ) } diff --git a/src/main/codex/codex-structured-session-adapter.ts b/src/main/codex/codex-structured-session-adapter.ts index afa881f8254..5b551c8b01e 100644 --- a/src/main/codex/codex-structured-session-adapter.ts +++ b/src/main/codex/codex-structured-session-adapter.ts @@ -74,7 +74,8 @@ export class CodexStructuredSessionAdapter implements StructuredAgentSessionAdap }) } - supportsLocation = supportsCodexStructuredLocation + supportsLocation = (location: Parameters[0]): boolean => + supportsCodexStructuredLocation(location, this.deps.isWindowsProcessStartTimeAvailable) acquire = (input: StructuredAgentSessionAcquireInput): Promise => acquireCodexStructuredSession({ diff --git a/src/main/codex/codex-structured-session-state.ts b/src/main/codex/codex-structured-session-state.ts index 2f805e8570f..5fd82f22ff9 100644 --- a/src/main/codex/codex-structured-session-state.ts +++ b/src/main/codex/codex-structured-session-state.ts @@ -41,6 +41,8 @@ export type CodexStructuredSessionAdapterDeps = { resolveLaunch: (input: { identity: AgentSessionJournalIdentity }) => Promise + /** Host capability seam; production uses the native Windows process table. */ + isWindowsProcessStartTimeAvailable?: () => boolean onEvent?: (event: CodexStructuredSessionEvent) => void openConnection?: typeof openCodexAppServerConnection readProcessStartTime?: (pid: number) => Promise diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts new file mode 100644 index 00000000000..cbaafa5ff32 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts @@ -0,0 +1,78 @@ +import { isDeepStrictEqual } from 'node:util' +import type { AgentSessionRecord } from '../../../shared/agent-session-record' +import { + AgentSessionPreSpawnError, + isAgentSessionPreSpawnError, + rethrowAfterAgentSessionAcquisitionCleanup +} from './structured-agent-session-adapter' +import { journalIdentityFor } from './structured-agent-session-attach' +import type { AttachFlowInput } from './structured-agent-session-attach-flow' +import { readNativeSessionOptions } from './structured-agent-session-option-restoration' + +/** A reservation with no process behind it is only a promise to spawn; the + * adapter makes it real and the store then grants the writer. */ +export async function acquireOwner( + input: AttachFlowInput, + record: AgentSessionRecord +): Promise<{ record: AgentSessionRecord; acquisitionGeneration: string | null }> { + const fence = record.lease.runtimeFence + const spawnToken = record.lease.reservedSpawnToken + if (!spawnToken) { + throw new Error('agent_session_ownership_unknown') + } + // Pre-spawn proof is single-use: this retry may create a child after the durable clear. + try { + try { + record = await input.store.setReservationProcesslessProof({ + sessionId: record.sessionId, + fence, + spawnToken, + processlessAt: null, + now: input.now() + }) + await input.onAcquiring?.() + } catch (error) { + throw new AgentSessionPreSpawnError(error) + } + const acquired = await input.adapter.acquire({ + identity: journalIdentityFor(record, input.params), + fence, + // Retries must recover the original reservation, not mint a second child. + spawnToken, + ...(record.options ? { options: record.options } : {}), + ...(input.eventSink ? { events: input.eventSink } : {}) + }) + const options = await readNativeSessionOptions({ + adapter: input.adapter, + sessionId: record.sessionId, + fence, + ...(record.options ? { priorOptions: record.options } : {}) + }) + if (record.lease.ownerProcess === null) { + await input.store.commitProcessIdentity({ + sessionId: record.sessionId, + fence, + process: acquired.process, + now: input.now() + }) + } else if (!isDeepStrictEqual(record.lease.ownerProcess, acquired.process)) { + throw new Error('agent_session_ownership_unknown') + } + const proved = await input.store.proveOwner({ + sessionId: record.sessionId, + fence, + link: acquired.link, + now: input.now(), + ...(options ? { options } : {}) + }) + return { + record: proved, + acquisitionGeneration: acquired.acquisitionGeneration ?? null + } + } catch (error) { + if (isAgentSessionPreSpawnError(error)) { + throw error + } + return rethrowAfterAgentSessionAcquisitionCleanup(input.adapter, record.sessionId, error) + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts index 8697e76ba3b..4bbdd51cdf9 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts @@ -5,7 +5,6 @@ // the decisions that must not be client-supplied — the spawn token, the claim // key, the owner probe — and passes them in. -import { isDeepStrictEqual } from 'node:util' import type { AgentSessionAttachResult, AgentSessionMutationResult @@ -16,7 +15,6 @@ import { admitAttachOrRefuse, attachJournal, classifyStoreFailure, - journalIdentityFor, reserveRequestFor, type AgentSessionAttachAuthority, type AgentSessionAttachParams, @@ -24,18 +22,18 @@ import { } from './structured-agent-session-attach' import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter' +import { adapterSupportsCreateIfDeclared } from './structured-agent-session-provider-support' import { AgentSessionAcquisitionExitUnprovenError, AgentSessionAcquisitionRootExitObservedError, AgentSessionAcquisitionRefusal, - AgentSessionPreSpawnError, isAgentSessionPreSpawnError, rethrowAfterAgentSessionAcquisitionCleanup } from './structured-agent-session-adapter' import type { StructuredAgentSessionEventSink } from './structured-agent-session-event-sink' -import { readNativeSessionOptions } from './structured-agent-session-option-restoration' import { resolveAgentSessionReplayOutcome } from './structured-agent-session-replay-outcome' import { readAgentSessionHydrationPage } from './agent-session-history-page' +import { acquireOwner } from './structured-agent-session-acquisition' import { importAdoptedTranscript, prepareAdoptedTranscript @@ -72,15 +70,27 @@ export async function performAttach( input: AttachFlowInput ): Promise> { const { params, store } = input + const unsupported = (): AgentSessionMutationResult => ({ + ok: false, + refusal: { + code: 'structured_agent_session_unsupported', + message: 'This execution host cannot create the requested structured agent session.' + } + }) const sessionId = params.envelope.sessionId const admitted = admitAttachOrRefuse(params) if (!admitted.ok) { return admitted } + // Ensure/recovery bypass create-intent, so recheck before reserving or spawning. + if (!adapterSupportsCreateIfDeclared(input.adapter, params.location, params.agent)) { + return unsupported() + } let record: AgentSessionRecord let acquisitionGeneration: string | null = null let reservedRecord: AgentSessionRecord | null = null + let unsupportedReservationSettlementAttempted = false let replayed = false const preparedTranscript = store.getRecord(sessionId) ? { ok: true as const, items: null } @@ -101,6 +111,21 @@ export async function performAttach( ) record = reserved.record replayed = reserved.disposition === 'replayed' + // Capability can change while the durable reservation is in flight. Recheck + // every reservation at its effect boundary so it cannot bypass the support + // gate, and release a pending reservation that support drift invalidated. + reservedRecord = record + if (!adapterSupportsCreateIfDeclared(input.adapter, params.location, params.agent)) { + if ( + record.lease.claimStatus === 'reserved' && + record.lease.handoffStage === 'new-owner-proving' && + record.lease.reservedSpawnToken + ) { + unsupportedReservationSettlementAttempted = true + await settleUnsupportedReservation(input, record) + } + return unsupported() + } if ( replayed && reserved.operationRow.outcome.status !== 'pending' && @@ -115,7 +140,6 @@ export async function performAttach( return { ok: false, refusal: replay.refusal } } } - reservedRecord = record if (!agentSessionLeaseAdmitsWriter(record.lease)) { const acquired = await acquireOwner(input, record) record = acquired.record @@ -123,7 +147,7 @@ export async function performAttach( } } catch (error) { const spawnToken = reservedRecord?.lease.reservedSpawnToken - if (reservedRecord && spawnToken) { + if (reservedRecord && spawnToken && !unsupportedReservationSettlementAttempted) { // A pre-spawn failure is its own processless proof; the settlement records the // evidence and the failed operation in one durable transaction. const exitProof = isAgentSessionPreSpawnError(error) @@ -217,6 +241,34 @@ export async function performAttach( } } +async function settleUnsupportedReservation( + input: AttachFlowInput, + record: AgentSessionRecord +): Promise { + const spawnToken = record.lease.reservedSpawnToken + if (!spawnToken) { + return + } + try { + await input.store.settleFailedAcquisition({ + sessionId: record.sessionId, + fence: record.lease.runtimeFence, + spawnToken, + callerKey: input.callerKey, + operationId: input.params.envelope.clientOperationId, + outcome: { + status: 'failed', + code: 'structured_agent_session_unsupported', + message: 'Structured session support changed before the provider could start.' + }, + exitProof: 'processless', + now: input.now() + }) + } catch (error) { + throw new AggregateError([error], 'agent session unsupported reservation settlement failed') + } +} + async function settlePostAcquisitionAttachFailure( input: AttachFlowInput, record: AgentSessionRecord, @@ -261,71 +313,3 @@ async function settlePostAcquisitionAttachFailure( } throw cleanupError } - -/** A reservation with no process behind it is only a promise to spawn; the - * adapter makes it real and the store then grants the writer. */ -async function acquireOwner( - input: AttachFlowInput, - record: AgentSessionRecord -): Promise<{ record: AgentSessionRecord; acquisitionGeneration: string | null }> { - const fence = record.lease.runtimeFence - const spawnToken = record.lease.reservedSpawnToken - if (!spawnToken) { - throw new Error('agent_session_ownership_unknown') - } - // Pre-spawn proof is single-use: this retry may create a child after the durable clear. - try { - try { - record = await input.store.setReservationProcesslessProof({ - sessionId: record.sessionId, - fence, - spawnToken, - processlessAt: null, - now: input.now() - }) - await input.onAcquiring?.() - } catch (error) { - throw new AgentSessionPreSpawnError(error) - } - const acquired = await input.adapter.acquire({ - identity: journalIdentityFor(record, input.params), - fence, - // Retries must recover the original reservation, not mint a second child. - spawnToken, - ...(record.options ? { options: record.options } : {}), - ...(input.eventSink ? { events: input.eventSink } : {}) - }) - const options = await readNativeSessionOptions({ - adapter: input.adapter, - sessionId: record.sessionId, - fence, - ...(record.options ? { priorOptions: record.options } : {}) - }) - if (record.lease.ownerProcess === null) { - await input.store.commitProcessIdentity({ - sessionId: record.sessionId, - fence, - process: acquired.process, - now: input.now() - }) - } else if (!isDeepStrictEqual(record.lease.ownerProcess, acquired.process)) { - throw new Error('agent_session_ownership_unknown') - } - const proved = await input.store.proveOwner({ - sessionId: record.sessionId, - fence, - link: acquired.link, - now: input.now(), - ...(options ? { options } : {}) - }) - return { - record: proved, - acquisitionGeneration: acquired.acquisitionGeneration ?? null - } - } catch (error) { - if (isAgentSessionPreSpawnError(error)) { - throw error - } - return rethrowAfterAgentSessionAcquisitionCleanup(input.adapter, record.sessionId, error) - } -} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.ts index 9bf27a11106..bf2a1381b3b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.ts @@ -11,6 +11,7 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' import { createTrackedJournalOpener } from '../agent-session-journal/journal-store-test-open' import { createDeferredStructuredAgentSessionEventSink } from './structured-agent-session-event-sink' +import type { StructuredAgentSessionHostDeps } from './structured-agent-session-host-types' import { acquireNativeHandoffOwner, createStructuredAgentSessionHostHandoff, @@ -202,6 +203,191 @@ describe('native handoff acquisition', () => { expect(order).toEqual(['append-entered', 'append-complete', 'unbind', 'acquire']) }) + + it('refuses an unsupported adapter before unbinding the TUI owner', async () => { + const location: AgentSessionExecutionLocation = { + executionHostId: LOCAL_EXECUTION_HOST_ID, + wslDistro: null, + workspaceId: 'workspace-unsupported', + workspaceKind: 'folder' + } + const operationId = `${now}-00000000000000000000000000000011` + const reserved = await store.reserveOwner({ + sessionId: 'session-handoff-unsupported', + location, + provider: 'codex', + accountHome: { variable: 'CODEX_HOME', path: join(root, 'codex-home') }, + runtimeKind: 'native', + expectedFence: null, + spawnToken: 'unsupported-spawn', + claimKeyId: 'key-1', + handoffOperationId: operationId, + probe: { outcome: 'reservation-unused' }, + operation: { callerKey: 'test', operationId, fingerprint: 'unsupported' }, + now + }) + const journal = await journals.open({ + identity: { + sessionId: 'session-handoff-unsupported', + workspaceId: location.workspaceId, + hostId: location.executionHostId, + agent: 'codex', + providerHandle: { kind: 'codex', threadId: 'unsupported-thread' } + }, + journalDir: join(root, 'unsupported-journal') + }) + const eventSink = createDeferredStructuredAgentSessionEventSink() + eventSink.bind({ journal, fence: reserved.record.lease.runtimeFence, publish: () => undefined }) + const unbind = vi.spyOn(eventSink, 'unbind') + const acquire = vi.fn>() + const adapter = { + supportsLocation: vi.fn(() => false), + acquire + } + const session = { + journal, + params: { + envelope: { + sessionId: 'session-handoff-unsupported', + clientOperationId: `${now}-00000000000000000000000000000012`, + expectedRuntimeFence: reserved.record.lease.runtimeFence, + payloadFingerprint: 'unsupported' + }, + location, + provider: 'codex' as const, + agent: 'codex' as const, + accountHome: { variable: 'CODEX_HOME' as const, path: join(root, 'codex-home') }, + runtimeKind: 'native' as const, + providerHandle: { kind: 'codex' as const, threadId: 'unsupported-thread' } + }, + fence: reserved.record.lease.runtimeFence, + hasProviderChild: false, + acquisitionGeneration: null + } + + await expect( + acquireNativeHandoffOwner( + { + store, + adapter: adapter as never, + journalRoot: root, + claimKeyId: 'key-1' + }, + { + session: () => session, + findSession: () => session, + eventSink: () => eventSink, + flush: async () => undefined, + serialize: async (_sessionId, task) => task(), + subscribers: { + publish: vi.fn(), + reset: vi.fn(), + handoff: vi.fn(), + snapshot: vi.fn() + } as never, + now: () => now + }, + { + sessionId: 'session-handoff-unsupported', + fence: reserved.record.lease.runtimeFence, + spawnToken: 'unsupported-spawn' + } + ) + ).rejects.toThrow('structured_agent_session_unsupported') + expect(unbind).not.toHaveBeenCalled() + expect(acquire).not.toHaveBeenCalled() + }) + + it('rechecks adapter support immediately before handoff acquisition', async () => { + const sessionId = 'session-handoff-drift' + const location: AgentSessionExecutionLocation = { + executionHostId: LOCAL_EXECUTION_HOST_ID, + wslDistro: null, + workspaceId: 'workspace-drift', + workspaceKind: 'folder' + } + const operationId = `${now}-00000000000000000000000000000021` + const reserved = await store.reserveOwner({ + sessionId, + location, + provider: 'codex', + accountHome: { variable: 'CODEX_HOME', path: join(root, 'codex-home') }, + runtimeKind: 'native', + expectedFence: null, + spawnToken: 'drift-spawn', + claimKeyId: 'key-1', + handoffOperationId: operationId, + probe: { outcome: 'reservation-unused' }, + operation: { callerKey: 'test', operationId, fingerprint: 'drift' }, + now + }) + const journal = await journals.open({ + identity: { + sessionId, + workspaceId: location.workspaceId, + hostId: location.executionHostId, + agent: 'codex', + providerHandle: { kind: 'codex', threadId: 'drift-thread' } + }, + journalDir: join(root, 'drift-journal') + }) + const eventSink = createDeferredStructuredAgentSessionEventSink() + eventSink.bind({ journal, fence: reserved.record.lease.runtimeFence, publish: () => undefined }) + const unbind = vi.spyOn(eventSink, 'unbind') + const supportsLocation = vi.fn(() => true) + supportsLocation.mockReturnValueOnce(true).mockReturnValueOnce(false) + const acquire = vi.fn>() + const adapter = { supportsLocation, acquire } + const session = { + journal, + params: { + envelope: { + sessionId, + clientOperationId: `${now}-00000000000000000000000000000022`, + expectedRuntimeFence: reserved.record.lease.runtimeFence, + payloadFingerprint: 'drift' + }, + location, + provider: 'codex' as const, + agent: 'codex' as const, + accountHome: { variable: 'CODEX_HOME' as const, path: join(root, 'codex-home') }, + runtimeKind: 'native' as const, + providerHandle: { kind: 'codex' as const, threadId: 'drift-thread' } + }, + fence: reserved.record.lease.runtimeFence, + hasProviderChild: false, + acquisitionGeneration: null + } + + await expect( + acquireNativeHandoffOwner( + { + store, + adapter: adapter as never, + journalRoot: root, + claimKeyId: 'key-1' + }, + { + session: () => session, + findSession: () => session, + eventSink: () => eventSink, + flush: async () => undefined, + serialize: async (_sessionId, task) => task(), + subscribers: { + publish: vi.fn(), + reset: vi.fn(), + handoff: vi.fn(), + snapshot: vi.fn() + } as never, + now: () => now + }, + { sessionId, fence: reserved.record.lease.runtimeFence, spawnToken: 'drift-spawn' } + ) + ).rejects.toThrow('structured_agent_session_unsupported') + expect(supportsLocation).toHaveBeenCalledTimes(2) + expect(unbind).toHaveBeenCalledOnce() + expect(acquire).not.toHaveBeenCalled() + }) }) describe('handoff status published for a session the host no longer holds', () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.ts index cb316850e5b..7c8c65a5292 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.ts @@ -14,6 +14,7 @@ import { recoverDeadTuiHandoffStatus } from './structured-agent-session-dead-tui import { readNativeSessionOptions } from './structured-agent-session-option-restoration' import type { AgentSessionSubscribers } from './structured-agent-session-subscribers' import { StructuredTuiTranscriptCatchup } from './structured-tui-transcript-catchup' +import { adapterSupportsCreateIfDeclared } from './structured-agent-session-provider-support' import { retryLoadedStructuredAgentSessionSettlement } from './structured-agent-session-settlement-retry' type HostHandoffAccess = { @@ -195,12 +196,21 @@ export async function acquireNativeHandoffOwner( if (!record) { throw new Error('agent_session_identity_required') } + // Native handoff bypasses attach admission; reject before unbinding TUI ownership. + if (!adapterSupportsCreateIfDeclared(deps.adapter, record.location, record.provider)) { + throw new Error('structured_agent_session_unsupported') + } const eventSink = host.eventSink(input.sessionId) const priorBarrier = await eventSink.drained() if (!priorBarrier.ok) { throw priorBarrier.error } eventSink.unbind() + // Recheck immediately before acquisition; capability probes may drift while + // the old TUI event sink is draining. + if (!adapterSupportsCreateIfDeclared(deps.adapter, record.location, record.provider)) { + throw new Error('structured_agent_session_unsupported') + } const acquired = await deps.adapter.acquire({ identity: journalIdentityFor(record, session.params), fence: input.fence, diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-processless-reservation.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-processless-reservation.test.ts index a1b6b39f5e0..0f115da5ebd 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-processless-reservation.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-processless-reservation.test.ts @@ -64,6 +64,151 @@ function attachParams( } describe('processless structured session reservation', () => { + it('refuses an adapter that declares no create support before reserving a lease', async () => { + root = await mkdtemp(join(tmpdir(), 'orca-unsupported-attach-')) + const store = await AgentSessionRecordStore.open({ + directory: join(root, 'store'), + hostId: 'local' + }) + const reserveOwner = vi.spyOn(store, 'reserveOwner') + const acquire = vi.fn() + const adapter = { + supportsCreate: vi.fn(() => false), + acquire, + dispatch: vi.fn(), + cancelTurn: vi.fn(), + answerPrompt: vi.fn(), + setOption: vi.fn() + } as unknown as StructuredAgentSessionAdapter + + await expect( + performAttach({ + store, + adapter, + journalRoot: root, + authority: { + spawnToken: 'spawn-a', + claimKeyId: 'key-1', + handoffOperationId: OPERATION, + probe: { outcome: 'reservation-unused' } + }, + callerKey: 'client-1', + params: attachParams(), + now: () => NOW, + onAttached: () => {} + }) + ).resolves.toMatchObject({ + ok: false, + refusal: { code: 'structured_agent_session_unsupported' } + }) + expect(reserveOwner).not.toHaveBeenCalled() + expect(acquire).not.toHaveBeenCalled() + }) + + it('refuses a replay when adapter support drifts after durable reservation', async () => { + root = await mkdtemp(join(tmpdir(), 'orca-replay-support-drift-')) + const store = await AgentSessionRecordStore.open({ + directory: join(root, 'store'), + hostId: 'local' + }) + const supportsCreate = vi + .fn>() + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + const adapter = { + supportsCreate, + acquire: vi.fn(async ({ fence, spawnToken }) => ({ + process: { hostId: 'local', pid: 4242, processStartTimeMs: NOW, spawnToken }, + link: { + linkId: 'link-1', + handle: { provider: 'codex' as const, threadId: 'thread-1' }, + origin: 'created' as const, + mintedAtFence: fence, + observedAt: NOW + } + })) + } as unknown as StructuredAgentSessionAdapter + const input = { + store, + adapter, + journalRoot: root, + authority: { + spawnToken: 'spawn-a', + claimKeyId: 'key-1', + handoffOperationId: OPERATION, + probe: { outcome: 'reservation-unused' as const } + }, + callerKey: 'client-1', + params: attachParams(), + now: () => NOW, + onAttached: () => {} + } + + await expect(performAttach(input)).resolves.toMatchObject({ ok: true }) + await expect(performAttach(input)).resolves.toMatchObject({ + ok: false, + refusal: { code: 'structured_agent_session_unsupported' } + }) + expect(supportsCreate).toHaveBeenCalledTimes(3) + expect(adapter.acquire).toHaveBeenCalledOnce() + }) + + it('releases a new reservation when support drifts before acquisition', async () => { + root = await mkdtemp(join(tmpdir(), 'orca-support-drift-reservation-')) + const store = await AgentSessionRecordStore.open({ + directory: join(root, 'store'), + hostId: 'local' + }) + const supportsCreate = vi + .fn>() + .mockReturnValueOnce(true) + .mockReturnValueOnce(false) + .mockReturnValueOnce(true) + .mockReturnValueOnce(true) + const acquire = vi.fn() + const adapter = { supportsCreate, acquire } as unknown as StructuredAgentSessionAdapter + const input = { + store, + adapter, + journalRoot: root, + authority: { + spawnToken: 'spawn-drift', + claimKeyId: 'key-1', + handoffOperationId: OPERATION, + probe: { outcome: 'reservation-unused' as const } + }, + callerKey: 'client-1', + params: attachParams(), + now: () => NOW, + onAttached: () => {} + } + + await expect(performAttach(input)).resolves.toMatchObject({ + ok: false, + refusal: { code: 'structured_agent_session_unsupported' } + }) + + expect(acquire).not.toHaveBeenCalled() + expect(store.getRecord(SESSION)?.lease).toMatchObject({ + claimStatus: 'released', + handoffStage: null, + reservedSpawnToken: null, + processlessAt: null, + runtimeFence: 2, + deathEvidence: { kind: 'pid-absent', detail: 'reservation failed before spawn' } + }) + expect(store.listOperationRows()[0]?.outcome).toMatchObject({ + status: 'failed', + code: 'structured_agent_session_unsupported' + }) + await expect(performAttach(input)).resolves.toMatchObject({ + ok: false, + refusal: { code: 'structured_agent_session_unsupported' } + }) + expect(acquire).not.toHaveBeenCalled() + }) + it('settles a pre-spawn failure and its processless evidence in one durable transaction', async () => { root = await mkdtemp(join(tmpdir(), 'orca-processless-reservation-')) const storeDir = join(root, 'store') diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-provider-support.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-provider-support.ts index 99958a2bcb0..15af150c12f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-provider-support.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-provider-support.ts @@ -9,17 +9,35 @@ export function adapterSupportsCreate( location: AgentSessionExecutionLocation, agent: string ): boolean { - return ( - adapter.supportsCreate?.(location, agent) ?? - (agent === 'codex' && (adapter.supportsLocation?.(location) ?? false)) - ) + if (adapter.supportsCreate) { + return adapter.supportsCreate(location, agent) + } + if (agent !== 'codex') { + return false + } + // Older Codex adapters exposed only location support; absence still fails closed here. + return adapter.supportsLocation?.(location) ?? false +} + +/** Honors declared gates while retaining legacy adapters whose acquire path is authoritative. */ +export function adapterSupportsCreateIfDeclared( + adapter: StructuredAgentSessionAdapter, + location: AgentSessionExecutionLocation, + agent: string +): boolean { + if (!adapter.supportsCreate && !adapter.supportsLocation) { + return true + } + return adapterSupportsCreate(adapter, location, agent) } export function adapterSupportsRecord( adapter: StructuredAgentSessionAdapter, record: AgentSessionRecord ): boolean { - return adapter.supportsCreate - ? adapter.supportsCreate(record.location, record.provider) - : record.provider === 'codex' + if (adapter.supportsCreate) { + return adapter.supportsCreate(record.location, record.provider) + } + // Old Codex records stay readable unless the adapter explicitly rejects their location. + return record.provider === 'codex' && (adapter.supportsLocation?.(record.location) ?? true) } diff --git a/src/main/own-chromium-tree-kill-guard.test.ts b/src/main/own-chromium-tree-kill-guard.test.ts index 7b9c30687bc..5bfad815631 100644 --- a/src/main/own-chromium-tree-kill-guard.test.ts +++ b/src/main/own-chromium-tree-kill-guard.test.ts @@ -17,7 +17,7 @@ import { admitSelfInitiatedTreeKill, installMainProcessTreeKillGate } from './own-chromium-tree-kill-guard' -import { killCodexAppServerProcessTree } from './codex/codex-app-server-session' +import { killCodexAppServerProcessTree } from './codex/codex-app-server-process-tree-kill' import { setProcessTreeKillGate } from '../shared/child-process/process-tree-kill-gate' import { resetSelfInitiatedTreeKillLogForTest } from './crash-reporting/self-initiated-tree-kill-log' import { diff --git a/src/main/refused-tree-kill-root-termination.test.ts b/src/main/refused-tree-kill-root-termination.test.ts index ada4b5942a9..3912d6e946e 100644 --- a/src/main/refused-tree-kill-root-termination.test.ts +++ b/src/main/refused-tree-kill-root-termination.test.ts @@ -34,7 +34,7 @@ import { terminateNotebookProcessTree } from './ipc/notebook' import { killLocalPrecheckProcessTree } from './automations/precheck-runner' import { killRecipeProcess } from '../shared/ephemeral-vm-recipe-process' import { killSpawnedCommandTree } from './git/command-runner/spawned-command-tree-kill' -import { killCodexAppServerProcessTree } from './codex/codex-app-server-session' +import { killCodexAppServerProcessTree } from './codex/codex-app-server-process-tree-kill' import { signalProcessTree } from '../shared/child-process/process-tree-termination' import { killSourceControlAgentProcess } from './text-generation/source-control-local-process' import { terminateCodexTurnProcesses } from './codex/codex-structured-turn-processes' diff --git a/src/main/runtime/agent-session-process-identity-probe-windows-batch.test.ts b/src/main/runtime/agent-session-process-identity-probe-windows-batch.test.ts new file mode 100644 index 00000000000..5e8ef48ad62 --- /dev/null +++ b/src/main/runtime/agent-session-process-identity-probe-windows-batch.test.ts @@ -0,0 +1,42 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { isWindowsProcessStartTimeAvailable, readWindowsProcessIdentityTableFresh } = vi.hoisted( + () => ({ + isWindowsProcessStartTimeAvailable: vi.fn(() => true), + readWindowsProcessIdentityTableFresh: vi.fn() + }) +) + +vi.mock('../windows/windows-process-table', async (importOriginal) => ({ + ...(await importOriginal()), + isWindowsProcessStartTimeAvailable, + readWindowsProcessIdentityTableFresh +})) + +const { readProcessStartTimesMs } = await import('./agent-session-process-identity-probe') + +const START_TIME = 1_700_000_000_000 + +afterEach(() => { + isWindowsProcessStartTimeAvailable.mockReset() + isWindowsProcessStartTimeAvailable.mockReturnValue(true) + readWindowsProcessIdentityTableFresh.mockReset() +}) + +describe('Windows owner identity batch probe', () => { + it('reads Windows start times for a batch from one process-table snapshot', async () => { + readWindowsProcessIdentityTableFresh.mockResolvedValue([ + { pid: 4242, ppid: 1, name: 'codex.exe', creationTimeMs: START_TIME }, + { pid: 4243, ppid: 1, name: 'codex.exe', creationTimeMs: START_TIME + 10 } + ]) + + await expect(readProcessStartTimesMs([4242, 4243, 4242], 'win32')).resolves.toEqual( + new Map([ + [4242, START_TIME], + [4243, START_TIME + 10] + ]) + ) + + expect(readWindowsProcessIdentityTableFresh).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/runtime/agent-session-process-identity-probe.ts b/src/main/runtime/agent-session-process-identity-probe.ts index 5d441782ca8..3fa1971b830 100644 --- a/src/main/runtime/agent-session-process-identity-probe.ts +++ b/src/main/runtime/agent-session-process-identity-probe.ts @@ -131,6 +131,25 @@ async function readWindowsProcessStartTimeMs(pid: number): Promise> { + const observed = new Map(pids.map((pid) => [pid, null])) + if (pids.length === 0 || !isWindowsProcessStartTimeAvailable()) { + return observed + } + try { + const table = await readWindowsProcessIdentityTableFresh() + const startTimesByPid = new Map(table.map((row) => [row.pid, row.creationTimeMs ?? null])) + for (const pid of pids) { + observed.set(pid, startTimesByPid.get(pid) ?? null) + } + } catch { + // A missing process table is unknown, never evidence that every owner exited. + } + return observed +} + /** * Process start time is the cross-platform PID-reuse guard when no provider hook can echo the * spawn token back to the owner probe. @@ -160,6 +179,9 @@ export async function readProcessStartTimesMs( const table = await readDarwinProcessStartTimesMs(uniquePids) return new Map(uniquePids.map((pid) => [pid, table.get(pid) ?? null])) } + if (platform === 'win32') { + return readWindowsProcessStartTimesMs(uniquePids) + } return new Map( await Promise.all( uniquePids.map(async (pid) => [pid, await readProcessStartTimeMs(pid, platform)] as const) diff --git a/src/main/runtime/orca-runtime-get-status.ts b/src/main/runtime/orca-runtime-get-status.ts index bd378ea2bf7..d177c8fe64d 100644 --- a/src/main/runtime/orca-runtime-get-status.ts +++ b/src/main/runtime/orca-runtime-get-status.ts @@ -20,6 +20,7 @@ import { browserUnavailableMessage } from '../../shared/runtime-types' import { runtimeTerminalDegradation } from './native-terminal-availability' +import { isWindowsProcessStartTimeAvailable } from '../windows/windows-process-table' import type { RuntimeWorktreeLifecycleEvent } from './orca-runtime-core' import { WORKTREE_CREATE_RESULT_TTL_MS } from './orca-runtime-core' import type { RuntimePtyController } from './runtime-pty-controller-contract' @@ -56,6 +57,10 @@ export class OrcaRuntimeWithGetStatus extends OrcaRuntimeWithGetRuntimeId { const hasOffscreen = !hasRenderer && Boolean(this.offscreenBrowserBackend) const hasHeadlessCommands = runtimeBrowserCommandsFactoryIsHeadless() const canBrowse = hasRenderer || hasOffscreen + // This field reports current Windows process-identity proof. Structured RPC + // support itself stays advertised; agentSession.createSupport owns current eligibility. + const windowsProcessStartTimeAvailable = + process.platform === 'win32' && isWindowsProcessStartTimeAvailable() const capabilities: RuntimeCapability[] = RUNTIME_CAPABILITIES.filter( (capability) => (capability !== 'browser.screencast.v1' || canBrowse) && @@ -110,6 +115,7 @@ export class OrcaRuntimeWithGetStatus extends OrcaRuntimeWithGetRuntimeId { capabilities, ...(degradations.length > 0 ? { degradations } : {}), worktreeCreateIdempotency: { dedupeTtlMs: WORKTREE_CREATE_RESULT_TTL_MS }, + ...(windowsProcessStartTimeAvailable ? { windowsProcessStartTimeAvailable } : {}), hostPlatform: process.platform, terminalWindowsShell: this.store?.getSettings?.().terminalWindowsShell ?? null, floatingWorkspaceEnabled: this.store?.getSettings?.().floatingTerminalEnabled !== false, diff --git a/src/main/runtime/orca-runtime-resolve-recovered-structured-tui-transcript.ts b/src/main/runtime/orca-runtime-resolve-recovered-structured-tui-transcript.ts index 37752d207e6..6448cc3911d 100644 --- a/src/main/runtime/orca-runtime-resolve-recovered-structured-tui-transcript.ts +++ b/src/main/runtime/orca-runtime-resolve-recovered-structured-tui-transcript.ts @@ -22,6 +22,8 @@ import { hasPersistedStructuredAgentSessionStore as hasPersistedStructuredAgentS import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' import { homedir } from 'node:os' import { join } from 'node:path' +import { parseWslUncPath } from '../../shared/wsl-paths' +import { parseWorkspaceKey } from '../../shared/workspace-scope' export class OrcaRuntimeWithResolveRecoveredStructuredTuiTranscript extends OrcaRuntimeWithStopStructuredSessionProcess { protected async resolveRecoveredStructuredTuiTranscript(input: { @@ -95,14 +97,23 @@ export class OrcaRuntimeWithResolveRecoveredStructuredTuiTranscript extends Orca protected async resolveStructuredAgentSessionLocation(worktreeSelector: string) { const target = await this.resolveRuntimeFileTarget(worktreeSelector) const repo = this.store?.getRepo(target.worktree.repoId) - // WSL routing describes *this* machine; no remote or runtime host may inherit it. - const wslDistro = - repo && target.executionHostId === LOCAL_EXECUTION_HOST_ID + const folderScope = parseWorkspaceKey(target.worktree.id) + const folderWorkspace = folderScope?.type === 'folder' + // WSL routing describes *this* machine; no remote or runtime host may inherit + // it. Both branches key on executionHostId: the target no longer carries a + // connectionId, which used to spell remote, unresolved and local alike. + const isLocalHost = target.executionHostId === LOCAL_EXECUTION_HOST_ID + const configuredWslDistro = + repo && isLocalHost ? (getLocalProjectWorktreeGitOptions(this.requireStore(), repo).wslDistro ?? null) : null - const folderWorkspace = this.store - ?.getFolderWorkspaces?.() - .some((workspace) => workspace.id === target.worktree.id) + // Folder workspaces have no repo Git options, so a WSL UNC path is the only + // durable signal that native Windows structured Codex cannot safely use it. + const wslDistro = + configuredWslDistro ?? + (folderWorkspace && isLocalHost + ? (parseWslUncPath(target.worktree.path)?.distro ?? null) + : null) return { executionHostId: target.executionHostId, wslDistro, diff --git a/src/main/runtime/rpc/methods/orchestration-worker-start-mode.test.ts b/src/main/runtime/rpc/methods/orchestration-worker-start-mode.test.ts index 7eafe9c86d4..23ed5b5a549 100644 --- a/src/main/runtime/rpc/methods/orchestration-worker-start-mode.test.ts +++ b/src/main/runtime/rpc/methods/orchestration-worker-start-mode.test.ts @@ -23,13 +23,11 @@ function decide( overrides: { params?: Parameters[0]['params'] settings?: Parameters[0]['settings'] - platform?: NodeJS.Platform } = {} ): WorkerStartModeReceipt { return decideWorkerStartMode({ params: { agent: 'claude', ...overrides.params }, - settings: overrides.settings === undefined ? STRUCTURED_DEFAULT : overrides.settings, - platform: overrides.platform ?? 'darwin' + settings: overrides.settings === undefined ? STRUCTURED_DEFAULT : overrides.settings }) } @@ -90,12 +88,10 @@ describe('a structured default this dispatch cannot honour', () => { ).toMatchObject({ mode: 'terminal', reason: 'tui_launch_customization' }) }) - it('keeps Codex terminal-backed on Windows and leaves Claude to the host', () => { - expect(decide({ params: { agent: 'codex' }, platform: 'win32' })).toMatchObject({ - mode: 'terminal', - reason: 'codex_on_windows' - }) - expect(decide({ params: { agent: 'claude' }, platform: 'win32' }).mode).toBe('structured') + // Neither provider is refused here on the client's platform: only the executing host knows + // whether it can read a provider child's start time, and it answers at create time. + it.each(['claude', 'codex'] as const)('leaves a Windows %s worker to the host', (agent) => { + expect(decide({ params: { agent } }).mode).toBe('structured') }) }) diff --git a/src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts b/src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts index 7c02c2a688f..c1f22a2c3f4 100644 --- a/src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts +++ b/src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts @@ -87,7 +87,6 @@ const BLOCKER_REASON: Record< 'floating-workspace': 'structured_unsupported_on_host', 'tui-launch-customization': 'tui_launch_customization', 'remote-execution-host': 'remote_execution_host', - 'codex-on-windows': 'codex_on_windows', 'project-runtime': 'wsl_execution_runtime', 'runtime-capability': 'structured_sessions_unavailable' } @@ -105,7 +104,6 @@ const HOST_SUPPORT_REASON: Record< export function decideWorkerStartMode(args: { params: WorkerStartModePlacement settings: WorkerStartModeSettings | null | undefined - platform: NodeJS.Platform }): WorkerStartModeReceipt { const { params, settings } = args if (!prefersStructuredNativeChatByDefault(settings)) { @@ -125,7 +123,6 @@ export function decideWorkerStartMode(args: { agent, // Set only by --on, which the placement check above already turned into a fallback. executionHostId: 'local', - platform: args.platform, hostCapabilities: RUNTIME_CAPABILITIES, // Orchestration resolves a managed worktree or folder workspace; a floating terminal is never // a worker placement. WSL is left to the executing host's own create-support probe, which diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts index 6ccac1dea9e..8b14ec044cf 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts @@ -51,8 +51,7 @@ export const ORCHESTRATION_WORKER_START_METHODS: RpcMethod[] = [ await assertWorkerStartTaskSpecWithinPromptBudget(params.spec ?? existingTask!.spec) const mode = decideWorkerStartMode({ params, - settings: readWorkerStartModeSettings(runtime), - platform: process.platform + settings: readWorkerStartModeSettings(runtime) }) if (params.on) { // A remote worker is always a terminal agent; the mode receipt rides along so the diff --git a/src/main/runtime/rpc/methods/structured-agent-session-gate.ts b/src/main/runtime/rpc/methods/structured-agent-session-gate.ts index de83820e9c3..60b28425057 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-gate.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-gate.ts @@ -80,7 +80,10 @@ export function requireStructuredCleanupHost(ctx: RpcContext): StructuredAgentSe export async function ensureStructuredHostInstalled(ctx: RpcContext): Promise { // Gated first: a client that cannot read structured sessions must not be able // to make the host exist, which is an observable side effect of the surface. - if (!supportsStructuredSessions(ctx) || getStructuredAgentSessionHost()) { + if (!supportsStructuredSessions(ctx)) { + return + } + if (getStructuredAgentSessionHost()) { return } await ctx.runtime.ensureStructuredAgentSessionHost() diff --git a/src/main/runtime/structured-agent-session-runtime.test.ts b/src/main/runtime/structured-agent-session-runtime.test.ts index 3b69a0a4be3..2ce51b1c29b 100644 --- a/src/main/runtime/structured-agent-session-runtime.test.ts +++ b/src/main/runtime/structured-agent-session-runtime.test.ts @@ -8,9 +8,11 @@ import { createTrackedJournalOpener } from '../native-chat/agent-session-journal import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' import type { AgentSessionClaimStatus, + AgentSessionExecutionLocation, AgentSessionProcessIdentity, AgentSessionRecord } from '../../shared/agent-session-record' +import { __setWindowsProcessTreeLoaderForTests } from '../windows/windows-process-table' import { createStructuredAgentSessionOwnerProbe, createStructuredAgentSessionOwnerProbes @@ -270,6 +272,35 @@ describe('structured agent-session runtime install', () => { ) ) }) + + it('does not infer Windows process identity support from an injected reader', async () => { + stateDirectory = await mkdtemp(join(tmpdir(), 'orca-structured-runtime-')) + const originalPlatform = process.platform + const location: AgentSessionExecutionLocation = { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'folder' + } + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + __setWindowsProcessTreeLoaderForTests(() => null) + try { + const host = await ensureStructuredAgentSessionHost({ + stateDirectory, + hostId: HOST_ID, + claimKeyId: 'key-1', + resolveWorkspacePath: async () => stateDirectory!, + resolveEnvironment: async () => ({}), + resolveClaudeAuthPolicy: () => ({ stripAuthEnv: true }), + readProcessStartTime: async () => 1_700_000_000_000 + }) + + expect(host.supportsCreate(location, 'codex')).toBe(false) + } finally { + __setWindowsProcessTreeLoaderForTests() + Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) + } + }) }) // A stop whose teardown fails must not forget the runtime it was tearing down. diff --git a/src/main/runtime/structured-agent-session-support-probe.test.ts b/src/main/runtime/structured-agent-session-support-probe.test.ts index e393e41f3a4..f55a802e979 100644 --- a/src/main/runtime/structured-agent-session-support-probe.test.ts +++ b/src/main/runtime/structured-agent-session-support-probe.test.ts @@ -6,6 +6,21 @@ import { } from '../native-chat/agent-session-wire/structured-agent-session-registry' import { agentSessionPtyWriteGate } from './agent-session-pty-write-gate' +const { isWindowsProcessStartTimeAvailable } = vi.hoisted(() => ({ + isWindowsProcessStartTimeAvailable: vi.fn(() => true) +})) + +vi.mock('../windows/windows-process-table', async (importOriginal) => ({ + ...(await importOriginal()), + isWindowsProcessStartTimeAvailable +})) + +const originalPlatform = process.platform + +function setPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) +} + type InstallEffects = { storeOpened: boolean writeGateAttached: boolean @@ -94,6 +109,9 @@ async function expectSupportWithoutInstall(input: { describe('structured agent-session create-support probe', () => { afterEach(() => { + setPlatform(originalPlatform) + isWindowsProcessStartTimeAvailable.mockReset() + isWindowsProcessStartTimeAvailable.mockReturnValue(true) setStructuredAgentSessionHost(null) agentSessionPtyWriteGate.detachRecordLookup() vi.restoreAllMocks() @@ -111,6 +129,27 @@ describe('structured agent-session create-support probe', () => { } ) + it.each([ + ['codex', true, { supported: true }], + ['codex', false, { supported: false, reason: 'agent' }], + ['claude', true, { supported: true }], + ['claude', false, { supported: false, reason: 'agent' }] + ] as const)( + 'requires native Windows process identity proof before answering %s support (%s)', + async (agent, proofAvailable, expected) => { + setPlatform('win32') + isWindowsProcessStartTimeAvailable.mockReturnValue(proofAvailable) + + await expectSupportWithoutInstall({ + agent, + location: { executionHostId: 'local', wslDistro: null }, + expected + }) + + expect(isWindowsProcessStartTimeAvailable).toHaveBeenCalled() + } + ) + it.each(['codex', 'claude'] as const)( 'still reports an unsupported remote %s location without installing the host', async (agent) => { diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-workspace.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-workspace.ts index adedc94b22a..a1f2a296748 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-workspace.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-workspace.ts @@ -3,7 +3,6 @@ import { type AgentLaunchRoutingInput } from '@/lib/agent-launch-routing' import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' import { getExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner' import { readLocalRuntimeCapabilities } from '@/runtime/local-runtime-capabilities' import { useAppStore } from '@/store' @@ -47,7 +46,6 @@ export function resolveAiVaultSessionResumeInChatForWorkspace(args: { useAppStore.getState(), targetWorkspaceId as string ), - platform: CLIENT_PLATFORM, hostCapabilities: readLocalRuntimeCapabilities(), workspaceKind: (targetWorkspaceId as string).startsWith('folder:') ? 'folder' diff --git a/src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts b/src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts index ca685dded64..c016538cac9 100644 --- a/src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts +++ b/src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts @@ -1,8 +1,4 @@ -import { - CLIENT_PLATFORM, - ensureAgentStartupInTerminal, - type LinkedWorkItemSummary -} from '@/lib/new-workspace' +import { ensureAgentStartupInTerminal, type LinkedWorkItemSummary } from '@/lib/new-workspace' import { seedNativeChatLaunchDraftForAgentTab } from '@/lib/agent-launch-prompt-delivery' import { createBrowserUuid } from '@/lib/browser-uuid' import { buildAgentStartupPlan } from '@/lib/tui-agent-startup' @@ -151,7 +147,6 @@ export async function submitFolderWorkspaceCreate({ executionHostId: runtimeEnvironmentId ? `runtime:${encodeURIComponent(runtimeEnvironmentId)}` : (projectGroup.connectionId ?? 'local'), - platform: CLIENT_PLATFORM, hostCapabilities: readLocalRuntimeCapabilities(), workspaceKind: 'folder', promptDelivery: launchDraftPrompt ? 'draft' : 'auto-submit', diff --git a/src/renderer/src/hooks/composer-state/full-creation-execution.ts b/src/renderer/src/hooks/composer-state/full-creation-execution.ts index f199ca66f0c..0118f6c2236 100644 --- a/src/renderer/src/hooks/composer-state/full-creation-execution.ts +++ b/src/renderer/src/hooks/composer-state/full-creation-execution.ts @@ -33,7 +33,7 @@ import type { PendingSmartGitHubSubmitResolution } from './source-selection-deci import { translate } from '@/i18n/i18n' import { settleComposerSubmit } from '@/lib/composer-submit-cancellation' import { toFolderWorkspaceLinkedTask } from '@/components/sidebar/folder-workspace-composer-helpers' -import { CLIENT_PLATFORM, ensureAgentStartupInTerminal } from '@/lib/new-workspace' +import { ensureAgentStartupInTerminal } from '@/lib/new-workspace' import { createBrowserUuid } from '@/lib/browser-uuid' import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { seedNativeChatAppliedSessionOptions } from '@/components/native-chat/native-chat-session-option-cache' @@ -140,7 +140,6 @@ export function useFullCreationExecution(input: FullCreationExecutionInput) { agent: tuiAgent, settings, executionHostId: selectedRepoExecutionHostId ?? 'local', - platform: CLIENT_PLATFORM, hostCapabilities: readLocalRuntimeCapabilities(), workspaceKind: selectedRepoIsGit ? 'git-worktree' : 'folder', promptDelivery: startupPlan?.draftPrompt ? 'draft' : 'auto-submit', diff --git a/src/renderer/src/hooks/composer-state/quick-creation-execution.ts b/src/renderer/src/hooks/composer-state/quick-creation-execution.ts index 7160cb48b4c..a25afd9106c 100644 --- a/src/renderer/src/hooks/composer-state/quick-creation-execution.ts +++ b/src/renderer/src/hooks/composer-state/quick-creation-execution.ts @@ -51,7 +51,6 @@ import { resolveAgentLaunchRoute } from '@/lib/agent-launch-routing' import { readLocalRuntimeCapabilities } from '@/runtime/local-runtime-capabilities' -import { CLIENT_PLATFORM } from '@/lib/new-workspace' export function useQuickCreationExecution(input: QuickCreationExecutionInput) { const { @@ -206,7 +205,6 @@ export function useQuickCreationExecution(input: QuickCreationExecutionInput) { executionHostId: ephemeralVmRecipe ? 'runtime:pending-ephemeral-vm' : (workspaceRunContext?.hostId ?? selectedRepoExecutionHostId ?? 'local'), - platform: CLIENT_PLATFORM, hostCapabilities: readLocalRuntimeCapabilities(), workspaceKind: selectedRepoIsGit ? 'git-worktree' : 'folder', promptDelivery: quickDraftPrompt ? 'draft' : 'auto-submit', diff --git a/src/renderer/src/lib/agent-launch-routing.test.ts b/src/renderer/src/lib/agent-launch-routing.test.ts index af219bab633..cb3a2b70b00 100644 --- a/src/renderer/src/lib/agent-launch-routing.test.ts +++ b/src/renderer/src/lib/agent-launch-routing.test.ts @@ -19,7 +19,6 @@ function route(overrides: Partial[0]> agent: 'codex', settings, executionHostId: 'local', - platform: 'darwin', hostCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], workspaceKind: 'git-worktree', nativeChatTranscriptIsLocalReadable: true, @@ -41,57 +40,16 @@ describe('resolveAgentLaunchRoute', () => { } ) - /** Boundary guard between this lane and the one that owns Windows Codex. Codex's win32 refusal is - * deliberate, so it is asserted against whatever currently lets Claude through rather than - * against one host answer — a future gate swap must not be able to flip Codex on quietly. */ - describe("Codex's Windows refusal", () => { - it('holds in the exact situation that routes Claude to structured', () => { - const onWindows = { platform: 'win32' } as const - expect(route({ ...onWindows, agent: 'claude' })).toBe('structured-native-chat') - expect(route({ ...onWindows, agent: 'codex' })).toBe('legacy-native-chat') - }) - - it('holds for every host capability set, including ones that carry extra gates', () => { - for (const hostCapabilities of [ - [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], - [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, 'agent-session.structured.claude.v1'], - [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, 'agent-session.structured.hold.v1'] - ]) { - expect(route({ agent: 'codex', platform: 'win32', hostCapabilities })).toBe( - 'legacy-native-chat' - ) - } - }) - - it('holds for prompted and folder-workspace launches too', () => { - expect( - route({ - agent: 'codex', - platform: 'win32', - launchText: 'go', - promptDelivery: 'auto-submit' - }) - ).toBe('legacy-native-chat') - expect(route({ agent: 'codex', platform: 'win32', workspaceKind: 'folder' })).toBe( - 'legacy-native-chat' - ) - }) - }) - - /** Pins Codex's whole platform answer, not just win32, so no platform silently changes here. */ - it.each([ - ['darwin', 'structured-native-chat'], - ['linux', 'structured-native-chat'], - ['win32', 'legacy-native-chat'] - ] as const)('leaves Codex routing on %s unchanged', (platform, expected) => { - expect(route({ agent: 'codex', platform })).toBe(expected) - }) - - /** Claude's Windows answer is not a client-side platform guess: the route lets it through and the - * executing host settles it with agentSession.createSupport at create time. */ - it('lets a Windows Claude launch reach the host-measured create support check', () => { - expect(route({ agent: 'claude', platform: 'win32' })).toBe('structured-native-chat') - }) + /** Windows eligibility is no client-side platform guess for either provider: the route lets the + * launch through and the executing host settles it with agentSession.createSupport at create + * time. A stale caller still passing the removed `platform` input must not flip Codex off the + * structured route — the field is gone, not reinterpreted. */ + it.each(['claude', 'codex'] as const)( + 'routes %s to structured even when the caller claims a win32 client platform', + (agent) => { + expect(route({ agent, ...({ platform: 'win32' } as object) })).toBe('structured-native-chat') + } + ) it('routes a supported local Codex launch to structured native chat', () => { expect(route()).toBe('structured-native-chat') @@ -134,15 +92,13 @@ describe('resolveAgentLaunchRoute', () => { it.each(['git-worktree', 'folder'] as const)( 'supports a local %s without widening floating-terminal scope', (workspaceKind) => { - expect(route({ workspaceKind, platform: 'linux' })).toBe('structured-native-chat') + expect(route({ workspaceKind })).toBe('structured-native-chat') } ) it('keeps floating, WSL, and repair-required launches terminal-backed', () => { expect(route({ workspaceKind: 'floating' })).toBe('legacy-native-chat') - expect(route({ agent: 'claude', workspaceKind: 'floating', platform: 'win32' })).toBe( - 'legacy-native-chat' - ) + expect(route({ agent: 'claude', workspaceKind: 'floating' })).toBe('legacy-native-chat') expect( route({ projectRuntime: { diff --git a/src/renderer/src/lib/agent-launch-routing.ts b/src/renderer/src/lib/agent-launch-routing.ts index 2bca72ba3ae..090ef3c9108 100644 --- a/src/renderer/src/lib/agent-launch-routing.ts +++ b/src/renderer/src/lib/agent-launch-routing.ts @@ -30,7 +30,6 @@ export type AgentLaunchRoutingInput = { | null | undefined executionHostId: string - platform: NodeJS.Platform hostCapabilities: readonly string[] workspaceKind?: 'git-worktree' | 'folder' | 'floating' projectRuntime?: ProjectExecutionRuntimeResolution | null @@ -68,7 +67,6 @@ export function structuredAgentLaunchSupported( resolveStructuredNativeChatSupport({ agent: input.agent, executionHostId: input.executionHostId, - platform: input.platform, hostCapabilities: input.hostCapabilities, workspaceKind: input.workspaceKind, projectRuntime: input.projectRuntime, diff --git a/src/renderer/src/lib/launch-agent-in-new-tab.ts b/src/renderer/src/lib/launch-agent-in-new-tab.ts index 118fcdbeda8..cb3187878ef 100644 --- a/src/renderer/src/lib/launch-agent-in-new-tab.ts +++ b/src/renderer/src/lib/launch-agent-in-new-tab.ts @@ -213,7 +213,6 @@ function launchAgentInNewTabInternal( agent, settings: store.settings, executionHostId: getExecutionHostIdForWorktree(store, worktreeId), - platform: CLIENT_PLATFORM, hostCapabilities: readLocalRuntimeCapabilities(), workspaceKind, projectRuntime: getLocalProjectExecutionRuntimeContext(store, worktreeId), diff --git a/src/renderer/src/lib/launch-structured-agent-session.test.ts b/src/renderer/src/lib/launch-structured-agent-session.test.ts index d9a75ee2827..1d7dec2cdf3 100644 --- a/src/renderer/src/lib/launch-structured-agent-session.test.ts +++ b/src/renderer/src/lib/launch-structured-agent-session.test.ts @@ -19,37 +19,43 @@ describe('structured agent session launch', () => { }) it('creates a native session with a host-verifiable launch intent', async () => { - vi.mocked(callStructuredAgentSession).mockImplementation(async (_target, _method, params) => ({ - ok: true, - replayed: false, - fence: 1, - cursor: { epoch: 'epoch-1', sequence: 0 }, - value: { - sessionId: (params as { envelope: { sessionId: string } }).envelope.sessionId, - fence: 1, - page: { - sessionId: 'session-1', - epoch: 'epoch-1', - direction: 'tail', - items: [], - removedItemIds: [], - submissions: [], - window: { - oldest: null, - newest: null, - nextCursor: { epoch: 'epoch-1', sequence: 0 } - }, - liveCursor: { epoch: 'epoch-1', sequence: 0 }, - hasOlder: false, - hasNewer: false - }, - unconfirmedClientMessageIds: [] - } - })) + vi.mocked(callStructuredAgentSession).mockImplementation(async (_target, method, params) => + method === 'agentSession.createSupport' + ? { supported: true } + : { + ok: true, + replayed: false, + fence: 1, + cursor: { epoch: 'epoch-1', sequence: 0 }, + value: { + sessionId: (params as { envelope: { sessionId: string } }).envelope.sessionId, + fence: 1, + page: { + sessionId: 'session-1', + epoch: 'epoch-1', + direction: 'tail', + items: [], + removedItemIds: [], + submissions: [], + window: { + oldest: null, + newest: null, + nextCursor: { epoch: 'epoch-1', sequence: 0 } + }, + liveCursor: { epoch: 'epoch-1', sequence: 0 }, + hasOlder: false, + hasNewer: false + }, + unconfirmedClientMessageIds: [] + } + } + ) const intent = createStructuredAgentSessionLaunchIntent('workspace-1', 'codex') const receipt = await launchStructuredAgentSession(intent) - const params = vi.mocked(callStructuredAgentSession).mock.calls[0]?.[2] as { + const params = vi + .mocked(callStructuredAgentSession) + .mock.calls.find(([, method]) => method === 'agentSession.create')?.[2] as { envelope: { sessionId: string; payloadFingerprint: string } worktree: string agent: 'codex' @@ -87,40 +93,46 @@ describe('structured agent session launch', () => { ) }) - it('asks the executing host for create support before creating a Claude session', async () => { - vi.mocked(callStructuredAgentSession).mockImplementation(async (_target, method) => - method === 'agentSession.createSupport' - ? { supported: true } - : { ok: true, replayed: false, value: { sessionId: 'claude_1', fence: 1 } } - ) + it.each(['claude', 'codex'] as const)( + 'asks the executing host for create support before creating a %s session', + async (agent) => { + vi.mocked(callStructuredAgentSession).mockImplementation(async (_target, method) => + method === 'agentSession.createSupport' + ? { supported: true } + : { ok: true, replayed: false, value: { sessionId: `${agent}_1`, fence: 1 } } + ) - const intent = createStructuredAgentSessionLaunchIntent('workspace-1', 'claude') - await launchStructuredAgentSession(intent) + const intent = createStructuredAgentSessionLaunchIntent('workspace-1', agent) + await launchStructuredAgentSession(intent) - expect(vi.mocked(callStructuredAgentSession).mock.calls.map(([, method]) => method)).toEqual([ - 'agentSession.createSupport', - 'agentSession.create' - ]) - expect(callStructuredAgentSession).toHaveBeenNthCalledWith( - 1, - { kind: 'local' }, - 'agentSession.createSupport', - { worktree: 'id:workspace-1', agent: 'claude' } - ) - }) + expect(vi.mocked(callStructuredAgentSession).mock.calls.map(([, method]) => method)).toEqual([ + 'agentSession.createSupport', + 'agentSession.create' + ]) + expect(callStructuredAgentSession).toHaveBeenNthCalledWith( + 1, + { kind: 'local' }, + 'agentSession.createSupport', + { worktree: 'id:workspace-1', agent } + ) + } + ) - it('refuses a Claude launch the host says it cannot support, without creating', async () => { - vi.mocked(callStructuredAgentSession).mockResolvedValue({ supported: false, reason: 'agent' }) + it.each(['claude', 'codex'] as const)( + 'refuses a %s launch the host says it cannot support, without creating', + async (agent) => { + vi.mocked(callStructuredAgentSession).mockResolvedValue({ supported: false, reason: 'agent' }) - const intent = createStructuredAgentSessionLaunchIntent('workspace-1', 'claude') + const intent = createStructuredAgentSessionLaunchIntent('workspace-1', agent) - await expect(launchStructuredAgentSession(intent)).rejects.toBeInstanceOf( - StructuredAgentSessionCreateRefusalError - ) - expect(vi.mocked(callStructuredAgentSession).mock.calls.map(([, method]) => method)).toEqual([ - 'agentSession.createSupport' - ]) - }) + await expect(launchStructuredAgentSession(intent)).rejects.toBeInstanceOf( + StructuredAgentSessionCreateRefusalError + ) + expect(vi.mocked(callStructuredAgentSession).mock.calls.map(([, method]) => method)).toEqual([ + 'agentSession.createSupport' + ]) + } + ) it('fails closed when the create support probe cannot be answered', async () => { vi.mocked(callStructuredAgentSession).mockRejectedValue(new Error('runtime unreachable')) @@ -212,46 +224,40 @@ describe('structured agent session launch', () => { expect(callStructuredAgentSession).toHaveBeenCalledOnce() }) - /** Codex's support answer is settled by the launch route and owned elsewhere; this pins that the - * Claude probe did not change Codex's wire traffic. */ - it('does not probe create support for Codex', async () => { - vi.mocked(callStructuredAgentSession).mockResolvedValue({ - ok: true, - replayed: false, - value: { sessionId: 'codex_1', fence: 1 } - }) - - await launchStructuredAgentSession( - createStructuredAgentSessionLaunchIntent('workspace-1', 'codex') + /** The probe now runs for Codex too, so create-outcome tests script it to say yes. */ + function mockSupportedCreate(create: () => unknown): void { + vi.mocked(callStructuredAgentSession).mockImplementation(async (_target, method) => + method === 'agentSession.createSupport' ? { supported: true } : create() ) - - expect(vi.mocked(callStructuredAgentSession).mock.calls.map(([, method]) => method)).toEqual([ - 'agentSession.create' - ]) - }) + } it('replays the exact create envelope when an unknown outcome is retried', async () => { const intent = createStructuredAgentSessionLaunchIntent('workspace-retry', 'codex') - vi.mocked(callStructuredAgentSession).mockRejectedValue(new Error('response lost')) + mockSupportedCreate(() => { + throw new Error('response lost') + }) await expect(launchStructuredAgentSession(intent)).rejects.toThrow('response lost') await expect(launchStructuredAgentSession(intent)).rejects.toThrow('response lost') - const first = vi.mocked(callStructuredAgentSession).mock.calls[0]?.[2] - const second = vi.mocked(callStructuredAgentSession).mock.calls[1]?.[2] + const createCalls = vi + .mocked(callStructuredAgentSession) + .mock.calls.filter(([, method]) => method === 'agentSession.create') + const first = createCalls[0]?.[2] + const second = createCalls[1]?.[2] expect(first).toBe(intent.params) expect(second).toBe(first) expect(intent.params.envelope.clientOperationId).toMatch(/^\d{13}-[0-9a-f]{32}$/) }) it('preserves an unknown refusal code without classifying it as fallback-safe', async () => { - vi.mocked(callStructuredAgentSession).mockResolvedValue({ + mockSupportedCreate(() => ({ ok: false, refusal: { code: 'agent_session_operation_unknown', message: 'The chat may already exist.' } - }) + })) const error = await launchStructuredAgentSession( createStructuredAgentSessionLaunchIntent('workspace-unknown', 'codex') @@ -266,13 +272,13 @@ describe('structured agent session launch', () => { /** The class is the verdict, so a refusal message that happens to end in a definitive token * must not be re-read into one by the transport-error matcher. */ it('keeps an unknown outcome unknown even when its message ends in a definitive token', async () => { - vi.mocked(callStructuredAgentSession).mockResolvedValue({ + mockSupportedCreate(() => ({ ok: false, refusal: { code: 'agent_session_ownership_unknown', message: 'Owner check failed: method_not_found' } - }) + })) const error = await launchStructuredAgentSession( createStructuredAgentSessionLaunchIntent('workspace-unknown-token', 'codex') @@ -283,13 +289,13 @@ describe('structured agent session launch', () => { }) it('preserves a definitive refusal code for the fallback path', async () => { - vi.mocked(callStructuredAgentSession).mockResolvedValue({ + mockSupportedCreate(() => ({ ok: false, refusal: { code: 'structured_agent_session_unsupported', message: 'Structured chat is unavailable.' } - }) + })) const error = await launchStructuredAgentSession( createStructuredAgentSessionLaunchIntent('workspace-unsupported', 'codex') @@ -303,9 +309,9 @@ describe('structured agent session launch', () => { it.each(['method_not_found', 'structured_agent_session_unsupported'])( 'turns an old-host %s error into a definitive transport refusal', async (code) => { - vi.mocked(callStructuredAgentSession).mockRejectedValueOnce( - Object.assign(new Error(code), { code }) - ) + mockSupportedCreate(() => { + throw Object.assign(new Error(code), { code }) + }) const oldHostError = await launchStructuredAgentSession( createStructuredAgentSessionLaunchIntent(`workspace-old-host-${code}`, 'codex') ).catch((caught: unknown) => caught) @@ -316,9 +322,9 @@ describe('structured agent session launch', () => { ) it('keeps an unclassified transport failure outcome unknown', async () => { - vi.mocked(callStructuredAgentSession).mockRejectedValueOnce( - Object.assign(new Error('Connection lost'), { code: 'runtime_error' }) - ) + mockSupportedCreate(() => { + throw Object.assign(new Error('Connection lost'), { code: 'runtime_error' }) + }) const transportError = await launchStructuredAgentSession( createStructuredAgentSessionLaunchIntent('workspace-offline', 'codex') ).catch((caught: unknown) => caught) diff --git a/src/renderer/src/lib/launch-structured-agent-session.ts b/src/renderer/src/lib/launch-structured-agent-session.ts index 503ae771419..0694090fc5c 100644 --- a/src/renderer/src/lib/launch-structured-agent-session.ts +++ b/src/renderer/src/lib/launch-structured-agent-session.ts @@ -174,17 +174,10 @@ async function hostSupportsCreate(intent: StructuredAgentSessionLaunchIntent): P /** * Only the host that will execute the session can answer whether it supports creating one there — * on Windows that means reading the provider child's process start time, which a client cannot - * observe. - * - * Codex is absent on purpose: its answer is settled by the launch route and owned elsewhere, so - * probing here would change Codex's wire traffic. Note that this early return is also why the - * unresolvable-selector race above has never been able to refuse a Codex launch — the race is - * identical for Codex, nothing asks. Whoever gives Codex a probe inherits it. + * observe. Both providers ask: the host classifies per agent, and Codex inherits the + * unresolvable-selector retry above along with the probe. */ async function requireHostCreateSupport(intent: StructuredAgentSessionLaunchIntent): Promise { - if (intent.agent !== 'claude') { - return - } if (!(await hostSupportsCreate(intent))) { abandonStructuredAgentSessionLaunchIntent(intent) throw new StructuredAgentSessionCreateRefusalError( diff --git a/src/renderer/src/lib/launch-work-item-direct-route-preparation.ts b/src/renderer/src/lib/launch-work-item-direct-route-preparation.ts index 55aa77bddbe..1fdc3b6fa69 100644 --- a/src/renderer/src/lib/launch-work-item-direct-route-preparation.ts +++ b/src/renderer/src/lib/launch-work-item-direct-route-preparation.ts @@ -97,7 +97,6 @@ export async function prepareDirectWorkItemAgentLaunch(args: { agent: effectiveAgent, settings: args.settings, executionHostId: getExecutionHostIdForWorktree(args.latestStore, args.worktreeId), - platform: CLIENT_PLATFORM, hostCapabilities: readLocalRuntimeCapabilities(), workspaceKind: 'git-worktree', projectRuntime: getLocalProjectExecutionRuntimeContext( diff --git a/src/renderer/src/lib/onboarding-folder-agent-startup.ts b/src/renderer/src/lib/onboarding-folder-agent-startup.ts index 958f43eda28..a4341a4dc87 100644 --- a/src/renderer/src/lib/onboarding-folder-agent-startup.ts +++ b/src/renderer/src/lib/onboarding-folder-agent-startup.ts @@ -135,7 +135,6 @@ export function resolveDismissedOnboardingFolderAgentLaunch(args: { agent, settings: args.settings, executionHostId: args.executionHostId, - platform: getClientPlatform(), hostCapabilities: readLocalRuntimeCapabilities(), workspaceKind: 'folder', nativeChatTranscriptIsLocalReadable: args.nativeChatTranscriptIsLocalReadable, diff --git a/src/renderer/src/lib/structured-agent-session-launch-refusal-fallback.test.ts b/src/renderer/src/lib/structured-agent-session-launch-refusal-fallback.test.ts index 45c41bd111e..9139b1c122a 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-refusal-fallback.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-refusal-fallback.test.ts @@ -58,6 +58,9 @@ type CreateReply = { ok: boolean; refusal?: { code: string; message: string } } function replyToCreates(...replies: CreateReply[]): void { let index = 0 mocks.call.mockImplementation(async (_target: unknown, method: string, params: unknown) => { + if (method === 'agentSession.createSupport') { + return { supported: true } + } if (method !== 'agentSession.create') { return { ok: true, page: { fence: 1 } } } diff --git a/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts b/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts index 7e99ff73fe6..f93437bc088 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts @@ -63,11 +63,16 @@ describe('a launch that adopts a conversation is its own identity', () => { vi.clearAllMocks() localStorage.clear() mocks.refresh.mockResolvedValue([]) - mocks.call.mockImplementation(async (_target: unknown, method: string) => - method === 'agentSession.create' - ? new Promise(() => {}) - : { ok: true, value: { submission: { dispatchState: 'accepted' } } } - ) + mocks.call.mockImplementation(async (_target: unknown, method: string) => { + if (method === 'agentSession.create') { + return new Promise(() => {}) + } + // Both providers now ask the executing host before creating. + if (method === 'agentSession.createSupport') { + return { supported: true } + } + return { ok: true, value: { submission: { dispatchState: 'accepted' } } } + }) }) it('does not hand a resume the blank launch already pending for the same worktree', async () => { diff --git a/src/renderer/src/lib/web-client-location.test.ts b/src/renderer/src/lib/web-client-location.test.ts new file mode 100644 index 00000000000..9ea2886e533 --- /dev/null +++ b/src/renderer/src/lib/web-client-location.test.ts @@ -0,0 +1,43 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { isWebClientLocation } from './web-client-location' + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('isWebClientLocation', () => { + it('reports false when there is no window at all', () => { + vi.stubGlobal('window', undefined) + expect(isWebClientLocation()).toBe(false) + }) + + // Why: this runs on the launch-routing path, where a throw is swallowed and + // silently becomes a failed launch. A window without a usable `location` + // must answer the question, not throw. + it('does not throw when window exists without a location', () => { + vi.stubGlobal('window', { api: {} }) + expect(() => isWebClientLocation()).not.toThrow() + expect(isWebClientLocation()).toBe(false) + }) + + it('does not throw when location exists without a pathname', () => { + vi.stubGlobal('window', { location: {} }) + expect(() => isWebClientLocation()).not.toThrow() + expect(isWebClientLocation()).toBe(false) + }) + + it('detects the web client by its entry path', () => { + vi.stubGlobal('window', { location: { pathname: '/web-index.html' } }) + expect(isWebClientLocation()).toBe(true) + }) + + it('detects the web client by its global marker', () => { + vi.stubGlobal('window', { __ORCA_WEB_CLIENT__: true, location: { pathname: '/' } }) + expect(isWebClientLocation()).toBe(true) + }) + + it('reports false for a normal desktop renderer path', () => { + vi.stubGlobal('window', { location: { pathname: '/index.html' } }) + expect(isWebClientLocation()).toBe(false) + }) +}) diff --git a/src/renderer/src/lib/web-client-location.ts b/src/renderer/src/lib/web-client-location.ts index 26c7e70bb21..94d751b8ab1 100644 --- a/src/renderer/src/lib/web-client-location.ts +++ b/src/renderer/src/lib/web-client-location.ts @@ -2,8 +2,13 @@ export function isWebClientLocation(): boolean { if (typeof window === 'undefined') { return false } + // Why the pathname guard: `window` can exist without a usable `location` + // (partial test doubles, and any embedder that stubs the global), and this + // runs on the launch-routing path where a throw is swallowed and silently + // turns into a failed launch rather than a visible error. + const pathname = (window as { location?: { pathname?: unknown } }).location?.pathname return ( Boolean((window as unknown as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__) || - window.location.pathname.endsWith('/web-index.html') + (typeof pathname === 'string' && pathname.endsWith('/web-index.html')) ) } diff --git a/src/renderer/src/lib/windows-terminal-capabilities-race.test.ts b/src/renderer/src/lib/windows-terminal-capabilities-race.test.ts new file mode 100644 index 00000000000..0439e5c76bf --- /dev/null +++ b/src/renderer/src/lib/windows-terminal-capabilities-race.test.ts @@ -0,0 +1,80 @@ +// @vitest-environment happy-dom + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + getCachedWindowsTerminalCapabilities, + loadWindowsTerminalCapabilities, + resetWindowsTerminalCapabilitiesForTests +} from './windows-terminal-capabilities' +import { resetWindowsTerminalCapabilityReprobeForTests } from './windows-terminal-capability-reprobe' + +describe('Windows terminal capability probe ordering', () => { + afterEach(() => { + resetWindowsTerminalCapabilitiesForTests() + resetWindowsTerminalCapabilityReprobeForTests() + vi.unstubAllGlobals() + }) + + it('does not let an older forced probe overwrite a newer identity proof', async () => { + let resolveOlderStatus!: (status: { hostPlatform: NodeJS.Platform }) => void + let resolveNewerStatus!: (status: { + hostPlatform: NodeJS.Platform + windowsProcessStartTimeAvailable: boolean + }) => void + const olderStatus = new Promise<{ hostPlatform: NodeJS.Platform }>((resolve) => { + resolveOlderStatus = resolve + }) + const newerStatus = new Promise<{ + hostPlatform: NodeJS.Platform + windowsProcessStartTimeAvailable: boolean + }>((resolve) => { + resolveNewerStatus = resolve + }) + const runtimeGetStatus = vi + .fn<() => Promise>() + .mockReturnValueOnce(olderStatus) + .mockReturnValueOnce(newerStatus) + vi.stubGlobal('window', { + api: { + wsl: { + isAvailable: vi.fn().mockResolvedValue(false), + listDistros: vi.fn().mockResolvedValue([]) + }, + pwsh: { isAvailable: vi.fn().mockResolvedValue(false) }, + gitBash: { isAvailable: vi.fn().mockResolvedValue(false) }, + runtime: { getStatus: runtimeGetStatus } + } + }) + + const olderProbe = loadWindowsTerminalCapabilities({ + ownerKey: 'local', + force: true, + now: 1_000 + }) + const newerProbe = loadWindowsTerminalCapabilities({ + ownerKey: 'local', + force: true, + now: 2_000 + }) + + resolveNewerStatus({ hostPlatform: 'win32', windowsProcessStartTimeAvailable: true }) + await expect(newerProbe).resolves.toMatchObject({ + hostPlatform: 'win32', + windowsProcessStartTimeAvailable: true + }) + expect(getCachedWindowsTerminalCapabilities('local')).toMatchObject({ + hostPlatform: 'win32', + windowsProcessStartTimeAvailable: true + }) + + resolveOlderStatus({ hostPlatform: 'win32' }) + await expect(olderProbe).resolves.toMatchObject({ + hostPlatform: 'win32', + windowsProcessStartTimeAvailable: true + }) + expect(getCachedWindowsTerminalCapabilities('local')).toMatchObject({ + hostPlatform: 'win32', + windowsProcessStartTimeAvailable: true + }) + }) +}) diff --git a/src/renderer/src/lib/windows-terminal-capabilities.test.ts b/src/renderer/src/lib/windows-terminal-capabilities.test.ts index 1f1a83dec9e..d1ad22b463d 100644 --- a/src/renderer/src/lib/windows-terminal-capabilities.test.ts +++ b/src/renderer/src/lib/windows-terminal-capabilities.test.ts @@ -70,6 +70,7 @@ function stubTerminalCapabilityApi(args: { wslDistros?: string[] gitBashAvailable?: boolean hostPlatform?: NodeJS.Platform | null + windowsProcessStartTimeAvailable?: boolean }): { wslIsAvailable: ReturnType wslListDistros: ReturnType @@ -81,9 +82,12 @@ function stubTerminalCapabilityApi(args: { const wslListDistros = vi.fn().mockResolvedValue(args.wslDistros ?? []) const pwshIsAvailable = vi.fn().mockResolvedValue(args.pwshAvailable) const isGitBashAvailable = vi.fn().mockResolvedValue(args.gitBashAvailable ?? false) - const runtimeGetStatus = vi - .fn() - .mockResolvedValue({ hostPlatform: 'hostPlatform' in args ? args.hostPlatform : 'win32' }) + const runtimeGetStatus = vi.fn().mockResolvedValue({ + hostPlatform: 'hostPlatform' in args ? args.hostPlatform : 'win32', + ...(args.windowsProcessStartTimeAvailable !== undefined + ? { windowsProcessStartTimeAvailable: args.windowsProcessStartTimeAvailable } + : {}) + }) vi.stubGlobal('window', { api: { @@ -583,7 +587,8 @@ describe('windows terminal capabilities', () => { const { wslIsAvailable, wslListDistros } = stubTerminalCapabilityApi({ wslAvailable: false, pwshAvailable: true, - wslDistros: [] + wslDistros: [], + windowsProcessStartTimeAvailable: true }) wslIsAvailable.mockResolvedValueOnce(false).mockResolvedValue(true) wslListDistros.mockResolvedValueOnce([]).mockResolvedValue(['Ubuntu']) diff --git a/src/renderer/src/lib/windows-terminal-capabilities.ts b/src/renderer/src/lib/windows-terminal-capabilities.ts index c759567df15..4bc5d6d7b6e 100644 --- a/src/renderer/src/lib/windows-terminal-capabilities.ts +++ b/src/renderer/src/lib/windows-terminal-capabilities.ts @@ -11,6 +11,8 @@ export type WindowsTerminalCapabilities = { pwshAvailable: boolean gitBashAvailable: boolean hostPlatform: NodeJS.Platform | null + /** Host-owned PID-reuse proof; absent means the host did not advertise it. */ + windowsProcessStartTimeAvailable?: boolean isLoading: boolean } diff --git a/src/renderer/src/lib/windows-terminal-capability-read.ts b/src/renderer/src/lib/windows-terminal-capability-read.ts index 3c9a7edc6bc..9a77538cefc 100644 --- a/src/renderer/src/lib/windows-terminal-capability-read.ts +++ b/src/renderer/src/lib/windows-terminal-capability-read.ts @@ -49,16 +49,13 @@ export async function readWindowsTerminalCapabilities( } if (target.kind === 'local') { - const [wslAvailable, wslDistros, pwshAvailable, gitBashAvailable, hostPlatform] = + const [wslAvailable, wslDistros, pwshAvailable, gitBashAvailable, runtimeStatus] = await Promise.all([ window.api.wsl.isAvailable().catch(() => false), window.api.wsl.listDistros().catch(() => []), window.api.pwsh.isAvailable().catch(() => false), window.api.gitBash.isAvailable().catch(() => false), - window.api.runtime - .getStatus() - .then((status) => status.hostPlatform ?? null) - .catch(() => null) + window.api.runtime.getStatus().catch(() => null) ]) const reconciledWslAvailable = await reconcileWslAvailability(wslAvailable, wslDistros, () => window.api.wsl.isAvailable() @@ -68,7 +65,10 @@ export async function readWindowsTerminalCapabilities( wslDistros, pwshAvailable, gitBashAvailable, - hostPlatform, + hostPlatform: runtimeStatus?.hostPlatform ?? null, + ...(runtimeStatus?.windowsProcessStartTimeAvailable !== undefined + ? { windowsProcessStartTimeAvailable: runtimeStatus.windowsProcessStartTimeAvailable } + : {}), isLoading: false } } diff --git a/src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts b/src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts index ad35839ba3d..3d3d476753e 100644 --- a/src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts +++ b/src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts @@ -40,6 +40,36 @@ afterEach(() => { }) describe('windows terminal capability re-probe', () => { + it('reprobes usable WSL until Windows process identity is proved', async () => { + vi.useFakeTimers() + let current: WindowsTerminalCapabilities = USABLE_WSL + const probe = vi.fn(async () => { + current = { ...current, windowsProcessStartTimeAvailable: true } + return current + }) + const readCached = () => current + startWindowsTerminalCapabilityReprobe({ ownerKey: 'local', probe, readCached }) + + await vi.advanceTimersByTimeAsync(30_000) + expect(probe).toHaveBeenCalledTimes(1) + expect(readCached().windowsProcessStartTimeAvailable).toBe(true) + + await vi.advanceTimersByTimeAsync(30 * 60_000) + expect(probe).toHaveBeenCalledTimes(1) + }) + + it('resets the backoff when only process identity capability changes', async () => { + vi.useFakeTimers() + const identityAvailable = { ...ABSENT_WSL, windowsProcessStartTimeAvailable: true } + const { probe, readCached } = createWatcher([identityAvailable, identityAvailable]) + startWindowsTerminalCapabilityReprobe({ ownerKey: 'local', probe, readCached }) + + await vi.advanceTimersByTimeAsync(30_000) + expect(probe).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(30_000) + expect(probe).toHaveBeenCalledTimes(2) + }) + it('backs off to a five-minute ceiling on a stable answer', async () => { vi.useFakeTimers() const { probe, readCached } = createWatcher() @@ -55,7 +85,9 @@ describe('windows terminal capability re-probe', () => { it('still re-checks a transient absent answer, then stops once WSL answers', async () => { vi.useFakeTimers() - const { probe, readCached } = createWatcher([USABLE_WSL]) + const { probe, readCached } = createWatcher([ + { ...USABLE_WSL, windowsProcessStartTimeAvailable: true } + ]) startWindowsTerminalCapabilityReprobe({ ownerKey: 'local', probe, readCached }) await vi.advanceTimersByTimeAsync(30_000) diff --git a/src/renderer/src/lib/windows-terminal-capability-reprobe.ts b/src/renderer/src/lib/windows-terminal-capability-reprobe.ts index 674adc565d7..f9b9d44b025 100644 --- a/src/renderer/src/lib/windows-terminal-capability-reprobe.ts +++ b/src/renderer/src/lib/windows-terminal-capability-reprobe.ts @@ -31,13 +31,21 @@ function capabilitySignature(capabilities: WindowsTerminalCapabilities): string capabilities.wslDistros.join('\u0000'), capabilities.pwshAvailable, capabilities.gitBashAvailable, - capabilities.hostPlatform ?? '' + capabilities.hostPlatform ?? '', + capabilities.windowsProcessStartTimeAvailable ].join('|') } -/** The answer #11295 waits for: a usable WSL. Nothing further to watch for. */ +/** A usable WSL is settled only after Windows hosts also prove PID identity. */ function isSettled(capabilities: WindowsTerminalCapabilities): boolean { - return capabilities.wslAvailable && capabilities.wslDistros.length > 0 + if (!capabilities.wslAvailable || capabilities.wslDistros.length === 0) { + return false + } + if (capabilities.hostPlatform === 'win32') { + return capabilities.windowsProcessStartTimeAvailable === true + } + // A missing platform means the status probe may have failed; keep checking until it recovers. + return capabilities.hostPlatform !== null } function clearRunnerTimer(runner: CapabilityReprobeRunner): void { diff --git a/src/shared/child-process/__fixtures__/child-process-import-allowlist.txt b/src/shared/child-process/__fixtures__/child-process-import-allowlist.txt index fd8502d8913..d7a503bbaf2 100644 --- a/src/shared/child-process/__fixtures__/child-process-import-allowlist.txt +++ b/src/shared/child-process/__fixtures__/child-process-import-allowlist.txt @@ -57,7 +57,6 @@ src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-interference-shims.ts src/main/codex-accounts/service.ts -src/main/codex/codex-app-server-client.ts src/main/codex/codex-app-server-posix-supervisor.ts src/main/codex/codex-app-server-session.ts src/main/codex/codex-state-db-backfill-recovery.ts diff --git a/src/shared/child-process/child-process-import-boundary.test.ts b/src/shared/child-process/child-process-import-boundary.test.ts index 3abdf8023c4..ac4a02f6ee5 100644 --- a/src/shared/child-process/child-process-import-boundary.test.ts +++ b/src/shared/child-process/child-process-import-boundary.test.ts @@ -29,7 +29,7 @@ const CHILD_PROCESS_IMPORT_ALLOWLIST: readonly string[] = readFileSync( * May only ever be DECREASED, and only by migrating a file off * `node:child_process`. Raising it is never the fix. */ -const DIRECT_IMPORTER_PIN = 156 +const DIRECT_IMPORTER_PIN = 155 const IMPORT_PATTERN = /(?:from\s+['"]node:child_process['"]|from\s+['"]child_process['"]|require\(\s*['"]node:child_process['"]|require\(\s*['"]child_process['"])/ diff --git a/src/shared/runtime-session-contracts.ts b/src/shared/runtime-session-contracts.ts index 9b7bf2ee0cd..99b4fbe4d6f 100644 --- a/src/shared/runtime-session-contracts.ts +++ b/src/shared/runtime-session-contracts.ts @@ -78,6 +78,8 @@ export type RuntimeStatus = { worktreeCreateIdempotency?: { dedupeTtlMs: number } + /** True only when this Windows host can prove process creation times for PID ownership. */ + windowsProcessStartTimeAvailable?: boolean /** * Optional for mixed-version peers. Absence means the host predates structured * degradation reporting, not that the host proved every optional feature available. diff --git a/src/shared/structured-native-chat-launch-route.test.ts b/src/shared/structured-native-chat-launch-route.test.ts index 48cb117fdf5..ee13a8fb590 100644 --- a/src/shared/structured-native-chat-launch-route.test.ts +++ b/src/shared/structured-native-chat-launch-route.test.ts @@ -22,7 +22,6 @@ function support(overrides: Partial = {}) { return resolveStructuredNativeChatSupport({ agent: 'claude', executionHostId: 'local', - platform: 'darwin', hostCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], workspaceKind: 'git-worktree', ...overrides @@ -64,7 +63,6 @@ describe('per-launch structured feasibility', () => { ['a floating workspace', { workspaceKind: 'floating' }, 'floating-workspace'], ['a custom TUI launch', { requiresTuiLaunchCustomization: true }, 'tui-launch-customization'], ['an SSH host', { executionHostId: 'ssh:host-a' }, 'remote-execution-host'], - ['Codex on Windows', { agent: 'codex', platform: 'win32' }, 'codex-on-windows'], ['a missing capability', { hostCapabilities: [] }, 'runtime-capability'] ] as [string, Partial, string][])( 'names %s as the blocker', @@ -73,9 +71,14 @@ describe('per-launch structured feasibility', () => { } ) - it('leaves a Windows Claude launch to the executing host', () => { - expect(support({ agent: 'claude', platform: 'win32' })).toEqual({ supported: true }) - }) + // The client cannot see whether the host can read a provider child's start time, so neither + // provider is refused here on platform; agentSession.createSupport answers that at create time. + it.each(['claude', 'codex'] as const)( + 'leaves a Windows %s launch to the executing host', + (agent) => { + expect(support({ agent })).toEqual({ supported: true }) + } + ) it('blocks a WSL or repair-required project runtime', () => { expect( diff --git a/src/shared/structured-native-chat-launch-route.ts b/src/shared/structured-native-chat-launch-route.ts index b97ffcc0dac..8498fe674ce 100644 --- a/src/shared/structured-native-chat-launch-route.ts +++ b/src/shared/structured-native-chat-launch-route.ts @@ -26,7 +26,6 @@ export type StructuredNativeChatBlocker = | 'floating-workspace' | 'tui-launch-customization' | 'remote-execution-host' - | 'codex-on-windows' | 'project-runtime' | 'runtime-capability' @@ -37,7 +36,6 @@ export type StructuredNativeChatSupport = export type StructuredNativeChatSupportInput = { agent: TuiAgent executionHostId: string - platform: NodeJS.Platform hostCapabilities: readonly string[] workspaceKind?: 'git-worktree' | 'folder' | 'floating' projectRuntime?: ProjectExecutionRuntimeResolution | null @@ -82,12 +80,6 @@ export function resolveStructuredNativeChatSupport( if (input.executionHostId !== 'local') { return { supported: false, blocker: 'remote-execution-host' } } - // Codex's Windows refusal is deliberate and settled elsewhere, so it stays a client-side answer. - // Claude's is measured by the executing host at create time (agentSession.createSupport) because - // only that host knows whether it can read a provider child's start time. - if (input.agent === 'codex' && input.platform === 'win32') { - return { supported: false, blocker: 'codex-on-windows' } - } const projectRuntime = input.projectRuntime if (projectRuntime?.status === 'repair-required' || projectRuntime?.runtime.kind === 'wsl') { return { supported: false, blocker: 'project-runtime' } From bcb703fb4ca433b5077d170ad908c25a069db00d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 7 Sep 2026 09:32:14 -0700 Subject: [PATCH 19/37] test(ssh): isolate the MFA fixture from the developer's real ~/.ssh (#19300) The multi-stage cases pass `resolved: null`, so `resolvePrivateKeys` falls through to `findDefaultKeyFile`, which reads `~/.ssh/id_*` via `homedir()`. On a machine with an encrypted default key ssh2 rejects with "Cannot parse privateKey" before authentication is exercised, so two cases failed locally while staying green on hosted CI, which has no key. Point home at the existing fixture directory so default-key discovery stays in the test's control. Co-authored-by: Merge Sim --- .../ssh-multi-factor-authentication.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/main/ssh/ssh-multi-factor-authentication.test.ts b/src/main/ssh/ssh-multi-factor-authentication.test.ts index 275ea2e3247..2ee643dea7a 100644 --- a/src/main/ssh/ssh-multi-factor-authentication.test.ts +++ b/src/main/ssh/ssh-multi-factor-authentication.test.ts @@ -186,9 +186,19 @@ function connectWithOrcaConfig( describe('multi-stage SSH authentication', () => { let tempDir: string let keyPaths: string[] + let homeEnv: { HOME?: string; USERPROFILE?: string } beforeEach(() => { tempDir = mkdtempSync(join(tmpdir(), 'orca-mfa-')) + // Why: the cases below pass `resolved: null`, so `resolvePrivateKeys` falls through to + // `findDefaultKeyFile`, which reads `~/.ssh/id_*` through `homedir()`. On a developer + // machine that picks up a real key, and an encrypted one makes ssh2 reject with + // "Cannot parse privateKey" before authentication is exercised at all. Hosted CI has no + // key, so this only ever failed locally. Pointing home at the fixture directory keeps + // default-key discovery inside the test's control on every machine. + homeEnv = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE } + process.env.HOME = tempDir + process.env.USERPROFILE = tempDir keyPaths = ['id_a', 'id_b'].map((name) => { const path = join(tempDir, name) writeFileSync(path, utils.generateKeyPairSync('ecdsa', { bits: 256 }).private) @@ -197,6 +207,14 @@ describe('multi-stage SSH authentication', () => { }) afterEach(() => { + for (const key of ['HOME', 'USERPROFILE'] as const) { + const previous = homeEnv[key] + if (previous === undefined) { + delete process.env[key] + } else { + process.env[key] = previous + } + } rmSync(tempDir, { recursive: true, force: true }) }) From 6ae5418a890a7d410952c9e7e34ed51c9e20e3d4 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Mon, 7 Sep 2026 09:33:23 -0700 Subject: [PATCH 20/37] Add localization for activity view and sidebar (#18589) * i18n: add localization for activity view and sidebar Wrap activity thread state labels, interrupted status, and sidebar title in translate() calls. Add localization keys to all five locale catalogs (en, es, ja, ko, zh) to enable translation support. * i18n: refactor to static keys for activity and sidebar Convert dynamic translation key construction to static literal keys, enabling proper i18n catalog registration. This ensures activity state labels and sidebar strings are bundled in the boot catalog with their complete translations. * i18n: change permission state label to 'Needs attention' - Rename state label for semantic clarity across all locales - Remove strings now using static keys (per i18n refactor to static keys) --------- Co-authored-by: m4air Co-authored-by: m4air --- .../activity/activity-thread-presentation.ts | 42 +++++++++++++++++-- .../src/components/sidebar/SidebarHeader.tsx | 5 ++- src/renderer/src/i18n/locales/en.json | 18 +++++++- src/renderer/src/i18n/locales/es.json | 28 ++++++++++++- src/renderer/src/i18n/locales/ja.json | 28 ++++++++++++- src/renderer/src/i18n/locales/ko.json | 28 ++++++++++++- src/renderer/src/i18n/locales/zh.json | 28 ++++++++++++- 7 files changed, 163 insertions(+), 14 deletions(-) diff --git a/src/renderer/src/components/activity/activity-thread-presentation.ts b/src/renderer/src/components/activity/activity-thread-presentation.ts index 93d69c7688a..f1262082345 100644 --- a/src/renderer/src/components/activity/activity-thread-presentation.ts +++ b/src/renderer/src/components/activity/activity-thread-presentation.ts @@ -1,4 +1,4 @@ -import { agentStateLabel, type AgentDotState } from '@/components/AgentStateDot' +import type { AgentDotState } from '@/components/AgentStateDot' import { formatAgentTypeLabel } from '@/lib/agent-status' import { getAgentRowPrimaryText } from '@/lib/agent-row-primary-text' import { showsAgentToolPreview } from '@/lib/agent-row-tool-preview' @@ -8,6 +8,7 @@ import { resolveActivityThreadStatusPreview } from '@/lib/activity-thread-display' import { formatUiRelativeTime } from '@/i18n/relative-time-format' +import { translate } from '@/i18n/i18n' import type { AgentStatusEntry, AgentStatusState } from '../../../../shared/agent-status-types' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import type { ActivityEvent, AgentPaneThread } from './activity-thread-types' @@ -109,9 +110,44 @@ export function threadAgentState(thread: AgentPaneThread): AgentDotState { export function threadAgentStateLabel(thread: AgentPaneThread): string { const state = threadAgentState(thread) if (!thread.currentAgentState && state === 'done' && thread.latestEvent?.entry.interrupted) { - return 'Interrupted' + return translate('auto.components.activity.ActivityPrototypePage.interrupted', 'Interrupted') + } + // Literal keys with literal fallbacks: a dynamic key registers no catalog reference + // and forces every state string into the boot bundle. + switch (state) { + case 'working': + return translate('auto.components.activity.ActivityPrototypePage.state.working', 'Working') + case 'monitoring': + return translate( + 'auto.components.activity.ActivityPrototypePage.state.monitoring', + 'Monitoring background tasks' + ) + case 'blocked': + return translate('auto.components.activity.ActivityPrototypePage.state.blocked', 'Blocked') + case 'waiting': + return translate( + 'auto.components.activity.ActivityPrototypePage.state.waiting', + 'Waiting for input' + ) + case 'interrupted': + return translate('auto.components.activity.ActivityPrototypePage.interrupted', 'Interrupted') + case 'failed': + return translate('auto.components.activity.ActivityPrototypePage.state.failed', 'Failed') + case 'done': + return translate('auto.components.activity.ActivityPrototypePage.state.done', 'Done') + case 'idle': + return translate('auto.components.activity.ActivityPrototypePage.state.idle', 'Idle') + case 'unverifiable': + return translate( + 'auto.components.activity.ActivityPrototypePage.state.unverifiable', + 'No recent update' + ) + case 'permission': + return translate( + 'auto.components.activity.ActivityPrototypePage.state.permission', + 'Needs attention' + ) } - return agentStateLabel(state) } export type ActivityThreadStatusKind = 'tool' | 'message' | 'state' | 'none' diff --git a/src/renderer/src/components/sidebar/SidebarHeader.tsx b/src/renderer/src/components/sidebar/SidebarHeader.tsx index fafd7094034..413558ff9c7 100644 --- a/src/renderer/src/components/sidebar/SidebarHeader.tsx +++ b/src/renderer/src/components/sidebar/SidebarHeader.tsx @@ -36,7 +36,10 @@ const SidebarHeader = React.memo(function SidebarHeader({ const acknowledgeIntro = React.useCallback(() => { void updateSettings?.({ agentsSidebarIntroShown: true }) }, [updateSettings]) - const sidebarTitle = groupBy === 'repo' ? 'Projects' : 'Workspaces' + const sidebarTitle = + groupBy === 'repo' + ? translate('dashboard.sidebar.projects', 'Projects') + : translate('dashboard.sidebar.workspaces', 'Workspaces') const activityLabel = translate( agentsViewActive ? 'dashboard.sidebar.closeActivity' : 'dashboard.sidebar.openActivity', agentsViewActive ? 'Turn off activity view' : 'View activity' diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b23161d3887..e3198b9c45a 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -16225,7 +16225,19 @@ "showUnreadOnly": "Show unread only", "showChildAgents": "Show child agents", "activityOptions": "Activity options", - "threadListOptionsFiltered": "Thread list options, filters active" + "threadListOptionsFiltered": "Thread list options, filters active", + "interrupted": "Interrupted", + "state": { + "working": "Working", + "monitoring": "Monitoring background tasks", + "blocked": "Blocked", + "waiting": "Waiting for input", + "failed": "Failed", + "done": "Done", + "idle": "Idle", + "unverifiable": "No recent update", + "permission": "Needs attention" + } }, "clearCompleted": { "clearedOne": "Cleared 1 completed agent", @@ -17617,7 +17629,9 @@ "label": "Agents", "dashboardLabel": "Agent Dashboard", "openActivity": "View activity", - "closeActivity": "Turn off activity view" + "closeActivity": "Turn off activity view", + "projects": "Projects", + "workspaces": "Workspaces" } }, "runtimeRpc": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 3c2881e16f2..e7fc5a60e42 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -14186,7 +14186,27 @@ "beb2c19173": "No leído", "5651b216c6": "Proyecto desconocido", "22b22034bc": "Terminal independiente no disponible en Actividad.", - "afdc2139a8": "Terminal de Agent cerrada. Abre una nueva terminal en este workspace para continuar." + "afdc2139a8": "Terminal de Agent cerrada. Abre una nueva terminal en este workspace para continuar.", + "compactModeDescription": "Muestra filas de hilo más cortas con títulos de una línea y mensajes de estado de dos líneas.", + "unreadOnlyDescription": "Filtra la lista de actividad para mostrar solo hilos con actualizaciones sin leer.", + "clearCompleted": "Borrar completados", + "none": "Ninguno", + "search": "Buscar", + "showUnreadOnly": "Mostrar solo no leídos", + "showChildAgents": "Mostrar agentes secundarios", + "activityOptions": "Opciones de actividad", + "interrupted": "Interrumpido", + "state": { + "working": "Trabajando", + "monitoring": "Supervisando tareas en segundo plano", + "blocked": "Bloqueado", + "waiting": "Esperando entrada", + "failed": "Fallido", + "done": "Completado", + "idle": "Inactivo", + "unverifiable": "Sin actualizaciones recientes", + "permission": "Requiere atención" + } }, "ActivityScopeFilterControls": { "resetScope": "Mostrar todos los hosts y proyectos" @@ -14842,7 +14862,11 @@ "dashboard": { "sidebar": { "label": "Agentes", - "dashboardLabel": "Panel de agentes" + "dashboardLabel": "Panel de agentes", + "openActivity": "Ver actividad", + "closeActivity": "Cerrar vista de actividad", + "projects": "Proyectos", + "workspaces": "Espacios de trabajo" } }, "browser": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index c46c27ddf5a..1dcf28f78fa 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -14186,7 +14186,27 @@ "beb2c19173": "未読", "5651b216c6": "不明なプロジェクト", "22b22034bc": "スタンドアロンターミナルはアクティビティでは使用できません。", - "afdc2139a8": "Agent ターミナルが閉じられました。続行するには、このワークスペースで新規ターミナルを開いてください。" + "afdc2139a8": "Agent ターミナルが閉じられました。続行するには、このワークスペースで新規ターミナルを開いてください。", + "compactModeDescription": "1 行のタイトルと 2 行のステータスメッセージで短いスレッド行を表示します。", + "unreadOnlyDescription": "未読の更新があるスレッドのみをアクティビティ一覧に表示します。", + "clearCompleted": "完了済みをクリア", + "none": "なし", + "search": "検索", + "showUnreadOnly": "未読のみ表示", + "showChildAgents": "子 Agent を表示", + "activityOptions": "アクティビティのオプション", + "interrupted": "中断", + "state": { + "working": "作業中", + "monitoring": "バックグラウンドタスクを監視中", + "blocked": "ブロック", + "waiting": "入力待ち", + "failed": "失敗", + "done": "完了", + "idle": "アイドル", + "unverifiable": "最近の更新なし", + "permission": "要対応" + } }, "ActivityScopeFilterControls": { "resetScope": "すべてのホストとプロジェクトを表示" @@ -14877,7 +14897,11 @@ "dashboard": { "sidebar": { "label": "Agent", - "dashboardLabel": "Agent ダッシュボード" + "dashboardLabel": "Agent ダッシュボード", + "openActivity": "アクティビティを表示", + "closeActivity": "アクティビティビューを閉じる", + "projects": "プロジェクト", + "workspaces": "ワークスペース" } }, "browser": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 8314abe56c8..710df014665 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -14264,7 +14264,27 @@ "beb2c19173": "읽지 않음", "5651b216c6": "알 수 없는 프로젝트", "22b22034bc": "활동에서는 독립형 terminal을 사용할 수 없습니다.", - "afdc2139a8": "Agent terminal이 닫혔습니다. 계속하려면 이 워크스페이스에서 새 terminal을 여세요." + "afdc2139a8": "Agent terminal이 닫혔습니다. 계속하려면 이 워크스페이스에서 새 terminal을 여세요.", + "compactModeDescription": "한 줄 제목과 두 줄 상태 메시지로 더 짧은 스레드 행을 표시합니다.", + "unreadOnlyDescription": "읽지 않은 업데이트가 있는 스레드만 활동 목록에 표시합니다.", + "clearCompleted": "완료된 항목 지우기", + "none": "없음", + "search": "검색", + "showUnreadOnly": "읽지 않은 항목만 표시", + "showChildAgents": "하위 에이전트 표시", + "activityOptions": "활동 옵션", + "interrupted": "중단됨", + "state": { + "working": "작업 중", + "monitoring": "백그라운드 작업 모니터링 중", + "blocked": "차단됨", + "waiting": "입력 대기 중", + "failed": "실패", + "done": "완료", + "idle": "유휴", + "unverifiable": "최근 업데이트 없음", + "permission": "주의 필요" + } }, "ActivityScopeFilterControls": { "resetScope": "모든 호스트 및 프로젝트 표시" @@ -15016,7 +15036,11 @@ "dashboard": { "sidebar": { "label": "에이전트", - "dashboardLabel": "에이전트 대시보드" + "dashboardLabel": "에이전트 대시보드", + "openActivity": "활동 보기", + "closeActivity": "활동 보기 닫기", + "projects": "프로젝트", + "workspaces": "워크스페이스" } }, "browser": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 17f60476de0..7d60495e3b5 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -14264,7 +14264,27 @@ "beb2c19173": "未读", "5651b216c6": "未知项目", "22b22034bc": "独立终端在活动中不可用。", - "afdc2139a8": "智能体终端关闭。在此工作区中打开一个新终端以继续。" + "afdc2139a8": "智能体终端关闭。在此工作区中打开一个新终端以继续。", + "compactModeDescription": "以单行标题和两行状态消息显示更短的线程行。", + "unreadOnlyDescription": "将活动列表筛选为仅显示有未读更新的线程。", + "clearCompleted": "清除已完成", + "none": "无", + "search": "搜索", + "showUnreadOnly": "仅显示未读", + "showChildAgents": "显示子智能体", + "activityOptions": "活动选项", + "interrupted": "已中断", + "state": { + "working": "工作中", + "monitoring": "监控后台任务", + "blocked": "受阻", + "waiting": "等待输入", + "failed": "失败", + "done": "完成", + "idle": "空闲", + "unverifiable": "暂无近期更新", + "permission": "需注意" + } }, "ActivityScopeFilterControls": { "resetScope": "显示所有主机和项目" @@ -14981,7 +15001,11 @@ "dashboard": { "sidebar": { "label": "智能体", - "dashboardLabel": "智能体仪表盘" + "dashboardLabel": "智能体仪表盘", + "openActivity": "查看活动", + "closeActivity": "关闭活动视图", + "projects": "项目", + "workspaces": "工作区" } }, "browser": { From bffdad9f05f61f3a6f3b961148a3f31304543dc9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 7 Sep 2026 09:36:14 -0700 Subject: [PATCH 21/37] fix(native-chat): make structured chat tabs renameable (#19153) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(native-chat): let a structured chat tab be renamed Renaming a native chat tab accepted the text and silently did nothing: setTabCustomTitle only scanned terminal tabs and only bridged to unified tabs whose contentType was 'terminal', so the agent-session tab it was keyed to never matched. Any label that did land was then re-nulled by the next host snapshot, which preserved color/createdAt/isPinned but not customLabel. Also routes both placeholder sites through one helper so a Claude chat stops falling back to 'Codex Chat'. * test(native-chat): cover structured chat tab rename and label fallback * chore: drop the local @pnpm/exe lockfile artifact Swept in accidentally; running pnpm here adds @pnpm/exe to the root lockfile, which fails CI's frozen-lockfile guard. * fix(native-chat): reach the rename shortcut and tab color too Review found the first fix covered only the context-menu path. The tab.rename shortcut gated on activeTabType === 'terminal', so on a structured chat tab it stayed the silent no-op this branch set out to fix. setTabColor carried the identical terminal-only lookup one function below the one that was fixed. Both lookups now share one resolver instead of two copies. * fix(native-chat): stop unknown agents reading as Codex, cover the terminal path Review found the placeholder helper encoded "unknown means Codex": its signature accepts null/undefined and Tab.agentSessionAgent is the open AgentType, so the first caller passing a Tab would label gemini or grok as "Codex Chat". Routed through the shared agent-name table instead. Also adds the missing regression test that a terminal rename still resolves through its entityId now that both rename and color share one resolver, and a guard on a test that passed with the fix reverted. * fix(native-chat): degrade instead of throwing on a null tab title A stacked branch can publish title: null when a conversation name is cleared. The wire type says string, so this consumer trusted it and threw inside the store patch that applies the snapshot. Fall back to the placeholder — the producer bug is fixed separately, but a consumer of wire data should not crash on a contract violation. * fix(native-chat): rename the focused structured tab, not a background terminal * fix(native-chat): cycle terminals from the structured tab, not a stale terminal --------- Co-authored-by: Merge Sim --- ...tore-structured-agent-session-tabs-once.ts | 3 +- .../app-command-handlers-tab-rename.test.ts | 165 ++++++++++++++++++ .../src/app-shell/app-command-handlers.ts | 34 +++- .../components/tab-bar/tab-bar-item-model.ts | 3 + .../src/components/terminal/tab-type-cycle.ts | 15 +- ...c-tab-switch-group-order-hydration.test.ts | 15 +- ...pc-tab-switch-structured-tab-cycle.test.ts | 142 +++++++++++++++ src/renderer/src/hooks/ipc-tab-switch.test.ts | 13 +- src/renderer/src/hooks/ipc-tab-switch.ts | 9 +- .../mirrored-agent-tab-label.test.ts | 85 +++++++++ .../terminal-surfaces.ts | 9 +- .../store/terminals/renamable-unified-tab.ts | 15 ++ .../structured-chat-tab-rename.test.ts | 114 ++++++++++++ .../store/terminals/terminal-tab-attention.ts | 9 +- src/shared/agent-session-chat-label.ts | 9 + 15 files changed, 617 insertions(+), 23 deletions(-) create mode 100644 src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts create mode 100644 src/renderer/src/hooks/ipc-tab-switch-structured-tab-cycle.test.ts create mode 100644 src/renderer/src/runtime/web-session-tabs-sync/mirrored-agent-tab-label.test.ts create mode 100644 src/renderer/src/store/terminals/renamable-unified-tab.ts create mode 100644 src/renderer/src/store/terminals/structured-chat-tab-rename.test.ts create mode 100644 src/shared/agent-session-chat-label.ts diff --git a/src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts b/src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts index 536f00723f7..e912cc6b665 100644 --- a/src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts +++ b/src/main/runtime/orca-runtime-restore-structured-agent-session-tabs-once.ts @@ -1,4 +1,5 @@ // @ts-nocheck -- mechanically split from OrcaRuntimeService; behavior is covered by AST equivalence and characterization tests. +import { defaultAgentChatLabel } from '../../shared/agent-session-chat-label' import { OrcaRuntimeWithResolveRecoveredStructuredTuiTranscript } from './orca-runtime-resolve-recovered-structured-tui-transcript' import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' import { replaceConversationInSnapshot } from './structured-conversation-tab-replacement' @@ -132,7 +133,7 @@ export class OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce extends OrcaRu const tab: RuntimeMobileSessionAgentTab = { type: 'agent-session', id, - title: input.agent === 'claude' ? 'Claude Chat' : 'Codex Chat', + title: defaultAgentChatLabel(input.agent), sessionId: input.sessionId, ...(input.replacesSessionId ? { replacesSessionId: input.replacesSessionId } : {}), agent: input.agent, diff --git a/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts b/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts new file mode 100644 index 00000000000..80e43afddd3 --- /dev/null +++ b/src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts @@ -0,0 +1,165 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Tab, TabGroup } from '../../../shared/tab-types' +import type { TerminalTab } from '../../../shared/terminal-tab-types' +import type { AppState } from '@/store/types' +import { createTabsFocusActions } from '../store/slices/tabs/tabs-focus-actions' +import type { TabsSliceGet, TabsSliceSet } from '../store/slices/tabs/tabs-slice-contract' +import { buildActiveSurfacePatch } from '../store/slices/tabs/tabs-surface' +import type { AppShortcutState, ShortcutDispatchInput } from './app-command-handlers' + +const mocks = vi.hoisted(() => ({ + requestTerminalTabRename: vi.fn(), + store: {} as AppState +})) + +vi.mock('../store', () => ({ + useAppStore: Object.assign(vi.fn(), { getState: () => mocks.store }) +})) + +vi.mock('../components/tab-bar/terminal-tab-rename-request', () => ({ + requestTerminalTabRename: mocks.requestTerminalTabRename +})) + +vi.mock('@/lib/floating-workspace-terminal-actions', () => ({ + isFloatingWorkspacePanelFocused: () => false +})) + +vi.mock('@/lib/terminal-shortcut-capture-notification', () => ({ + showTerminalShortcutCaptureNotification: vi.fn() +})) + +import { createAppCommandHandlers } from './app-command-handlers' + +const WORKTREE_ID = 'repo::/feature' +const GROUP_ID = 'group-1' +const TERMINAL_ENTITY_ID = 'terminal-1' +const TERMINAL_UNIFIED_ID = 'unified-terminal' +const CHAT_UNIFIED_ID = 'unified-chat' + +function unifiedTab(overrides: Partial & Pick): Tab { + return { + groupId: GROUP_ID, + worktreeId: WORKTREE_ID, + label: overrides.id, + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0, + ...overrides + } +} + +/** + * Builds the store the real app has when `activeGroupTabId` is focused: the raw group/tab state + * plus the active-surface fields derived from it by the same code the store runs. That derivation + * is what leaves `activeTabId` pointing at a background terminal while a structured tab is active, + * so stubbing those fields instead would hide exactly the half under test. + */ +function storeForActiveTab(activeGroupTabId: string): AppState { + const groups: TabGroup[] = [ + { + id: GROUP_ID, + worktreeId: WORKTREE_ID, + activeTabId: activeGroupTabId, + tabOrder: [TERMINAL_UNIFIED_ID, CHAT_UNIFIED_ID] + } + ] + const rawState = { + activeBrowserTabIdByWorktree: {}, + activeFileIdByWorktree: {}, + activeGroupIdByWorktree: { [WORKTREE_ID]: GROUP_ID }, + // The user focused this terminal before switching to the structured tab. + activeTabIdByWorktree: { [WORKTREE_ID]: TERMINAL_ENTITY_ID }, + activeTabTypeByWorktree: {}, + browserTabsByWorktree: {}, + groupsByWorktree: { [WORKTREE_ID]: groups }, + layoutByWorktree: {}, + openFiles: [], + tabsByWorktree: { + [WORKTREE_ID]: [{ id: TERMINAL_ENTITY_ID, worktreeId: WORKTREE_ID } as TerminalTab] + }, + unifiedTabsByWorktree: { + [WORKTREE_ID]: [ + unifiedTab({ + id: TERMINAL_UNIFIED_ID, + entityId: TERMINAL_ENTITY_ID, + contentType: 'terminal' + }), + unifiedTab({ id: CHAT_UNIFIED_ID, entityId: 'session-1', contentType: 'agent-session' }) + ] + } + } as unknown as AppState + const store = { + ...rawState, + ...buildActiveSurfacePatch(rawState, WORKTREE_ID) + } as AppState + const noopSet = (() => {}) as unknown as TabsSliceSet + store.getActiveTab = createTabsFocusActions(noopSet, (() => store) as TabsSliceGet).getActiveTab + return store +} + +function shortcutState(): AppShortcutState { + return { + activeView: 'terminal', + activeWorktreeId: WORKTREE_ID, + actions: {} as AppShortcutState['actions'], + creationLayoutActive: false, + floatingTerminalEnabled: false, + floatingTerminalOpen: false, + floatingVisibleTabCount: 0, + keybindings: {}, + openFloatingWorkspaceMaximized: vi.fn(), + pluginCommands: [], + setFloatingTerminalOpen: vi.fn(), + terminalShortcutPolicy: 'orca-first', + workspaceChromeActive: true + } +} + +function shortcutInput(): ShortcutDispatchInput { + return { target: null, defaultPrevented: false, preventDefault: vi.fn() } +} + +function runRename(state: AppShortcutState = shortcutState()): boolean | undefined { + return createAppCommandHandlers(state, shortcutInput(), 'terminal').get('tab.rename')?.() +} + +describe('tab.rename shortcut', () => { + beforeEach(() => vi.clearAllMocks()) + + it('leaves activeTabId on a background terminal while a structured tab is active', () => { + // Guards the premise of the test below: without this the structured case proves nothing. + mocks.store = storeForActiveTab(CHAT_UNIFIED_ID) + expect(mocks.store.activeTabType).toBe('agent-session') + expect(mocks.store.activeTabId).toBe(TERMINAL_ENTITY_ID) + }) + + it('renames the structured chat tab, not the stale background terminal', () => { + mocks.store = storeForActiveTab(CHAT_UNIFIED_ID) + expect(runRename()).toBe(true) + expect(mocks.requestTerminalTabRename).toHaveBeenCalledWith(CHAT_UNIFIED_ID) + expect(mocks.requestTerminalTabRename).not.toHaveBeenCalledWith(TERMINAL_ENTITY_ID) + }) + + it('still renames the terminal tab by its backing terminal id', () => { + mocks.store = storeForActiveTab(TERMINAL_UNIFIED_ID) + expect(mocks.store.activeTabType).toBe('terminal') + expect(runRename()).toBe(true) + expect(mocks.requestTerminalTabRename).toHaveBeenCalledWith(TERMINAL_ENTITY_ID) + }) + + it('does not claim the chord for a tab type that has no inline rename', () => { + mocks.store = { + ...storeForActiveTab(CHAT_UNIFIED_ID), + activeTabType: 'browser' + } as AppState + expect(runRename()).toBe(false) + expect(mocks.requestTerminalTabRename).not.toHaveBeenCalled() + }) + + it('does not claim the chord for a structured tab with no active worktree', () => { + mocks.store = storeForActiveTab(CHAT_UNIFIED_ID) + expect(runRename({ ...shortcutState(), activeWorktreeId: null })).toBe(false) + expect(mocks.requestTerminalTabRename).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/app-shell/app-command-handlers.ts b/src/renderer/src/app-shell/app-command-handlers.ts index bb60f898130..1a7264efb5e 100644 --- a/src/renderer/src/app-shell/app-command-handlers.ts +++ b/src/renderer/src/app-shell/app-command-handlers.ts @@ -75,6 +75,24 @@ export function getKeybindingContext(target: EventTarget | null): KeybindingCont : 'app' } +/** + * The tab id the inline rename editor listens on, which differs per tab kind: a terminal tab is + * addressed by its backing terminal id (`activeTabId`), a structured chat tab by its unified tab + * id. `activeTabId` is terminal-only state and never moves for a structured tab, so reading it + * there targets whichever terminal was last active. Mirrors TabGroupPanel's tab-strip resolution. + */ +function resolveRenameTargetTabId(activeWorktreeId: string | null): string | null { + const store = useAppStore.getState() + if (store.activeTabType === 'terminal') { + return store.activeTabId + } + if (store.activeTabType !== 'agent-session' || !activeWorktreeId) { + return null + } + const activeTab = store.getActiveTab(activeWorktreeId) + return activeTab?.contentType === 'agent-session' ? activeTab.id : null +} + /** * Builds the app-level handlers for every keybindable action. Each returns whether it claimed * the chord, so an unavailable surface (settings view, closed floating panel) falls through to @@ -172,16 +190,16 @@ export function createAppCommandHandlers( [ 'tab.rename', () => { - const store = useAppStore.getState() - if ( - !workspaceChromeActive || - floatingWorkspaceFocused || - store.activeTabType !== 'terminal' || - !store.activeTabId - ) { + if (!workspaceChromeActive || floatingWorkspaceFocused) { return false } - return claim('tab.rename', () => requestTerminalTabRename(store.activeTabId!)) + // Why: a structured chat tab is renamed through the same inline editor, so gating on + // 'terminal' alone left the shortcut a silent no-op there. + const tabId = resolveRenameTargetTabId(activeWorktreeId) + if (!tabId) { + return false + } + return claim('tab.rename', () => requestTerminalTabRename(tabId)) } ], [ diff --git a/src/renderer/src/components/tab-bar/tab-bar-item-model.ts b/src/renderer/src/components/tab-bar/tab-bar-item-model.ts index d5b00ada161..3789d89b7de 100644 --- a/src/renderer/src/components/tab-bar/tab-bar-item-model.ts +++ b/src/renderer/src/components/tab-bar/tab-bar-item-model.ts @@ -234,6 +234,9 @@ export function findActiveVisibleTabId( return active.activeTabType === 'simulator' && item.id === active.activeSimulatorTabId } if (item.type === 'agent-session') { + // Reachable only from TabGroupPanel, which passes the structured tab's own id; the store's + // `activeTabId` names a background terminal here (cf. TerminalTitlebarTabs, which resolves + // `getActiveTab(...)?.id` for 'simulator' and never renders agent-session items). return active.activeTabType === 'agent-session' && item.id === active.activeTabId } return ( diff --git a/src/renderer/src/components/terminal/tab-type-cycle.ts b/src/renderer/src/components/terminal/tab-type-cycle.ts index 051c2533518..3de13076c15 100644 --- a/src/renderer/src/components/terminal/tab-type-cycle.ts +++ b/src/renderer/src/components/terminal/tab-type-cycle.ts @@ -18,11 +18,19 @@ type GetNextTabWithinActiveTypeParams = { direction: number } +/** + * The backing entity id of the active tab, in the same id domain the cyclable entries use. + * + * `activeAgentSessionEntityId` is optional because a caller that only compares type-matched + * entries stays correct without it; a caller that searches a pre-filtered single-type list must + * pass it, or a structured tab resolves to a live background terminal (see the branch below). + */ export function getActiveEntityIdForTabType( activeTabType: TabCycleType, activeTabId: string | null, activeFileId: string | null, - activeBrowserTabId: string | null + activeBrowserTabId: string | null, + activeAgentSessionEntityId: string | null = null ): string | null { if (activeTabType === 'editor') { return activeFileId @@ -30,6 +38,11 @@ export function getActiveEntityIdForTabType( if (activeTabType === 'browser') { return activeBrowserTabId } + // Why: `activeTabId` is terminal-only state that keeps naming a live background terminal while a + // structured tab is active, so falling through here cycles from a tab the user is not on. + if (activeTabType === 'agent-session') { + return activeAgentSessionEntityId + } if (activeTabType === 'simulator') { return activeTabId } diff --git a/src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts b/src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts index 2f8f1131559..7711d795403 100644 --- a/src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts +++ b/src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts @@ -9,6 +9,9 @@ const { getStateMock } = vi.hoisted(() => ({ getStateMock: vi.fn() })) vi.mock('../store', () => ({ useAppStore: { getState: getStateMock } })) +import { createTabsFocusActions } from '../store/slices/tabs/tabs-focus-actions' +import type { TabsSliceGet, TabsSliceSet } from '../store/slices/tabs/tabs-slice-contract' + import { handleSwitchTab, handleSwitchTabAcrossAllTypes, @@ -39,7 +42,7 @@ function stateWithGroupOrder(tabOrder: string[]) { terminalTab('tab-2', 'term-2', 1), terminalTab('tab-3', 'term-3', 2) ] - return { + const store = { activeWorktreeId: WT, activeTabType: 'terminal' as const, activeTabId: 'term-1', @@ -58,8 +61,16 @@ function stateWithGroupOrder(tabOrder: string[]) { setActiveFile: vi.fn(), setActiveBrowserTab: vi.fn(), setActiveTabType: vi.fn(), - activateTab: vi.fn() + activateTab: vi.fn(), + getActiveTab: (_worktreeId: string): unknown => null } + // Why the real resolver: a hand-written stub would decide the group-scoped answer the code + // under test is meant to exercise. + store.getActiveTab = createTabsFocusActions( + (() => {}) as unknown as TabsSliceSet, + (() => store) as unknown as TabsSliceGet + ).getActiveTab + return store } describe('tab-cycle chord against a group whose tabOrder is still hydrating', () => { diff --git a/src/renderer/src/hooks/ipc-tab-switch-structured-tab-cycle.test.ts b/src/renderer/src/hooks/ipc-tab-switch-structured-tab-cycle.test.ts new file mode 100644 index 00000000000..1bdb41bd5c4 --- /dev/null +++ b/src/renderer/src/hooks/ipc-tab-switch-structured-tab-cycle.test.ts @@ -0,0 +1,142 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Tab, TabGroup } from '../../../shared/tab-types' +import type { TerminalTab } from '../../../shared/terminal-tab-types' +import type { AppState } from '@/store/types' +import { createTabsFocusActions } from '../store/slices/tabs/tabs-focus-actions' +import type { TabsSliceGet, TabsSliceSet } from '../store/slices/tabs/tabs-slice-contract' +import { buildActiveSurfacePatch } from '../store/slices/tabs/tabs-surface' + +const mocks = vi.hoisted(() => ({ store: {} as AppState })) + +vi.mock('../store', () => ({ + useAppStore: Object.assign(vi.fn(), { getState: () => mocks.store }) +})) + +import { handleSwitchTerminalTab } from './ipc-tab-switch' + +const WORKTREE_ID = 'wt-1' +const GROUP_ID = 'group-1' +const SESSION_ID = 'sess-1' +const CHAT_UNIFIED_ID = `structured-agent-session-${SESSION_ID}` + +function unifiedTab(overrides: Partial & Pick): Tab { + return { + groupId: GROUP_ID, + worktreeId: WORKTREE_ID, + label: overrides.id, + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0, + ...overrides + } +} + +/** + * The store the app really has with a structured tab focused: raw group state plus the + * active-surface fields the store derives from it. That derivation is what leaves `activeTabId` + * naming a live background terminal, so stubbing it would hide the half under test. + */ +function storeWithStructuredTabActive({ + terminalIds, + lastFocusedTerminalId, + activeGroupTabId = CHAT_UNIFIED_ID +}: { + terminalIds: string[] + lastFocusedTerminalId: string + activeGroupTabId?: string +}): AppState { + const terminalTabs = terminalIds.map((id) => + unifiedTab({ id: `unified-${id}`, entityId: id, contentType: 'terminal' }) + ) + const chatTab = unifiedTab({ + id: CHAT_UNIFIED_ID, + entityId: SESSION_ID, + contentType: 'agent-session' + }) + const groups: TabGroup[] = [ + { + id: GROUP_ID, + worktreeId: WORKTREE_ID, + activeTabId: activeGroupTabId, + tabOrder: [...terminalTabs.map((tab) => tab.id), chatTab.id] + } + ] + const rawState = { + activeBrowserTabIdByWorktree: {}, + activeFileIdByWorktree: {}, + activeGroupIdByWorktree: { [WORKTREE_ID]: GROUP_ID }, + activeTabIdByWorktree: { [WORKTREE_ID]: lastFocusedTerminalId }, + activeTabTypeByWorktree: {}, + activeWorktreeId: WORKTREE_ID, + browserTabsByWorktree: {}, + groupsByWorktree: { [WORKTREE_ID]: groups }, + layoutByWorktree: {}, + openFiles: [], + tabBarOrderByWorktree: {}, + tabsByWorktree: { + [WORKTREE_ID]: terminalIds.map((id) => ({ id, worktreeId: WORKTREE_ID }) as TerminalTab) + }, + unifiedTabsByWorktree: { [WORKTREE_ID]: [...terminalTabs, chatTab] }, + setActiveTab: vi.fn(), + setActiveTabType: vi.fn(), + activateTab: vi.fn(), + setActiveFile: vi.fn(), + setActiveBrowserTab: vi.fn() + } as unknown as AppState + const store = { + ...rawState, + ...buildActiveSurfacePatch(rawState, WORKTREE_ID) + } as AppState + const noopSet = (() => {}) as unknown as TabsSliceSet + store.getActiveTab = createTabsFocusActions(noopSet, (() => store) as TabsSliceGet).getActiveTab + return store +} + +describe('handleSwitchTerminalTab with a structured chat tab active', () => { + beforeEach(() => vi.clearAllMocks()) + + it('leaves activeTabId naming a live background terminal', () => { + // Guards the premise: without a stale id that is really in the terminal list, the tests + // below would pass with the bug present. + mocks.store = storeWithStructuredTabActive({ + terminalIds: ['term-1', 'term-2', 'term-3'], + lastFocusedTerminalId: 'term-2' + }) + expect(mocks.store.activeTabType).toBe('agent-session') + expect(mocks.store.activeTabId).toBe('term-2') + }) + + it('jumps to the first terminal instead of cycling from the background terminal', () => { + mocks.store = storeWithStructuredTabActive({ + terminalIds: ['term-1', 'term-2', 'term-3'], + lastFocusedTerminalId: 'term-2' + }) + expect(handleSwitchTerminalTab(1)).toBe(true) + // Stepping from the stale 'term-2' would land on 'term-3'. + expect(mocks.store.setActiveTab).toHaveBeenCalledWith('term-1') + expect(mocks.store.setActiveTab).not.toHaveBeenCalledWith('term-3') + expect(mocks.store.setActiveTabType).toHaveBeenCalledWith('terminal') + }) + + it('still reaches the sole terminal rather than reading as already focused', () => { + mocks.store = storeWithStructuredTabActive({ + terminalIds: ['term-1'], + lastFocusedTerminalId: 'term-1' + }) + // The stale id matched the only terminal, so the single-terminal guard swallowed the chord. + expect(handleSwitchTerminalTab(1)).toBe(true) + expect(mocks.store.setActiveTab).toHaveBeenCalledWith('term-1') + }) + + it('still cycles normally from a focused terminal tab', () => { + mocks.store = storeWithStructuredTabActive({ + terminalIds: ['term-1', 'term-2', 'term-3'], + lastFocusedTerminalId: 'term-2', + activeGroupTabId: 'unified-term-2' + }) + expect(mocks.store.activeTabType).toBe('terminal') + expect(handleSwitchTerminalTab(1)).toBe(true) + expect(mocks.store.setActiveTab).toHaveBeenCalledWith('term-3') + }) +}) diff --git a/src/renderer/src/hooks/ipc-tab-switch.test.ts b/src/renderer/src/hooks/ipc-tab-switch.test.ts index 0cdc5276539..8cc6fc3afaa 100644 --- a/src/renderer/src/hooks/ipc-tab-switch.test.ts +++ b/src/renderer/src/hooks/ipc-tab-switch.test.ts @@ -15,6 +15,8 @@ vi.mock('@/components/tab-bar/group-tab-order', () => ({ getActiveTabNavOrder: getActiveTabNavOrderMock })) +import { createTabsFocusActions } from '../store/slices/tabs/tabs-focus-actions' +import type { TabsSliceGet, TabsSliceSet } from '../store/slices/tabs/tabs-slice-contract' import { handleSwitchRecentTab, handleSwitchTab, @@ -54,10 +56,11 @@ type MockStore = { setActiveBrowserTab: ReturnType activateTab: ReturnType setActiveTabType: ReturnType + getActiveTab: (worktreeId: string) => unknown } function makeStore(activeTabType: ActiveTabType, overrides: Partial = {}): MockStore { - return { + const store: MockStore = { activeWorktreeId: 'wt-1', activeTabType, activeTabId: 'term-1', @@ -72,8 +75,16 @@ function makeStore(activeTabType: ActiveTabType, overrides: Partial = setActiveBrowserTab: vi.fn(), activateTab: vi.fn(), setActiveTabType: vi.fn(), + getActiveTab: () => null, ...overrides } + // Why the real resolver: the group-scoped active tab is what the code under test reads, so a + // hand-written stub here would decide the answer instead of exercising it. + store.getActiveTab = createTabsFocusActions( + (() => {}) as unknown as TabsSliceSet, + (() => store) as unknown as TabsSliceGet + ).getActiveTab + return store } describe('handleSwitchTerminalTab', () => { diff --git a/src/renderer/src/hooks/ipc-tab-switch.ts b/src/renderer/src/hooks/ipc-tab-switch.ts index e88f9070703..2fee76386c2 100644 --- a/src/renderer/src/hooks/ipc-tab-switch.ts +++ b/src/renderer/src/hooks/ipc-tab-switch.ts @@ -343,13 +343,18 @@ export function handleSwitchTerminalTab(direction: number): boolean { if (terminalTabs.length === 0) { return false } + // Why: this list is pre-filtered to terminals, so the index search below has no type check to + // reject a stale terminal id — a structured tab must resolve to its own entity or the chord + // cycles from whichever terminal was last active. + const activeTab = store.getActiveTab(worktreeId) const currentId = getActiveEntityIdForTabType( store.activeTabType, store.activeTabId, store.activeFileId, - store.activeBrowserTabId + store.activeBrowserTabId, + activeTab?.contentType === 'agent-session' ? activeTab.entityId : null ) - // Why: when an editor/browser tab is active, jump to the first terminal on + // Why: when an editor/browser/structured tab is active, jump to the first terminal on // forward navigation instead of skipping to index 1. const idx = terminalTabs.findIndex((t) => t.id === currentId) // Why: only no-op when the sole terminal is already focused. With one terminal diff --git a/src/renderer/src/runtime/web-session-tabs-sync/mirrored-agent-tab-label.test.ts b/src/renderer/src/runtime/web-session-tabs-sync/mirrored-agent-tab-label.test.ts new file mode 100644 index 00000000000..7d5ef3c25f3 --- /dev/null +++ b/src/renderer/src/runtime/web-session-tabs-sync/mirrored-agent-tab-label.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types' +import type { Tab } from '../../../../shared/tab-types' +import { buildMirroredAgentTabs } from './terminal-surfaces' + +const WORKTREE = 'repo-1::worktree-1' +const GROUP = 'group-1' + +function snapshotWith(agent: 'claude' | 'codex', title: string): RuntimeMobileSessionTabsResult { + return { + worktree: WORKTREE, + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + activeGroupId: GROUP, + activeTabId: null, + activeTabType: null, + tabs: [ + { + type: 'agent-session', + id: 'host-tab-1', + title, + sessionId: `${agent}-1`, + agent, + isActive: false + } + ] + } as RuntimeMobileSessionTabsResult +} + +function build( + snapshot: RuntimeMobileSessionTabsResult, + currentUnifiedTabs: readonly Tab[] = [] +): Tab { + const [mirrored] = buildMirroredAgentTabs( + snapshot, + new Map(), + GROUP, + 0, + currentUnifiedTabs, + 1_000 + ) + return mirrored.unifiedTab +} + +describe('buildMirroredAgentTabs', () => { + it('falls back to the agent-specific placeholder when the host publishes no title', () => { + expect(build(snapshotWith('claude', '')).label).toBe('Claude Chat') + expect(build(snapshotWith('codex', ' ')).label).toBe('Codex Chat') + }) + + it('prefers the host title over the placeholder', () => { + expect(build(snapshotWith('claude', 'Flaky retry test')).label).toBe('Flaky retry test') + }) + + it('keeps a manual rename across host snapshots', () => { + const snapshot = snapshotWith('codex', 'Codex Chat') + const renamed = build(snapshot) + const existing: Tab = { ...renamed, customLabel: 'My rename' } + expect(build(snapshot, [existing]).customLabel).toBe('My rename') + }) + + it('leaves customLabel null when the tab was never renamed', () => { + // Guard: assert the row is actually built, so this cannot pass on an empty + // result the way a bare null-check would. + const tab = build(snapshotWith('codex', 'Codex Chat')) + expect(tab.label).toBe('Codex Chat') + expect(tab.customLabel).toBeNull() + }) + + it('degrades to the placeholder when the host violates the string contract', () => { + const snapshot = snapshotWith('claude', 'Named') + // The wire type says `string`, but a host clearing a name can send null. + ;(snapshot.tabs[0] as { title: unknown }).title = null + expect(() => build(snapshot)).not.toThrow() + expect(build(snapshot).label).toBe('Claude Chat') + }) + + it('names an agent this build does not know after itself, not Codex', () => { + const snapshot = snapshotWith('codex', '') + // Cast: the wire union is claude|codex today, but Tab.agentSessionAgent is + // the open AgentType, so a future agent can reach this label. + ;(snapshot.tabs[0] as { agent: string }).agent = 'gemini' + expect(build(snapshot).label).toBe('Gemini Chat') + }) +}) diff --git a/src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts b/src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts index 3c43eec8d5c..50a1558533c 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts @@ -3,6 +3,7 @@ import type { RuntimeMobileSessionAgentTab } from '../../../../shared/runtime-types' import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/terminal-tab-types' +import { defaultAgentChatLabel } from '../../../../shared/agent-session-chat-label' import { sanitizeTerminalLayoutPaneTitlesForLabels } from '@/lib/terminal-pane-title-sanitization' import { resolveTerminalLayoutRoot } from '../remote-terminal-layout-resolution' import { getRemoteRuntimePtyEnvironmentId } from '../runtime-terminal-stream' @@ -113,8 +114,12 @@ export function buildMirroredAgentTabs( worktreeId: snapshot.worktree, contentType: 'agent-session', agentSessionAgent: tab.agent, - label: tab.title.trim() || 'Codex Chat', - customLabel: null, + // Why: `title` is wire data typed `string`; a host that violates that must + // degrade to the placeholder, not throw inside the snapshot patch. + label: tab.title?.trim() || defaultAgentChatLabel(tab.agent), + // Why: a manual rename lives only on the client; re-nulling it here made + // every host snapshot silently discard the user's title. + customLabel: existing?.customLabel ?? null, color: tab.color !== undefined ? tab.color : (existing?.color ?? null), sortOrder: sortOffset + index, createdAt: existing?.createdAt ?? now + sortOffset + index, diff --git a/src/renderer/src/store/terminals/renamable-unified-tab.ts b/src/renderer/src/store/terminals/renamable-unified-tab.ts new file mode 100644 index 00000000000..74d3eee0234 --- /dev/null +++ b/src/renderer/src/store/terminals/renamable-unified-tab.ts @@ -0,0 +1,15 @@ +import type { Tab } from '../../../../shared/tab-types' + +/** Resolves the unified tab a per-tab presentation action (rename, color) targets. + * Terminal tabs are addressed by their backing terminal's entityId; a structured + * chat has no TerminalTab record and is addressed by the unified tab id itself. */ +export function findRenamableUnifiedTab( + unifiedTabsByWorktree: Record, + tabId: string +): Tab | undefined { + const unified = Object.values(unifiedTabsByWorktree).flat() + return ( + unified.find((entry) => entry.contentType === 'terminal' && entry.entityId === tabId) ?? + unified.find((entry) => entry.contentType === 'agent-session' && entry.id === tabId) + ) +} diff --git a/src/renderer/src/store/terminals/structured-chat-tab-rename.test.ts b/src/renderer/src/store/terminals/structured-chat-tab-rename.test.ts new file mode 100644 index 00000000000..5d1e6343f74 --- /dev/null +++ b/src/renderer/src/store/terminals/structured-chat-tab-rename.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, it, vi } from 'vitest' +import type { Tab } from '../../../../shared/tab-types' +import { createTestStore, makeWorktree, seedStore } from '../slices/store-test-helpers' + +vi.mock('sonner', () => ({ + toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } +})) + +const WORKTREE = 'local-repo::/tmp/app' +const STRUCTURED_TAB_ID = 'structured-agent-session-codex-1' + +function structuredTab(): Tab { + return { + id: STRUCTURED_TAB_ID, + entityId: 'codex-1', + groupId: 'group-1', + worktreeId: WORKTREE, + contentType: 'agent-session', + agentSessionAgent: 'codex', + label: 'Codex Chat', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 1 + } +} + +const TERMINAL_TAB_ID = 'terminal-1' +const TERMINAL_UNIFIED_ID = 'unified-terminal-1' + +function terminalTab(): Tab { + return { + id: TERMINAL_UNIFIED_ID, + entityId: TERMINAL_TAB_ID, + groupId: 'group-1', + worktreeId: WORKTREE, + contentType: 'terminal', + label: 'Terminal', + customLabel: null, + color: null, + sortOrder: 1, + createdAt: 2 + } +} + +function storeWithStructuredTab(): ReturnType { + const store = createTestStore() + seedStore(store, { + repos: [{ id: 'local-repo', path: '/tmp/app', name: 'app' }] as never, + worktreesByRepo: { + 'local-repo': [makeWorktree({ id: WORKTREE, repoId: 'local-repo', path: '/tmp/app' })] + }, + unifiedTabsByWorktree: { [WORKTREE]: [structuredTab()] } + }) + return store +} + +function labelOf(store: ReturnType): string | null | undefined { + return store + .getState() + .unifiedTabsByWorktree[WORKTREE]?.find((tab) => tab.id === STRUCTURED_TAB_ID)?.customLabel +} + +function colorOf(store: ReturnType): string | null | undefined { + return store + .getState() + .unifiedTabsByWorktree[WORKTREE]?.find((tab) => tab.id === STRUCTURED_TAB_ID)?.color +} + +describe('renaming a terminal tab still resolves', () => { + it('routes a terminal rename through its entityId, not the unified id', () => { + const store = createTestStore() + seedStore(store, { + repos: [{ id: 'local-repo', path: '/tmp/app', name: 'app' }] as never, + worktreesByRepo: { + 'local-repo': [makeWorktree({ id: WORKTREE, repoId: 'local-repo', path: '/tmp/app' })] + }, + unifiedTabsByWorktree: { [WORKTREE]: [terminalTab(), structuredTab()] } + }) + + // Keyed by the TERMINAL's entityId — the structured tab must not absorb it. + store.getState().setTabCustomTitle(TERMINAL_TAB_ID, 'Build logs') + + const tabs = store.getState().unifiedTabsByWorktree[WORKTREE] ?? [] + expect(tabs.find((t) => t.id === TERMINAL_UNIFIED_ID)?.customLabel).toBe('Build logs') + expect(tabs.find((t) => t.id === STRUCTURED_TAB_ID)?.customLabel).toBeNull() + }) +}) + +describe('recoloring a structured chat tab', () => { + it('writes the color onto the agent-session tab', () => { + const store = storeWithStructuredTab() + store.getState().setTabColor(STRUCTURED_TAB_ID, 'red') + expect(colorOf(store)).toBe('red') + }) +}) + +describe('renaming a structured chat tab', () => { + it('writes the custom label onto the agent-session tab', () => { + const store = storeWithStructuredTab() + store.getState().setTabCustomTitle(STRUCTURED_TAB_ID, 'Flaky retry test') + expect(labelOf(store)).toBe('Flaky retry test') + }) + + it('clears the custom label when the rename is emptied', () => { + const store = storeWithStructuredTab() + store.getState().setTabCustomTitle(STRUCTURED_TAB_ID, 'Flaky retry test') + // Guard: without the intermediate assertion this case passes on a rename + // that never wrote anything, since the label starts out null too. + expect(labelOf(store)).toBe('Flaky retry test') + store.getState().setTabCustomTitle(STRUCTURED_TAB_ID, null) + expect(labelOf(store)).toBeNull() + }) +}) diff --git a/src/renderer/src/store/terminals/terminal-tab-attention.ts b/src/renderer/src/store/terminals/terminal-tab-attention.ts index 062043b546e..3ba84961763 100644 --- a/src/renderer/src/store/terminals/terminal-tab-attention.ts +++ b/src/renderer/src/store/terminals/terminal-tab-attention.ts @@ -1,6 +1,7 @@ import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph' import { resolveTerminalWorktreeRoute } from '@/lib/terminal-worktree-route' import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state' +import { findRenamableUnifiedTab } from './renamable-unified-tab' export function createTerminalTabAttentionActions( set: TerminalStoreSet, @@ -87,9 +88,7 @@ export function createTerminalTabAttentionActions( scheduleRuntimeGraphSync() return { tabsByWorktree: next } }) - const item = Object.values(get().unifiedTabsByWorktree) - .flat() - .find((entry) => entry.contentType === 'terminal' && entry.entityId === tabId) + const item = findRenamableUnifiedTab(get().unifiedTabsByWorktree, tabId) if (item) { get().setTabCustomLabel(item.id, title, opts) } @@ -102,9 +101,7 @@ export function createTerminalTabAttentionActions( } return { tabsByWorktree: next } }) - const item = Object.values(get().unifiedTabsByWorktree) - .flat() - .find((entry) => entry.contentType === 'terminal' && entry.entityId === tabId) + const item = findRenamableUnifiedTab(get().unifiedTabsByWorktree, tabId) if (item) { get().setUnifiedTabColor(item.id, color) // Why: tab color is host-authoritative for remote-server tabs; mirror it so it persists instead of reverting on the next snapshot. diff --git a/src/shared/agent-session-chat-label.ts b/src/shared/agent-session-chat-label.ts new file mode 100644 index 00000000000..131285b0626 --- /dev/null +++ b/src/shared/agent-session-chat-label.ts @@ -0,0 +1,9 @@ +import type { AgentType } from './agent-status-types' +import { formatAgentTypeLabel } from './agent-type-label' + +/** Placeholder tab label for a structured chat that has no conversation name yet. + * Routed through the shared agent-name table so an agent this build does not + * know reads as itself rather than silently as Codex. */ +export function defaultAgentChatLabel(agent: AgentType | null | undefined): string { + return `${formatAgentTypeLabel(agent)} Chat` +} From 0252fe5c36da38e02f2f950bccecf9cda2fd029c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 7 Sep 2026 09:38:16 -0700 Subject: [PATCH 22/37] feat(native-chat): show Codex subagent activity instead of opcode rows (#18773) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(native-chat): show Codex subagent activity instead of opcode rows Codex spawns subagents and reports their lifecycle, but Orca rendered only gray `codex · item:subAgentActivity` opcode rows. Build the real display: one summary row per spawn group with a live working count and token usage. State is accumulated from `subAgentActivity.kind` alone. A live probe against app-server 0.152.1 showed `agentsStates` arrives empty even in a real subagent run, and that every activity item is delivered twice (item/started and item/completed), so every transition is idempotent and terminal states latch. Children never receive `thread/started`, so there is no nickname, role, or depth to read; the row labels from the trailing segment of `agentPath`. Two sweeps keep a row from claiming work forever: the parent turn's terminal event settles still-running children, and session start marks a pre-restart roster unverifiable rather than exited, since Codex resume replays no non-message items and no event can ever settle them. The roster rides a new NativeChatBlock variant paired with a plain-text twin. A journal item kind could not be used: that union is closed, and an unknown kind parses as malformed, which is the corrupt-journal class that can hide the chat tab. Block types are explicitly admissible when unknown, so an older client drops the block and renders the sentence. MessageRow moves out of NativeChatMessageList to keep both files under the max-lines budget without a disable. * feat(native-chat): give the subagent summary row its bot glyph The row led with a glyph that swapped on state — a check once every child completed, a group icon otherwise — so a group appeared to change identity the moment it settled. Per the approved mock, the glyph names the category and never moves: state is carried by the status dot and the tone of the words beside it. Use lucide `bot`, the same glyph the individual `subAgentActivity` rows take in the eight-category vocabulary, so the summary reads as their parent. Slot and glyph are the mock's 16px/14px, muted by default, and the svg is `aria-hidden` — the headline is what a screen reader announces, so the icon never stands alone. * fix(native-chat): correct the Codex subagent roster's build, journal write, and failure reporting * Restore the exhaustive block handling that adding `subagent-group` to `NativeChatBlock` broke. `formatWorkerTranscriptMessage` and `boundBlock` both fell through to `image-ref` field access, so `tsc -p` failed for the CLI and node projects and `build:cli` could not emit. Both now guard on `image-ref` explicitly and give the roster block its own branch. * Stop the roster's publish from evicting its own append. The sink queue coalesces by `coalescingKey` alone with no op-kind check, so passing the append's key to `tryPublish` spliced the queued append out and the row never reached the journal — permanently, since `lastSerialized` was already set. `tryPublish()` now takes no argument, matching every other call site. The regression test's fake sink honours the key, which the previous fake did not. * Keep `collabAgentToolCall` substantive. Only the MultiAgentV2 path emits `subAgentActivity`, so a V1 turn has no roster row; suppressing its collab tool calls too would have left a V1 fan-out showing nothing at all. * Surface a settled failure while siblings still work. The summary now reports the worst adverse outcome independently of the group verdict, so the row shows `3 working +1 failed` with a failed-coloured dot instead of a neutral pulsing dot. The plain-text twin names it too. * Treat `/morpheus` as a child. Only `/root` is the turn itself; the old segment-count test silently dropped a valid single-segment agent. * Refresh token-usage recency on update so an active thread is not evicted as the oldest entry, and scope the `agentsStates` comment to the V2 path. * fix(native-chat): stop the subagent roster announcing a new duration every second The roster row is an `aria-live="polite"` region and it contains the elapsed clock, which reticks once a second for as long as the fan-out runs. A screen reader therefore reads out a fresh duration every second, burying the state changes the live region exists to report — the headline, the verdict, and the `+1 failed` alert. No other live region in the transcript does this. `NativeChatToolRun`'s live button holds only the active tool label, and in `NativeChatWorkingStatus` the variant that shows a duration is precisely the one with no `aria-live`. Hide the clock from the accessibility tree only while it is moving. Once the group settles the duration is fixed, so it stays readable and costs no announcements. * fix(native-chat): retry a refused roster publish, and stop two wrong readings Four defects from a third review pass over the Codex subagent roster. `write()` set `lastSerialized` before the append and rolled it back only when the APPEND was refused. A refused PUBLISH left it set, so an identical replay short-circuited and the revision was never published again. The repo's own pattern is the opposite: `codex-structured-item-streams.ts` advances `checkpointLengths` only once the append AND the publish are both accepted. Roll back on either half. That alone did not cover the sweep, which is the LAST event a group ever gets: its `changed` guard skips the write on a retry because every child has already latched, stranding the settled roster's final revision. Write when the previous attempt was refused part-way, too. `formatWorkerTranscriptMessage` read `block.agents` as its exhaustive fallback. The journal schema deliberately admits block types this build does not know and `client.call` casts the RPC result instead of validating it, so a newer remote host's block reached that line and threw `agents is not iterable`, taking down the whole `worker read`. It printed a harmless `[image omitted]` before. Match `subagent-group` explicitly and degrade the unknown case. The elapsed clock measured to `now` whenever no child carried a terminal timestamp. That is exactly the roster restored from the journal after the host died: the reconciler latches `unverifiable` without a `settledAt`, so a child that ran four seconds reported the time since the crash as its run length, on a row that is not even counting. Show no duration when none is known. Also restores package.json to origin/main: the merge had deleted one of main's two duplicate `bench:terminal-partial-escape-tail` keys. Behaviour-preserving (JSON is last-wins and the deleted line was the dead one), but unrelated to this PR and better left to its own change. No gate rejects duplicate JSON keys. The new refusal tests also cover the append-side rollback, which had none. * fix(native-chat): stop the subagent roster vanishing from every settled turn `NativeChatToolRun` bailed out for a completed turn whose activity disclosure is collapsed before it reached the branch that draws a roster-only run. That guard exists to push TOOL activity behind the turn-status disclosure, and it fires on exactly the shape a spawn group has: a roster message carries no tool blocks, so `selectActiveToolCall` returns null and `isSettled` is true, while the list passes `expandOverride={expandedTurnIds.has(turnKey)}` — false until the reader opens that turn — and `activeTurnIsWorking={false}`. That is the default state of every finished turn in the transcript, so the one compact row this feature exists to leave behind ("Ran 3 subagents") disappeared the moment its turn ended. Worse, `MessageRow` counts a spawn group as renderable specifically so the row survives, then rendered a wrapper around a component that returned null — the empty ghost bubble its own guard is written to prevent. Order the roster branch before the disclosure guard. A roster has no tool activity to hide, and the guard's reasoning ("a failed child command looked like the whole response was still running") does not reach it. Runs that do carry tool blocks still fall through to the guard unchanged, and in practice a roster never shares a message with them: it is its own `role: 'system'` journal row and `isToolOnlyMessage` is false for it, so `foldToolMessages` never merges tool blocks into it. Also drop childless groups when building the rows, so `subagentRows.length` stays an honest test of "something will draw" — the roster-only branch returns a margin-bearing wrapper on the strength of it, and a group with no children renders null. Both tests fail with their fix reverted; the existing NativeChatToolRun suite still passes, so the completed-turn disclosure behaviour is unchanged. * test(native-chat): cover the subagent roster at the message-list level Every defect this feature has shipped so far lived in the assembly between rows, and the row-level suites kept passing through all of them. Loop 4's regression — a settled roster swallowed by the completed-turn disclosure — was found by reading the code, not by a test, and an independent visual-proof run observed the same symptom in the real UI and routed around it rather than reporting it. `NativeChatToolRun` rendered alone is handed `expandOverride` and `activeTurnIsWorking` by the test author, so it agrees with whatever the caller was assumed to pass. Drive the real component instead. The roster is its own `role: 'system'` journal row carrying the producer's two blocks (structured + plain-text twin), so what reaches the DOM depends on `foldToolMessages`, the turn-key mapping and the disclosure state `NativeChatMessageList` owns — none of which a row test exercises. Three cases, on one assembled transcript that holds tool calls AND a roster: - a settled turn with activity collapsed, the resting state of the whole transcript, still shows the row (fails with loop 4's reorder reverted); - tool activity stays behind that disclosure and appears only on expand, and expanding draws no second roster (fails with the guard removed); - a working turn reads as a live spawn. The first also pins that the plain-text twin is dropped rather than printed beside the row it stands in for. Timestamps are explicit and ascending: the list re-sorts by (timestamp, id), so rows sharing a millisecond tie-break alphabetically and the user turn can sort last, stranding the roster outside its own turn and reconciling live children to `unverifiable`. No production code changed. * fix(native-chat): make "counts as renderable" and "actually draws" agree for a spawn group `MessageRow` counts any `subagent-group` block as renderable, but `NativeChatSubagentRun` renders null for a childless roster. A group with `agents: []` therefore mounted a row that drew nothing — an empty div that still costs the transcript one `gap-5` slot. The Codex producer never writes one (every `write()` call site operates on a group that already holds an entry), but the block schema admits `agents: []` with no `.min(1)`, and the wire is where such a shape would arrive. Narrow `subagentGroupBlocks` — whose only production caller IS that renderable check — to the groups that will draw, behind a named `isRenderableSubagentGroup` that `NativeChatToolRun` now shares in place of its own copy of the predicate, so the two guards cannot drift apart again. A childless group carrying its plain-text twin now prints the twin, which is what the twin is for; a bare one skips the row entirely. Also correct four comments that had stopped describing the code: - the roster header called `agentsStates` "always empty", contradicting the probe note in `codex-subagent-activity.ts` — it is empty on the MultiAgentV2 path that emits these items, and the V1 path does populate it; - `tokensByThread` was documented "retained UNCONDITIONALLY" while `handleTokenUsage` LRU-caps it 65 lines below; - the sweep is not "the LAST event a group ever gets": neither `settleTurn` nor `settleSession` removes the group, so a later `thread/tokenUsage/updated` naming a swept child still writes it. The retry condition is right; only its stated reason was wrong; - the `subAgentActivity` classification is not reached "for every event — and every one of them arrives twice". `handleSubagentItem` intercepts those items before `items.handle`, so the live path never consults the catalog; `restoreThread` replays them straight through, and is the real consumer. Comment-only apart from the childless-group guard. * fix(cli): stop `worker read` printing the subagent roster sentence twice The producer ALWAYS writes a roster block beside a plain-text twin carrying the same sentence, for clients that cannot draw the block. The renderer honours that contract from one side — it draws the block and drops the twin. The CLI honoured neither side: it printed the twin as prose AND rendered the block as `[subagents] `, so a real roster message read [system] Ran 2 subagents (1 failed) [subagents] Ran 2 subagents (1 failed) Take the mirror of the renderer's rule, which is the cleaner half for a text client: the twin IS the sentence, so print it and drop the block it stands in for. A block that arrives WITHOUT its twin — a shape the wire admits and no producer writes — still stands in for itself, because dropping it unconditionally would lose the roster entirely. Either way the sentence prints exactly once, off the same `subagentGroupFallbackText` helper both sides use. Unreachable through `readWorkerTranscript` today, whose provider rollout decoder never emits a `subagent-group` block — but the formatter is the CLI's contract for any transcript source, and the shape is already producible. The test pinned a TWIN-LESS group, a body `codexSubagentGroupBody` never writes: it asserted the exact double-print this fixes was correct output, and would have blessed either behaviour. Rebuild the fixture as the producer's real two-block row, with the sentence taken from the shared helper rather than hardcoded so it cannot drift, and assert the sentence appears exactly once. The twin-less shape keeps a test of its own, labelled as the wire-only fallback it is. Also record why `settleTurn` keys on the RAW `turnId` while `groupFor` remaps off-primary activity onto the primary's active turn. The asymmetry is load-bearing, not an oversight: were `settleTurn` to remap, a child thread ending its own turn would sweep the parent group and settle every still-working sibling to `unverifiable`. The lookup missing is the intended no-op. * fix(native-chat): add the subagent roster's localization keys and narrow its twin filters The roster row called 16 `components.native-chat.subagents.*` keys that were never added to the catalog, failing the localization gate. Synced en.json; the English strings are the component's own inline fallbacks, so nothing renders differently. Also tightens the twin/block handoff on both readers. The renderer dropped every text block once a roster was present, which is safe only because Codex writes a roster as its own message — the block is provider-agnostic, so a lane folding prose in beside one would have lost it on desktop while mobile kept it. And both readers decided "the twin is already printing" by recomputing the sentence and comparing bytes, which a roster from a newer build never matches: its unknown state normalizes to `unverifiable` here, so the CLI printed the roster twice with two different verdicts. Both now recognize a twin by shape. * test(native-chat): pin the roster twin recognizer against prose Both readers use it to decide the twin is already printing, so a false positive eats a message's real prose and a false negative prints the roster twice. * docs(codex): restore the roster's evictionated trigger to its KNOWN LIMITATION The previous rewrite dropped both triggers the old comment named and kept only the restart one, but eviction is the reachable half: `groupFor` caps `groups` at MAX_CODEX_SUBAGENT_GROUPS and drops the oldest-INSERTED entry (it returns an existing group without re-inserting, so this is not LRU), which can evict a still-live group in-process. The row identity is keyed on the group id alone, so the next activity item rebuilds that row from one child — the same N-to-1 rewrite, with no restart, and with the sweep skipped so the children never latch `unverifiable`. Also softens "every real turn id is freshly minted" to the provider assumption it is: turn ids are read verbatim off provider frames and nothing in this repo mints or asserts them. * docs(codex): justify the subagent wire notes from the live probe alone The roster and disposition comments explained themselves in terms of a provider-internal path taxonomy rather than anything this repo can observe. Restate them from the evidence Orca actually has: the live app-server probe saw `agentsStates` arrive empty, so nothing reads it; and `collabAgentToolCall` stays substantive because nothing guarantees a session reports subagent work as `subAgentActivity` at all — one that only emits the collab tool call gets no roster row, and suppressing that too would leave its fan-out blank. Same behaviour, same tests; comments and one test name only. * fix(native-chat): stop the roster's durable twin from claiming live subagents The spawn-group row is written once and revised in place, but the row itself is durable and replayed on every reconnect. Its plain-text twin — the only thing a client that cannot draw the block ever sees — froze a live count into that row: `Kicked off 4 subagents — 2 working`. The desktop renderer never shows it, and reconciles the block's `working` to `unverifiable` outside the live turn. A text-only reader does neither. When the writing process dies mid-flight the turn-end sweep never runs, so the sentence keeps asserting two running children forever, with nothing left that could re-check them. That is the collapse `docs/reference/ssh-execution-boundary.md` forbids: loss of contact reported as a live state. Fix it at the source rather than per client: the durable sentence now states only what survives its process — that the group was spawned, plus whatever outcome had latched. `Kicked off` vs `Ran` stays, because it reports whether an outcome was recorded at write time; saying `Ran` while children were in flight would assert they exited, the same error inverted. The adverse count stays so a failing fan-out still reads as failing. Reconciliation stays in the renderer, where the block still needs it. The twin recognizer keeps matching the legacy `— N working` shape: journals already hold those sentences and their rows replay forever, so dropping the branch would print every one of them twice, once as the block and once as prose the reader meant to drop. Also align the two functions that read `agentPath`. The root check compared the raw string while the label normalized separators, so `/root/` was both the turn itself and a child of it — a phantom row labelled `root` inflating the group by one. Compare normalized segments instead, keeping `/morpheus` a child. And a trailing segment with nothing visible in it survives the empty-segment filter and would draw a nameless row, so it now reads as no label and falls back to the placeholder. * fix(codex): key the subagent label collision ordinal on what the row draws `codexSubagentLabel` tested the trailing segment trimmed but returned it untrimmed, and `claimLabel` keys its collision ordinal on that string. Two children at `/root/read` and `/root/ read ` therefore both drew as `read` with no ordinal — the one thing the ordinal exists to prevent. Return the trimmed segment so labels that render identically collide. Also correct the legacy-clause note on the twin recognizer. It claimed shipped journals hold the old `— N working` sentence; the feature is unreleased, so the only journals holding one are dev worktrees of this branch. The branch still earns its place — those rows replay too, and it adds no false-positive surface the bare shape does not already carry — but the stated reason was wrong. * test(native-chat): retire the subagent-visibility guards now the roster renders Two tests from the sibling item-coverage PR asserted that subagent items stay on the generic gray row, explicitly gated on "until a real renderer exists". This branch is that renderer, so both guards fire on merge — the handoff they were written to mark rather than a regression. They now pin the other side of it: subAgentActivity is suppressed because the spawn-group roster renders it, and collabAgentToolCall deliberately stays visible, since nothing guarantees a session reports subagent work as subAgentActivity at all. Git merged both files without conflict; only running the suite surfaced this. * fix(native-chat): let a subagent swept at turn end still report what it did The turn-end sweep marks still-running children `unverifiable`, and the producer latched on any state that was not `working` — so `unverifiable` latched too. A subagent that outlived its turn then reported `completed`, the latch refused it, and a child that finished successfully read as one we never saw finish, permanently. One predicate was doing two jobs. `isTerminalSubagentState` is right for counting — `unverifiable` is not working — and wrong for latching, because `unverifiable` records that we stopped being able to see the child, not what it did. Split them: a child's own verdict latches, the sweep's guess does not. The reverse stays refused. Nothing returns to `working` once we have given up on it, so a straggler progress tick cannot re-light a settled row. Neither the latch nor the sweep was wrong alone, and both were tested; the defect lived only in their interaction, and only when a subagent outlives its turn — which the probe that drove this design never produced, because the parent it captured waited on its child. * fix: drop the @pnpm/exe lockfile drift a merge staged `git add -A` swept up the pnpm-lock.yaml mutation that every pnpm invocation leaves in this repo. Nineteen lines, thirteen of them @pnpm/exe, and it fails sixteen unrelated CI checks — native smoke, typecheck, packaging, xterm patch sync — none of which name the lockfile. * fix(native-chat): restore the item fall-through an inline dropped Inlining the subagent routing helper lost its null check: the roster returning null means it did not claim the item, and the translator must keep looking. Returning unconditionally once any thread item parsed swallowed every ordinary item — twelve settlement tests, none of them about subagents. * fix(orchestration): rebind the subagent block arm to the renamed bound state Main renamed clipMetadata's second parameter from a warnings set to a TranscriptBoundState. The subagent-group arm still passed `warnings`, and git merged both sides without a conflict because the lines never overlapped — the rename and the new arm are in different hunks. Typecheck was the only thing that could catch it, and did. * fix(codex): publish the turn tail for a subagent item the roster claims Main's #19055 added a `subAgentActivity` arm to the provider activity table, which is reached only through `publishActivity`. The roster's admission returned above that call, so every `subAgentActivity` item bypassed it and a fan-out that reports nothing else left the turn tail stuck on the previous frame's text. `publishActivity` already no-ops on a refused admission and on a non-primary thread, so routing the roster's admission through it is safe. Also corrects a docstring the frames extraction copy-pasted onto `settleOversizedNotification`. * fix(native-chat): bound the subagent roster on every boundary that carries it The spawn-group arm was the one collection in the worker-transcript payload with no cap, and the one block type mobile's `sanitizeBlock` forwarded verbatim. The producer's `MAX_CODEX_SUBAGENTS_PER_GROUP` does not reach either boundary: the journal schema declares no maximum on `agents`, and a remote host may run a build with a different cap. Both transports now cap the roster and bound `id`, `label` and the open `state` string; `label` and `id` also take the standard inline bound on the journal write path, where every other provider string already does. A token count is now persisted onto its entry at write time. `write` rebuilt `tokens` from the LRU-capped thread map on every write, so an eviction silently retracted a count the durable row had already shown. Adds the first coverage of the three roster caps, including the group eviction that rewrites a row from N children down to one. * fix(native-chat): keep the roster drawn beside tool calls and its clock honest The roster-only escape is keyed on `blocks.length === 0`, so a spawn group sharing its message with tool-call blocks fell through to the settled-turn guard, which returned bare null and took the roster with it — the exact regression the escape above was written to avoid, after the message row had already counted the group as renderable. Unreachable for Codex today; the block type is deliberately provider-agnostic, so it is live for the Claude lane. The elapsed clock also froze at a sibling's timestamp on a partial sweep: in a group where one child completed and another is unaccounted for, the ended turn left `working === 0` with the completed child's `settledAt`, and the row showed that child's duration as the group's run length. No clock is drawn while any child is `unverifiable` with no terminal timestamp. * perf(native-chat): bound the roster's provider strings without digesting them `boundInlineText` computes a sha256 and a Buffer BEFORE it checks the length, so the roster paid two digests per child on every write even when nothing was truncated — and `write()` runs on every claimed activity item (each delivered twice) and again from `handleTokenUsage`, which streams. A same-process A/B over a 64-child group: 76.5 us/write before, 2.0 us/write after (plain, unbounded row is 1.2 us). The cap changes with the mechanism. 16 KB is the tool-output bound; both readers of this row already clip the same fields to 512, so the producer was admitting ~2 MB per durable roster row for consumers to throw ~97% of away. One `MAX_SUBAGENT_FIELD_CHARS` now serves the producer and both readers, and the marker is an ellipsis rather than the tool-output truncation sentence — `id` is the roster key and the renderer's React key. Also raises the orchestration arm's per-group bound from 20 to the producer's 64, matching the mobile arm: a 21-64 child group is routinely producible here, so that arm clipped children and warned while its sibling clipped none. The slice and warning stay as the transport's own defence against a remote host with a larger cap. * fix(orchestration): suppress one roster block per twin, not all of them `hasTwin` was a single boolean over the whole message, so a message carrying two `subagent-group` blocks and one plain-text twin printed one sentence and dropped the second roster with no marker. Count the twins and claim one per group instead. Not reachable from this branch's producer, which writes one group per journal item, but the surrounding reasoning is explicitly about wire shapes the producer never writes and this is the adjacent one it missed. * fix(native-chat): loop-3 fixes to the Codex subagent worklog Five defects loop 2's own fixes introduced. Twin claiming was order-blind: the count-based claim silenced whichever roster block came first, so a lone twin belonging to a LATER group erased an earlier group's roster and printed the later sentence twice. Exact-text claims are now settled for every group before any leftover twin is claimed by position; the positional fallback stays for a newer build's frozen twin, which can never equal a recomputed sentence. `boundSubagentField` sliced UTF-16 units and could leave a lone high surrogate in a durable row, and the clip removed exactly the tail that told two children apart — `id` is the renderer's React key and `claimLabel` writes its repeat ordinal at the end. It now backs off a split pair and reserves the child index inside the bound, so both readers' re-clip cannot cut the disambiguator off again. `MAX_SUBAGENT_FIELD_CHARS`'s doc claimed a `groupId` bound the producer never applies; the doc now says so and why. The worker-transcript metadata cap is a separate literal again: it governs message ids, turn ids, tool-call names and image urls, so a roster-motivated change must not move it. * fix(native-chat): never infer a lost subagent from a turn boundary QA drove a real Codex session with three live `spawn_agent` children and sent a mid-turn correction. The roster row immediately read "Ran 3 subagents / 3 unverifiable" with no clock, while all three were still running — they reported `completed` 57-87s after that turn ended. Both sites rested on the same false premise: that a turn ending means no event will ever settle a child. Children outlive their turn and keep reporting into the same group. - Renderer: drop `reconcileSubagentRoster`. Nothing plumbed to the component distinguishes a row written by a dead host from a turn that merely ended — journal render items carry no epoch, and a new epoch deletes the rows of the one it supersedes — so the row now draws the state the journal recorded. Under-claiming beats over-claiming. - Main: stop sweeping on `turn/completed`. That sweep wrote `unverifiable` into the DURABLE journal, which mobile reads with no reconciliation. `turn/completed` is Codex's only turn-end notification, so an abort cannot be told apart from a clean finish; the safe default is not to sweep. `settleSession` — the provider actually being gone — is unchanged and is now the only sweep. `unverifiable` stays non-latching so a late verdict still lands. * test(native-chat): pin the roster at the seam the QA defect came from The mid-turn correction opens a new turn, so the fan-out's row stops being the current turn and the list hands the roster `activeTurnIsWorking={false}`. Asserted through the list, not the component, because that prop is what carried the wrong claim. * fix(native-chat): settle a roster the dying host never got to sweep `settleSession` only fires when the provider goes away while this process is alive. If the host itself dies, nothing sweeps and nothing reconciles on restore, so a `subagent-group` row persisted as `working` claimed live children forever — the mirror of the defect the previous commit fixed, and the same `ssh-execution-boundary.md` violation in the other direction. Reconciled host-side, at journal open, not in the renderer: mobile shows only the durable text twin and reconciles nothing, so a renderer-only fix would leave it claiming live children indefinitely. Opening the journal is also the one moment a host can honestly say the previous writer is gone. - `staleSubagentRosterRevisions` rewrites every child still reading `working` to `unverifiable` and regenerates the twin from the same summary, so the block and the sentence cannot disagree. - No terminal timestamp: the child stopped being observable at an unknown moment, and stamping the reopen would report the downtime as its run length. - Revises in place under the parsed identity, so a reopen upserts the row rather than appending a duplicate, and a second reopen writes nothing. - Skipped on a corrupt load: that journal is still owed a rebuild from provider history, and content past the repair's free sequence retires the demand. Reconciles journal ROWS, not roster state — the producer's in-process group map is untouched, so the roster's known seeding limitation is unchanged, as is `canReplaceSubagentState`: `unverifiable` still does not latch. --------- Co-authored-by: Merge Sim --- .../orchestration/worker-output.test.ts | 210 +++++ .../codex-structured-item-translation.test.ts | 7 +- .../codex/codex-structured-journal-limits.ts | 7 + ...x-structured-journal-translation-frames.ts | 43 + ...ured-journal-translation-subagents.test.ts | 168 ++++ .../codex-structured-journal-translation.ts | 76 +- src/main/codex/codex-subagent-activity.ts | 140 ++++ src/main/codex/codex-subagent-roster.test.ts | 769 ++++++++++++++++++ src/main/codex/codex-subagent-roster.ts | 347 ++++++++ .../journal-store-open.ts | 45 +- .../journal-store-restore.ts | 3 +- .../journal-subagent-liveness.test.ts | 202 +++++ .../journal-subagent-liveness.ts | 101 +++ .../provider-frame-activity.test.ts | 10 + .../provider-frame-disposition.test.ts | 49 +- .../provider-frame-disposition.ts | 16 +- .../worker-transcript-payload.test.ts | 75 ++ .../worker-transcript-payload.ts | 48 +- .../methods/native-chat-rpc-block-sanitize.ts | 132 +++ .../runtime/rpc/methods/native-chat.test.ts | 33 + src/main/runtime/rpc/methods/native-chat.ts | 110 +-- .../NativeChatMessageList.test.tsx | 295 +++++++ .../native-chat/NativeChatMessageRow.tsx | 35 +- .../NativeChatSubagentRun.test.tsx | 318 ++++++++ .../native-chat/NativeChatSubagentRun.tsx | 277 +++++++ .../native-chat/NativeChatToolRun.tsx | 38 +- .../native-chat/native-chat-tool-fold.test.ts | 49 ++ src/renderer/src/i18n/locales/en.json | 20 + src/shared/agent-session-journal-schemas.ts | 24 +- .../native-chat-subagent-summary.test.ts | 228 ++++++ src/shared/native-chat-subagent-summary.ts | 216 +++++ src/shared/native-chat-tool-fold.ts | 13 +- src/shared/native-chat-types.ts | 46 ++ src/shared/worker-transcript-text.ts | 66 +- 34 files changed, 4058 insertions(+), 158 deletions(-) create mode 100644 src/main/codex/codex-structured-journal-translation-frames.ts create mode 100644 src/main/codex/codex-structured-journal-translation-subagents.test.ts create mode 100644 src/main/codex/codex-subagent-activity.ts create mode 100644 src/main/codex/codex-subagent-roster.test.ts create mode 100644 src/main/codex/codex-subagent-roster.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-subagent-liveness.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-subagent-liveness.ts create mode 100644 src/main/runtime/rpc/methods/native-chat-rpc-block-sanitize.ts create mode 100644 src/renderer/src/components/native-chat/NativeChatSubagentRun.test.tsx create mode 100644 src/renderer/src/components/native-chat/NativeChatSubagentRun.tsx create mode 100644 src/shared/native-chat-subagent-summary.test.ts create mode 100644 src/shared/native-chat-subagent-summary.ts diff --git a/src/cli/handlers/orchestration/worker-output.test.ts b/src/cli/handlers/orchestration/worker-output.test.ts index 44da2d67f93..895e9909d05 100644 --- a/src/cli/handlers/orchestration/worker-output.test.ts +++ b/src/cli/handlers/orchestration/worker-output.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from 'vitest' import type { OrchestrationFleetWorker } from '../../../shared/orchestration-fleet-projection' +import { subagentGroupFallbackText } from '../../../shared/native-chat-subagent-summary' +import type { + NativeChatBlock, + NativeChatMessage, + NativeChatSubagentEntry +} from '../../../shared/native-chat-types' import type { OrchestrationWorkerReadResult } from '../../../shared/orchestration-worker-output' import { formatWorkerRead, formatWorkerStart } from './worker-output' @@ -288,3 +294,207 @@ function workerReadResult( type WorkerReadResultWithoutContext = T extends unknown ? Omit : never + +function transcriptRead( + blocks: NativeChatBlock[], + role: NativeChatMessage['role'] = 'assistant' +): OrchestrationWorkerReadResult { + const message: NativeChatMessage = { + id: 'm1', + role, + blocks, + timestamp: 1, + source: 'transcript' + } + return { + dispatchId: 'd1', + source: 'transcript', + sourceIdentity: 'pane:1', + provider: 'codex', + transcript: { messages: [message], nextCursor: '1', limited: false, returnedMessageCount: 1 }, + cursor: '1', + status: { worker: 'running', terminal: 'running' }, + fallbackReason: null, + warnings: [] + } +} + +const ROSTER: readonly NativeChatSubagentEntry[] = [ + { id: 'child-1', label: 'read', state: 'working' }, + { id: 'child-2', label: 'edit', state: 'failed' } +] + +function occurrences(haystack: string, needle: string): number { + return haystack.split(needle).length - 1 +} + +describe('formatWorkerRead', () => { + // The replay case this row is durable for: SQLite-backed, re-sent on every + // reconnect, and read here by a client that draws no roster block, runs no + // reconciliation, and cannot re-check whether those children still exist. A + // sentence frozen mid-flight outlives the process that wrote it, so it must + // not keep asserting a liveness only that process could have observed — + // `docs/reference/ssh-execution-boundary.md` calls that loss of contact + // reported as a live state. + it('replays a mid-flight roster row without claiming a child is still working', () => { + const midFlight: readonly NativeChatSubagentEntry[] = [ + { id: 'child-1', label: 'read', state: 'working' }, + { id: 'child-2', label: 'search', state: 'working' }, + { id: 'child-3', label: 'edit', state: 'failed' } + ] + + const output = formatWorkerRead( + transcriptRead([ + { type: 'text', text: subagentGroupFallbackText(midFlight) }, + { type: 'subagent-group', groupId: 'thread:turn-1', agents: [...midFlight] } + ]) + ) + + expect(output).toContain('[assistant] Kicked off 3 subagents (1 failed)') + expect(output).not.toMatch(/\bworking\b/) + }) + + // The body `codexSubagentGroupBody` actually writes: the plain-text twin, then + // the block it stands in for. The twin exists for clients that cannot draw the + // block, so a client printing the block must not print the twin beside it — + // the renderer drops the twin for the same reason, from the other side. + it('prints the roster sentence once for the two-block row the producer writes', () => { + const sentence = subagentGroupFallbackText(ROSTER) + const output = formatWorkerRead( + transcriptRead( + [ + { type: 'text', text: sentence }, + { type: 'subagent-group', groupId: 'thread:turn-1', agents: [...ROSTER] } + ], + 'system' + ) + ) + + expect(output).toContain(`[system] ${sentence}`) + expect(occurrences(output, sentence)).toBe(1) + }) + + // Suppression is per twin, not per message. One twin beside two roster blocks + // silenced BOTH groups and printed one sentence, so the second roster vanished + // with no marker — the same silent drop the missing-twin case above avoids. + it('stands in for the second roster block when only one twin accompanies two', () => { + const other: readonly NativeChatSubagentEntry[] = [ + { id: 'child-3', label: 'plan', state: 'completed' } + ] + const output = formatWorkerRead( + transcriptRead( + [ + { type: 'text', text: subagentGroupFallbackText(ROSTER) }, + { type: 'subagent-group', groupId: 'thread:turn-1', agents: [...ROSTER] }, + { type: 'subagent-group', groupId: 'thread:turn-2', agents: [...other] } + ], + 'system' + ) + ) + + expect(occurrences(output, subagentGroupFallbackText(ROSTER))).toBe(1) + expect(output).toContain(`[subagents] ${subagentGroupFallbackText(other)}`) + }) + + // Which group a lone twin belongs to is decided by its TEXT, not its position. + // Claiming positionally silenced whichever group came first, so a twin + // belonging to a LATER group erased the earlier group's roster and printed the + // later one's sentence twice — the same silent drop, one permutation over. + it('claims a lone twin for the group it names, not the first group in the message', () => { + const other: readonly NativeChatSubagentEntry[] = [ + { id: 'child-3', label: 'plan', state: 'completed' } + ] + const second = subagentGroupFallbackText(other) + const output = formatWorkerRead( + transcriptRead( + [ + { type: 'text', text: second }, + { type: 'subagent-group', groupId: 'thread:turn-1', agents: [...ROSTER] }, + { type: 'subagent-group', groupId: 'thread:turn-2', agents: [...other] } + ], + 'system' + ) + ) + + expect(occurrences(output, second)).toBe(1) + expect(output).toContain(`[subagents] ${subagentGroupFallbackText(ROSTER)}`) + }) + + // The same claim, with the twin written after both blocks: nothing about the + // ORDER of a twin and its group is guaranteed by the block schema. + it('claims a trailing twin for the group it names', () => { + const other: readonly NativeChatSubagentEntry[] = [ + { id: 'child-3', label: 'plan', state: 'completed' } + ] + const second = subagentGroupFallbackText(other) + const output = formatWorkerRead( + transcriptRead( + [ + { type: 'subagent-group', groupId: 'thread:turn-1', agents: [...ROSTER] }, + { type: 'subagent-group', groupId: 'thread:turn-2', agents: [...other] }, + { type: 'text', text: second } + ], + 'system' + ) + ) + + expect(occurrences(output, second)).toBe(1) + expect(output).toContain(`[subagents] ${subagentGroupFallbackText(ROSTER)}`) + }) + + // A group with no twin beside it is a shape the block schema admits and no + // producer writes. Dropping it would lose the roster entirely, so the block + // itself carries the sentence when nothing else does. + it('stands in for a roster block that arrived without its twin', () => { + const output = formatWorkerRead( + transcriptRead([{ type: 'subagent-group', groupId: 'thread:turn-1', agents: [...ROSTER] }]) + ) + + expect(output).toContain(`[assistant] [subagents] ${subagentGroupFallbackText(ROSTER)}`) + }) + + // A roster from a newer build holds a state this build does not know, which + // `summarizeSubagentGroup` reads as `unverifiable`. Recomputing the sentence + // to compare it against the frozen twin therefore produced a DIFFERENT string, + // and the CLI printed the roster twice: the twin's own wording plus a + // `[subagents]` line contradicting it. + it('prints the roster once when the twin names a state this build cannot reproduce', () => { + const frozenTwin = 'Ran 2 subagents (1 cancelled)' + const output = formatWorkerRead( + transcriptRead( + [ + { type: 'text', text: frozenTwin }, + { + type: 'subagent-group', + groupId: 'thread:turn-1', + agents: [ + { id: 'child-1', label: 'read', state: 'completed' }, + { id: 'child-2', label: 'edit', state: 'cancelled' } + ] as unknown as NativeChatSubagentEntry[] + } + ], + 'system' + ) + ) + + expect(output).toContain(`[system] ${frozenTwin}`) + expect(output).not.toContain('[subagents]') + expect(output).not.toContain('unverifiable') + }) + + // The journal admits block types this build does not know, and `client.call` + // casts the RPC result rather than validating it — so a newer remote host's + // block reaches this formatter as-is. Reading fields off it threw a TypeError + // and took down the whole `worker read`. + it('degrades an unknown block type from a newer host instead of throwing', () => { + const output = formatWorkerRead( + transcriptRead([ + { type: 'text', text: 'before' }, + { type: 'plan-step', title: 'ship it' } as unknown as NativeChatBlock, + { type: 'text', text: 'after' } + ]) + ) + + expect(output).toContain('[assistant] before\n[unsupported block]\nafter') + }) +}) diff --git a/src/main/codex/codex-structured-item-translation.test.ts b/src/main/codex/codex-structured-item-translation.test.ts index 2558f4b60de..0c47919f59d 100644 --- a/src/main/codex/codex-structured-item-translation.test.ts +++ b/src/main/codex/codex-structured-item-translation.test.ts @@ -784,7 +784,7 @@ describe('codex item bodies', () => { } }) - it('leaves subagent items on the generic row until a real renderer exists', () => { + it('drops the raw subagent item now the roster row renders it', () => { expect( codexJournalItem({ type: 'subAgentActivity', @@ -793,10 +793,7 @@ describe('codex item bodies', () => { agentThreadId: 'thread-child', agentPath: '/root/list_directory' }) - ).toMatchObject({ - handled: false, - body: { kind: 'status', providerFrame: { kind: 'item:subAgentActivity' } } - }) + ).toMatchObject({ handled: true, body: null }) }) it('drops the sleep item, which codex itself renders as nothing', () => { diff --git a/src/main/codex/codex-structured-journal-limits.ts b/src/main/codex/codex-structured-journal-limits.ts index d741a9e86d2..5137ea8dd16 100644 --- a/src/main/codex/codex-structured-journal-limits.ts +++ b/src/main/codex/codex-structured-journal-limits.ts @@ -7,3 +7,10 @@ export const MAX_CODEX_PENDING_PROMPTS = 128 export const MAX_CODEX_IDENTITY_ENTRIES = 512 export const MAX_CODEX_DETAIL_ENTRIES = 512 export const MAX_CODEX_DETAIL_BYTES = 64 * 1024 +/** Spawn-group rows kept live per session, and children per row. Both bound an + * event-accumulated map that no provider snapshot ever prunes. */ +export const MAX_CODEX_SUBAGENT_GROUPS = 32 +export const MAX_CODEX_SUBAGENTS_PER_GROUP = 64 +/** Threads whose latest token total is retained. Usage frames arrive for + * threads that are not yet (or never become) roster children. */ +export const MAX_CODEX_TOKEN_USAGE_THREADS = 256 diff --git a/src/main/codex/codex-structured-journal-translation-frames.ts b/src/main/codex/codex-structured-journal-translation-frames.ts new file mode 100644 index 00000000000..22dc516b210 --- /dev/null +++ b/src/main/codex/codex-structured-journal-translation-frames.ts @@ -0,0 +1,43 @@ +/** + * The translator's provider-frame arms. + * + * Each returns null for a frame it does not own, which is the translator's + * signal to keep looking. Split out so the translator reads as routing rather + * than as the shape checks each arm performs. + */ + +import type { CodexJournalTranslationAdmission } from './codex-structured-journal-contracts' +import { settleCodexOversizedNotification } from './codex-structured-journal-settlement' +import { + readCodexJournalRecord, + readCodexJournalString +} from './codex-structured-journal-translation-values' + +type OversizedInput = Parameters[0] + +/** A notification the transport refused to carry whole: settle whatever it + * opened rather than leaving the item mid-flight. */ +export function settleCodexOversizedNotificationFrame(input: { + sessionId: string + threadId: string + kind: string + payload: unknown + sink: OversizedInput['sink'] + streams: OversizedInput['streams'] + activeItems: OversizedInput['activeItems'] +}): CodexJournalTranslationAdmission | null { + if (input.kind !== 'frame:oversized-notification') { + return null + } + const method = readCodexJournalString(readCodexJournalRecord(input.payload), 'method') + return method + ? settleCodexOversizedNotification({ + sessionId: input.sessionId, + threadId: input.threadId, + method, + sink: input.sink, + streams: input.streams, + activeItems: input.activeItems + }) + : null +} diff --git a/src/main/codex/codex-structured-journal-translation-subagents.test.ts b/src/main/codex/codex-structured-journal-translation-subagents.test.ts new file mode 100644 index 00000000000..bf5cdffa5a9 --- /dev/null +++ b/src/main/codex/codex-structured-journal-translation-subagents.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from 'vitest' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import type { AgentSessionTurnActivity } from '../../shared/agent-session-wire' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import { isSubagentGroupBlock } from '../../shared/native-chat-types' +import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' +import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' + +const SESSION_ID = 'session-1' +const THREAD_ID = 'thread-abc' +const TURN_ID = 'turn-1' + +type Row = { key: string; body: AgentJournalItemBody } + +function harness() { + const rows: Row[] = [] + const activities: (AgentSessionTurnActivity | null)[] = [] + const sink: StructuredAgentSessionEventSink = { + appendItem: (identity: AgentJournalItemIdentity, body) => + rows.push({ key: agentJournalItemKey(identity), body }), + appendTombstone: () => {}, + publish: () => {}, + setActivity: (activity) => activities.push(activity) + } + const translator = createCodexJournalTranslator({ + sink, + primaryThreadId: () => THREAD_ID, + schedule: (run: () => void) => { + run() + return () => {} + } + }) + return { translator, rows, activities } +} + +function notification(method: string, params: unknown): CodexStructuredSessionEvent { + return { type: 'notification', sessionId: SESSION_ID, threadId: THREAD_ID, method, params } +} + +function subagentItem(kind: string, agentThreadId: string, agentPath: string): unknown { + return { + turnId: TURN_ID, + item: { + type: 'subAgentActivity', + id: `item-${agentThreadId}-${kind}`, + kind, + agentThreadId, + agentPath + } + } +} + +/** Every activity item reaches the wire twice. */ +function deliverActivity( + translator: ReturnType, + params: unknown +): void { + translator.handle(notification('item/started', params)) + translator.handle(notification('item/completed', params)) +} + +function rosterAgents(rows: Row[]): { id: string; state: string; tokens?: number }[] { + const body = rows.findLast((row) => row.key.startsWith('orca:codex-subagents'))?.body + if (!body || body.kind !== 'message') { + return [] + } + return body.blocks.find(isSubagentGroupBlock)?.agents ?? [] +} + +describe('codex journal translation — subagents', () => { + it('renders a spawn group as one roster row and no opcode-shaped duplicate', () => { + const { translator, rows } = harness() + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + deliverActivity(translator, subagentItem('started', 'child-1', '/root/list_directory')) + deliverActivity(translator, subagentItem('interacted', 'child-1', '/root/list_directory')) + + expect(rosterAgents(rows)).toMatchObject([ + { id: 'child-1', label: 'list_directory', state: 'working' } + ]) + // Four wire deliveries (two items, each sent twice) collapse to ONE roster + // row, and none of the gray `codex · item:subAgentActivity` rows survive. + const providerFrameKinds = rows.flatMap((row) => + row.body.kind === 'status' && row.body.providerFrame ? [row.body.providerFrame.kind] : [] + ) + expect(providerFrameKinds).toEqual([]) + expect(rows.filter((row) => row.key.startsWith('orca:codex-subagents'))).toHaveLength(1) + }) + + // The roster claims the item, but claiming it must not take the turn tail with + // it: the activity table is reached only through the publish arm, so a bare + // return leaves the tail stuck on whatever the previous frame said. + it('still publishes the turn tail for an item the roster claims', () => { + const { translator, activities } = harness() + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + activities.length = 0 + deliverActivity(translator, subagentItem('started', 'child-1', '/root/read')) + + expect(activities.at(-1)).toEqual({ + turnId: TURN_ID, + text: 'Coordinating with another agent' + }) + }) + + it('consumes thread/tokenUsage/updated instead of swallowing it as chrome', () => { + const { translator, rows } = harness() + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + deliverActivity(translator, subagentItem('started', 'child-1', '/root/read')) + translator.handle( + notification('thread/tokenUsage/updated', { + threadId: 'child-1', + tokenUsage: { total: { totalTokens: 40661 } } + }) + ) + + expect(rosterAgents(rows)).toMatchObject([{ id: 'child-1', tokens: 40661 }]) + }) + + // The QA scenario this row got wrong: three `spawn_agent` children were still + // running when a mid-turn correction ended their turn and opened a new one. + // They reported `completed` 57-87s later, so a turn boundary is a fact about + // the turn and never evidence that contact with a child was lost. + it('leaves children working when their turn ends and a newer turn opens', () => { + const { translator, rows } = harness() + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + deliverActivity(translator, subagentItem('started', 'child-1', '/root/read_readme')) + deliverActivity(translator, subagentItem('started', 'child-2', '/root/read_package')) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } })) + translator.handle(notification('turn/started', { turn: { id: 'turn-2' } })) + + expect(rosterAgents(rows)).toMatchObject([ + { id: 'child-1', state: 'working' }, + { id: 'child-2', state: 'working' } + ]) + + // And the verdict a child reports after its turn ended still lands on the row. + deliverActivity(translator, subagentItem('completed', 'child-1', '/root/read_readme')) + + expect(rosterAgents(rows)).toMatchObject([ + { id: 'child-1', state: 'completed' }, + { id: 'child-2', state: 'working' } + ]) + }) + + it('sweeps every group when the provider ends', () => { + const { translator, rows } = harness() + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + deliverActivity(translator, subagentItem('started', 'child-1', '/root/read')) + translator.handle({ + type: 'ended', + sessionId: SESSION_ID, + reason: 'provider exited', + cause: 'unexpected-exit', + fence: 1, + acquisitionGeneration: 'gen-1' + } as CodexStructuredSessionEvent) + + expect(rosterAgents(rows)).toMatchObject([{ id: 'child-1', state: 'unverifiable' }]) + }) +}) diff --git a/src/main/codex/codex-structured-journal-translation.ts b/src/main/codex/codex-structured-journal-translation.ts index c0c103bddff..c8a6fe9f158 100644 --- a/src/main/codex/codex-structured-journal-translation.ts +++ b/src/main/codex/codex-structured-journal-translation.ts @@ -1,4 +1,10 @@ import { createCodexProviderActivityReader } from '../native-chat/agent-session-wire/provider-frame-activity' +import { + CODEX_TOKEN_USAGE_METHOD, + readCodexNotificationThreadItem +} from './codex-subagent-activity' +import { CodexSubagentRoster } from './codex-subagent-roster' +import { readCodexThreadItem } from './codex-structured-item-translation' import { CodexJournalGenericFrames } from './codex-structured-journal-generic-frames' import { CodexJournalItems } from './codex-structured-journal-items' import { CodexJournalPrompts } from './codex-structured-journal-prompts' @@ -10,16 +16,12 @@ import { } from './codex-structured-journal-contracts' import { settleCodexJournalSession, - settleCodexJournalTurn, - settleCodexOversizedNotification + settleCodexJournalTurn } from './codex-structured-journal-settlement' +import { settleCodexOversizedNotificationFrame } from './codex-structured-journal-translation-frames' import { restoreCodexJournalThread } from './codex-structured-journal-translation-restore' import { CodexJournalActiveTurns } from './codex-structured-journal-translation-turn-state' import { publishCodexTurnLifecycle } from './codex-structured-journal-translation-turns' -import { - readCodexJournalRecord, - readCodexJournalString -} from './codex-structured-journal-translation-values' import { readCodexTurnId } from './codex-structured-thread-facts' import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' @@ -55,6 +57,11 @@ export function createCodexJournalTranslator( const prompts = new CodexJournalPrompts(deps, (threadId, itemId) => items.detailFor(threadId, itemId) ) + const subagents = new CodexSubagentRoster({ + sink: deps.sink, + primaryThreadId: () => deps.primaryThreadId?.() ?? null, + activeTurn: (threadId) => activeTurns.current(threadId) + }) const flushStreams = (): CodexJournalTranslationAdmission => items.streams.flush() ? CODEX_JOURNAL_ADMITTED : { accepted: false, reason: 'backpressure' } let readActivity = createCodexProviderActivityReader() @@ -118,6 +125,11 @@ export function createCodexJournalTranslator( if (!admission.accepted) { return admission } + // No event will ever settle a child once the provider is gone. + const sweep = subagents.settleSession() + if (!sweep.accepted) { + return sweep + } readActivity = createCodexProviderActivityReader() deps.sink.setActivity?.(null) items.activeItems.clear() @@ -159,7 +171,30 @@ export function createCodexJournalTranslator( if (event.method === 'turn/completed') { return completeTurn(event) } + if (event.method === CODEX_TOKEN_USAGE_METHOD) { + // Classified `status-chrome`, so the generic-frame path swallows it + // before the journal. The roster consumes it as a typed notification. + const admission = subagents.handleTokenUsage(event.params) + if (admission) { + return admission + } + } if (event.method === 'item/started' || event.method === 'item/completed') { + const subagentItem = readCodexNotificationThreadItem(event.params, readCodexThreadItem) + // Null means the roster did not claim it; fall through to normal item + // handling. Returning here unconditionally swallows every other item. + const subagentAdmission = subagentItem + ? subagents.handleItem({ + threadId: event.threadId, + turnId: readCodexTurnId(event.params) ?? activeTurns.current(event.threadId), + item: subagentItem + }) + : null + if (subagentAdmission) { + // Not a bare return: the roster claiming the item must not skip the + // turn-tail arm, which is the only publisher of its activity copy. + return publishActivity(event, subagentAdmission) + } const translated = items.handle(event) return publishActivity( event, @@ -186,30 +221,25 @@ export function createCodexJournalTranslator( items.dispose() prompts.dispose() genericFrames.dispose() + subagents.dispose() activeTurns.clear() } } + /** Settles the item a notification the transport refused to carry left + * mid-flight; null when the frame is not one. */ function settleOversizedNotification(event: { sessionId: string threadId: string kind: string payload: unknown }): CodexJournalTranslationAdmission | null { - if (event.kind !== 'frame:oversized-notification') { - return null - } - const method = readCodexJournalString(readCodexJournalRecord(event.payload), 'method') - return method - ? settleCodexOversizedNotification({ - sessionId: event.sessionId, - threadId: event.threadId, - method, - sink: deps.sink, - streams: items.streams, - activeItems: items.activeItems - }) - : null + return settleCodexOversizedNotificationFrame({ + ...event, + sink: deps.sink, + streams: items.streams, + activeItems: items.activeItems + }) } function startTurn(event: { @@ -255,6 +285,12 @@ export function createCodexJournalTranslator( if (!turnId) { return CODEX_JOURNAL_ADMITTED } + // The roster is deliberately NOT swept here. `spawn_agent` children outlive + // the turn that spawned them and go on reporting into the same group, so a + // turn boundary is no evidence contact was lost — and `turn/completed` is + // the only turn-end notification Codex sends, so an abort cannot be told + // apart from a clean finish either. Only `settleSession` may write + // `unverifiable`. const admission = settleCodexJournalTurn({ sink: deps.sink, sessionId: event.sessionId, diff --git a/src/main/codex/codex-subagent-activity.ts b/src/main/codex/codex-subagent-activity.ts new file mode 100644 index 00000000000..f12e9dfb1b3 --- /dev/null +++ b/src/main/codex/codex-subagent-activity.ts @@ -0,0 +1,140 @@ +// Reading Codex's subagent wire shapes. +// +// Established by a live probe against `codex app-server` 0.152.1, not inferred: +// * `subAgentActivity` items carry `{kind, agentThreadId, agentPath}`, and each +// one arrives TWICE — via `item/started` and again via `item/completed`. +// * `agentPath` is a tree path (`/root`, `/root/list_directory`); the trailing +// segment is a semantic task name and the only label available. There is no +// `thread/started` for a child, so nickname/role/depth do not exist. +// * `agentsStates` on `collabAgentToolCall` arrived empty (`{}`) throughout the +// probe, so nothing here reads it — state comes from `kind` alone. +// * `thread/tokenUsage/updated` reports a per-thread RUNNING TOTAL, so the +// latest frame replaces the previous one — it is never accumulated. + +import type { NativeChatSubagentState } from '../../shared/native-chat-types' +import type { CodexThreadItem } from './codex-structured-item-translation' + +export const CODEX_SUBAGENT_ITEM_TYPE = 'subAgentActivity' +export const CODEX_TOKEN_USAGE_METHOD = 'thread/tokenUsage/updated' + +export type CodexSubagentActivity = { + kind: string + agentThreadId: string + agentPath: string | null +} + +function nonEmptyString(value: unknown): string | null { + return typeof value === 'string' && value.length > 0 ? value : null +} + +function record(value: unknown): Record | null { + return typeof value === 'object' && value !== null && !Array.isArray(value) + ? (value as Record) + : null +} + +export function readCodexSubagentActivity(item: CodexThreadItem): CodexSubagentActivity | null { + if (item.type !== CODEX_SUBAGENT_ITEM_TYPE) { + return null + } + const agentThreadId = nonEmptyString(item.agentThreadId) + if (!agentThreadId) { + return null + } + return { + kind: nonEmptyString(item.kind) ?? '', + agentThreadId, + agentPath: nonEmptyString(item.agentPath) + } +} + +/** + * The state a `kind` implies for the child it names. + * + * An unrecognized kind means "this child exists and reported something we + * cannot classify" — `working`, which the session sweep will later settle to + * `unverifiable` if nothing better ever arrives. Claiming a terminal state from + * an unknown kind would assert an outcome the wire never gave us. + */ +export function codexSubagentStateForKind(kind: string): NativeChatSubagentState { + if (kind === 'completed') { + return 'completed' + } + if (kind === 'interrupted') { + return 'stopped' + } + return 'working' +} + +/** Path segments, empty ones dropped: `/root/list_directory` → 2 segments. */ +export function codexSubagentPathSegments(agentPath: string | null): string[] { + return agentPath === null ? [] : agentPath.split('/').filter((part) => part.length > 0) +} + +/** The one path segment that names the parent turn itself rather than a child. + * Compared after the same normalization the label uses, not against the raw + * string: `/root/` and `/root//` are the same node as `/root`, and a check that + * disagreed with `codexSubagentPathSegments` would let one path be both the + * turn and a child of it — a phantom row labelled `root` inflating the group. + * Only this segment is the root; `/morpheus` is single-segment too but IS a + * child. */ +const CODEX_ROOT_AGENT_SEGMENT = 'root' + +/** + * Whether an activity item describes the ROOT of the agent tree rather than a + * spawned child. Counting the root would make the parent turn report itself as + * its own subagent. + * + * A path-less item cannot be placed in the tree at all, so it is treated as a + * child: dropping it would lose a real spawn, while an extra row is visible and + * self-correcting. + */ +export function isCodexRootAgentActivity(activity: CodexSubagentActivity): boolean { + const segments = codexSubagentPathSegments(activity.agentPath) + return segments.length === 1 && segments[0] === CODEX_ROOT_AGENT_SEGMENT +} + +/** Row label: the agent path's trailing segment, trimmed. A segment with nothing + * visible in it survives the empty-segment filter but would draw a nameless row, + * so it reads as no label and the caller's placeholder takes over. Trimmed + * because the caller keys its collision ordinals on this string: ` read ` and + * `read` render identically and must therefore collide. */ +export function codexSubagentLabel(activity: CodexSubagentActivity): string | null { + const trailing = codexSubagentPathSegments(activity.agentPath).at(-1)?.trim() + return trailing !== undefined && trailing.length > 0 ? trailing : null +} + +export type CodexThreadTokenTotal = { threadId: string; totalTokens: number } + +/** `{threadId, tokenUsage: {total: {totalTokens}}}`. Older builds put the total + * on the envelope, so both shapes are accepted. */ +export function readCodexThreadTokenTotal(params: unknown): CodexThreadTokenTotal | null { + const root = record(params) + if (!root) { + return null + } + const threadId = nonEmptyString(root.threadId) ?? nonEmptyString(record(root.thread)?.id) + if (!threadId) { + return null + } + const usage = record(root.tokenUsage) + const total = record(usage?.total)?.totalTokens ?? usage?.totalTokens ?? root.totalTokens + return typeof total === 'number' && Number.isFinite(total) && total >= 0 + ? { threadId, totalTokens: total } + : null +} + +/** Pull the `subAgentActivity` item out of a raw notification payload. + * + * Lives beside the readers rather than in the translator: the translator's job + * is routing, and this is the shape check that decides whether a frame is one + * of ours at all. Returns null for anything that is not a thread item, which is + * the translator's signal to keep looking. */ +export function readCodexNotificationThreadItem( + params: unknown, + read: (value: unknown) => CodexThreadItem | null +): CodexThreadItem | null { + const record = + typeof params === 'object' && params !== null ? (params as Record) : {} + return read(record.item) +} diff --git a/src/main/codex/codex-subagent-roster.test.ts b/src/main/codex/codex-subagent-roster.test.ts new file mode 100644 index 00000000000..2f20c9df9bf --- /dev/null +++ b/src/main/codex/codex-subagent-roster.test.ts @@ -0,0 +1,769 @@ +import { describe, expect, it } from 'vitest' +import { isAdmissibleAgentJournalItemBody } from '../../shared/agent-session-journal-schemas' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import { MAX_SUBAGENT_FIELD_CHARS } from '../../shared/native-chat-subagent-summary' +import { isSubagentGroupBlock, type NativeChatSubagentEntry } from '../../shared/native-chat-types' +import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { + CodexSubagentRoster, + codexSubagentGroupIdentity, + codexSubagentGroupId +} from './codex-subagent-roster' +import type { CodexThreadItem } from './codex-structured-item-translation' +import { + MAX_CODEX_SUBAGENT_GROUPS, + MAX_CODEX_SUBAGENTS_PER_GROUP, + MAX_CODEX_TOKEN_USAGE_THREADS +} from './codex-structured-journal-limits' + +const THREAD = 'thread-parent' +const TURN = 'turn-1' + +type Appended = { identity: AgentJournalItemIdentity; body: AgentJournalItemBody } + +function createHarness(options: { threadId?: string | null } = {}): { + roster: CodexSubagentRoster + appended: Appended[] + agents: () => NativeChatSubagentEntry[] + latest: () => Appended | undefined +} { + const appended: Appended[] = [] + let clock = 1_000 + const sink: StructuredAgentSessionEventSink = { + appendItem: () => {}, + appendTombstone: () => {}, + publish: () => {}, + tryAppendItem: (identity, body) => { + appended.push({ identity, body }) + return { accepted: true } + }, + tryPublish: () => ({ accepted: true }) + } + const roster = new CodexSubagentRoster({ + sink, + primaryThreadId: () => (options.threadId === undefined ? THREAD : options.threadId), + activeTurn: () => TURN, + now: () => (clock += 1) + }) + const agents = (): NativeChatSubagentEntry[] => { + const body = appended.at(-1)?.body + if (!body || body.kind !== 'message') { + return [] + } + const block = body.blocks.find(isSubagentGroupBlock) + return block ? block.agents : [] + } + return { roster, appended, agents, latest: () => appended.at(-1) } +} + +function latestIdentity(appended: Appended[]): AgentJournalItemIdentity | undefined { + return appended.at(-1)?.identity +} + +function activity(input: { + id?: string + kind: string + agentThreadId: string + agentPath: string | null +}): CodexThreadItem { + return { + type: 'subAgentActivity', + id: input.id ?? `item-${input.agentThreadId}-${input.kind}`, + kind: input.kind, + agentThreadId: input.agentThreadId, + agentPath: input.agentPath + } +} + +function deliver( + roster: CodexSubagentRoster, + item: CodexThreadItem, + turnId: string | null = TURN +): void { + // Every activity item reaches the wire twice: item/started, then item/completed. + roster.handleItem({ threadId: THREAD, turnId, item }) + roster.handleItem({ threadId: THREAD, turnId, item }) +} + +/** + * A sink that coalesces the way the real queue does: by `coalescingKey` ALONE, + * with no op-kind check, and only draining when released. A fake that ignores + * the key cannot see an append being spliced out by its own publish. + */ +function createCoalescingHarness(): { + roster: CodexSubagentRoster + appended: Appended[] + drain: () => void +} { + const appended: Appended[] = [] + const queue: { key?: string; run: () => void }[] = [] + let clock = 1_000 + const submit = (key: string | undefined, run: () => void): void => { + const at = key === undefined ? -1 : queue.findIndex((queued) => queued.key === key) + if (at >= 0) { + queue.splice(at, 1) + } + queue.push(key === undefined ? { run } : { key, run }) + } + const sink: StructuredAgentSessionEventSink = { + appendItem: () => {}, + appendTombstone: () => {}, + publish: () => {}, + tryAppendItem: (identity, body, options) => { + submit(options?.coalescingKey, () => appended.push({ identity, body })) + return { accepted: true } + }, + tryPublish: (options) => { + submit(options?.coalescingKey ?? 'publish', () => {}) + return { accepted: true } + } + } + const roster = new CodexSubagentRoster({ + sink, + primaryThreadId: () => THREAD, + activeTurn: () => TURN, + now: () => (clock += 1) + }) + return { + roster, + appended, + drain: () => { + while (queue.length > 0) { + queue.shift()?.run() + } + } + } +} + +describe('CodexSubagentRoster', () => { + it('does not let its own publish evict the still-queued roster append', () => { + const { roster, appended, drain } = createCoalescingHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + drain() + + // Sharing the append's coalescing key with the publish spliced the append + // out of the queue, and `lastSerialized` then suppressed every retry. + expect(appended).toHaveLength(1) + }) + + it('counts a /morpheus agent as a child — only /root is the turn itself', () => { + const { roster, agents } = createHarness() + + deliver(roster, activity({ kind: 'started', agentThreadId: 'child-m', agentPath: '/morpheus' })) + + expect(agents()).toMatchObject([{ id: 'child-m', label: 'morpheus', state: 'working' }]) + }) + + // `codexSubagentPathSegments` already defines what a path means for the label, + // and the root check has to agree with it: a path that normalizes to the same + // node must classify the same way, or one string is both the turn itself and a + // child of it — a phantom row labelled `root` inflating the group by one. + it('reads a root path with a trailing or doubled separator as the turn itself', () => { + for (const agentPath of ['/root/', '/root//', '//root']) { + const { roster, appended } = createHarness() + + deliver(roster, activity({ kind: 'started', agentThreadId: THREAD, agentPath })) + + expect(appended).toEqual([]) + } + }) + + it('keeps a doubled separator inside a child path off the label', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root//read/' }) + ) + + expect(agents()).toMatchObject([{ id: 'child-1', label: 'read' }]) + }) + + // An all-whitespace trailing segment survives the empty-segment filter and + // would draw a row with no visible name at all. + it('falls back to the placeholder when the trailing segment has nothing to show', () => { + const { roster, agents } = createHarness() + + deliver(roster, activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/ ' })) + + expect(agents()).toMatchObject([{ id: 'child-1', label: 'subagent' }]) + }) + + // The collision ordinal keys on the label, so two segments that render + // identically must collide rather than both draw as `read`. + it('collides labels that differ only in surrounding whitespace', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-2', agentPath: '/root/ read ' }) + ) + + expect(agents().map((agent) => agent.label)).toEqual(['read', 'read 2']) + }) + + it('ignores the root node so a turn is not its own subagent', () => { + const { roster, appended } = createHarness() + + deliver(roster, activity({ kind: 'started', agentThreadId: THREAD, agentPath: '/root' })) + + expect(appended).toEqual([]) + }) + + it('writes an admissible journal body carrying a plain-text fallback block', () => { + const { roster, latest } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/list_directory' }) + ) + + const body = latest()?.body + expect(body?.kind).toBe('message') + expect(isAdmissibleAgentJournalItemBody(body)).toBe(true) + expect(body?.kind === 'message' ? body.blocks.map((block) => block.type) : []).toEqual([ + 'text', + 'subagent-group' + ]) + expect( + body?.kind === 'message' && body.blocks[0]?.type === 'text' ? body.blocks[0].text : '' + ).toBe('Kicked off 1 subagent') + }) + + it('keys the durable identity by the parent turn so a revision lands on one row', () => { + const { roster, appended } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + deliver( + roster, + activity({ kind: 'completed', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + + const expected = codexSubagentGroupIdentity(codexSubagentGroupId(THREAD, TURN)) + expect(new Set(appended.map((entry) => JSON.stringify(entry.identity)))).toEqual( + new Set([JSON.stringify(expected)]) + ) + }) + + it('rule 1 — a duplicate delivery writes no second revision', () => { + const { roster, appended } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + + expect(appended).toHaveLength(1) + }) + + it('rule 2 — a first event of any kind creates the entry in the state it implies', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'completed', agentThreadId: 'child-late', agentPath: '/root/search' }) + ) + + expect(agents()).toMatchObject([{ id: 'child-late', label: 'search', state: 'completed' }]) + }) + + it('rule 3 — a terminal state latches against a late or duplicate start', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'completed', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + deliver( + roster, + activity({ kind: 'interacted', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + + expect(agents()).toMatchObject([{ state: 'completed' }]) + }) + + it('rule 4 — the session sweep settles a lost child as unverifiable, not exited', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + deliver( + roster, + activity({ kind: 'completed', agentThreadId: 'child-2', agentPath: '/root/search' }) + ) + roster.settleSession() + + expect(agents()).toMatchObject([ + { id: 'child-1', state: 'unverifiable' }, + { id: 'child-2', state: 'completed' } + ]) + }) + + it('lets a swept child still report what it actually did', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + roster.settleSession() + expect(agents()[0]?.state).toBe('unverifiable') + + // Contact can return — a reconnected provider replays the child's own + // verdict. Latching the sweep would report a child that finished as one we + // never saw finish. + deliver( + roster, + activity({ kind: 'completed', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + expect(agents()[0]?.state).toBe('completed') + }) + + it('refuses to put a swept child back to working', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + roster.settleSession() + // A straggler progress tick after we gave up must not re-light the row. + deliver( + roster, + activity({ kind: 'interacted', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + expect(agents()[0]?.state).toBe('unverifiable') + }) + + it('keeps a real verdict when a later frame disagrees', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'completed', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + deliver( + roster, + activity({ kind: 'interrupted', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + expect(agents()[0]?.state).toBe('completed') + }) + + it('rule 4 — the session sweep settles every group and never un-terminals one', () => { + const { roster, agents, appended } = createHarness() + + deliver( + roster, + activity({ kind: 'interacted', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + roster.settleSession() + const afterFirstSweep = appended.length + roster.settleSession() + + expect(agents()).toMatchObject([{ state: 'unverifiable' }]) + expect(appended).toHaveLength(afterFirstSweep) + }) + + it('rule 5 — the whole roster is persisted in the carrier, not just a count', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + roster.handleTokenUsage({ threadId: 'child-1', tokenUsage: { total: { totalTokens: 40661 } } }) + + expect(agents()).toMatchObject([ + { id: 'child-1', label: 'read', state: 'working', tokens: 40661 } + ]) + }) + + it('rule 6 — the group id names the parent turn, or says there was none', () => { + const { roster, appended } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-2', agentPath: '/root/search' }), + null + ) + + expect(appended.map((entry) => entry.identity)).toEqual([ + { provider: 'orca', clientMessageId: `codex-subagents:${THREAD}:${TURN}` }, + { provider: 'orca', clientMessageId: `codex-subagents:${THREAD}:outside-turn` } + ]) + }) + + it('disambiguates two children that share a trailing path segment', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-2', agentPath: '/root/read' }) + ) + + expect(agents().map((agent) => agent.label)).toEqual(['read', 'read 2']) + }) + + it('takes the latest token snapshot per child and never accumulates updates', () => { + const { roster, agents } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + roster.handleTokenUsage({ threadId: 'child-1', tokenUsage: { total: { totalTokens: 100 } } }) + roster.handleTokenUsage({ threadId: 'child-1', tokenUsage: { total: { totalTokens: 250 } } }) + + expect(agents()).toMatchObject([{ tokens: 250 }]) + }) + + it('retains a usage frame that arrives before the child is known', () => { + const { roster, agents } = createHarness() + + roster.handleTokenUsage({ threadId: 'child-1', tokenUsage: { total: { totalTokens: 900 } } }) + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + + expect(agents()).toMatchObject([{ tokens: 900 }]) + }) + + it('never attributes the parent thread its own usage', () => { + const { roster, agents, appended } = createHarness() + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + const beforeParentUsage = appended.length + roster.handleTokenUsage({ threadId: THREAD, tokenUsage: { total: { totalTokens: 26099 } } }) + + expect(appended).toHaveLength(beforeParentUsage) + expect(agents()).toHaveLength(1) + expect(agents()[0]).not.toHaveProperty('tokens') + }) + + // The row is durable and both readers clip these fields to the same cap, so + // writing more than that is bytes replayed on every reconnect and then thrown + // away. The marker is an ellipsis, not the tool-output truncation sentence: + // `id` is the roster key and the renderer's React key. + it('bounds the provider strings the roster row carries into the journal', () => { + const { roster, agents, latest } = createHarness() + const oversized = 'a'.repeat(20 * 1024) + + deliver( + roster, + activity({ kind: 'started', agentThreadId: oversized, agentPath: `/root/${oversized}` }) + ) + + const entry = agents()[0] + expect(entry?.label.length).toBeLessThanOrEqual(MAX_SUBAGENT_FIELD_CHARS) + expect(entry?.label).toMatch(/…~0$/) + expect(entry?.id.length).toBeLessThanOrEqual(MAX_SUBAGENT_FIELD_CHARS) + expect(entry?.id).toMatch(/…~0$/) + expect(JSON.stringify(latest()?.body)).not.toContain('output truncated') + expect(isAdmissibleAgentJournalItemBody(latest()?.body)).toBe(true) + }) + + // The clip cuts UTF-16 code units, so a boundary landing inside a surrogate + // pair left a LONE high surrogate in a durable row — malformed, and replaced + // with U+FFFD through any non-JSON UTF-8 hop. + it('never clips a provider string mid surrogate pair', () => { + const { roster, agents } = createHarness() + const astral = '😀'.repeat(400) + + deliver( + roster, + activity({ kind: 'started', agentThreadId: astral, agentPath: `/root/${astral}` }) + ) + + const entry = agents()[0] + expect(entry?.id.length).toBeLessThanOrEqual(MAX_SUBAGENT_FIELD_CHARS) + expect(Buffer.from(entry?.id ?? '', 'utf8').toString('utf8')).toBe(entry?.id) + expect(Buffer.from(entry?.label ?? '', 'utf8').toString('utf8')).toBe(entry?.label) + }) + + // The clip removes exactly the tail that told two children apart: `id` is the + // renderer's React key, and `claimLabel` writes its repeat ordinal at the end. + // Two clipped children collapsing to one key drew two rows under one identity. + it('keeps clipped ids and labels distinct between children', () => { + const { roster, agents } = createHarness() + const prefix = 'p'.repeat(MAX_SUBAGENT_FIELD_CHARS) + const sharedPath = `/root/${'q'.repeat(640)}` + + deliver( + roster, + activity({ kind: 'started', agentThreadId: `${prefix}AAAA`, agentPath: sharedPath }) + ) + deliver( + roster, + activity({ kind: 'started', agentThreadId: `${prefix}BBBB`, agentPath: sharedPath }) + ) + + const entries = agents() + expect(entries).toHaveLength(2) + expect(new Set(entries.map((agent) => agent.id)).size).toBe(2) + expect(new Set(entries.map((agent) => agent.label)).size).toBe(2) + for (const agent of entries) { + expect(agent.id.length).toBeLessThanOrEqual(MAX_SUBAGENT_FIELD_CHARS) + expect(agent.label.length).toBeLessThanOrEqual(MAX_SUBAGENT_FIELD_CHARS) + } + }) + + it('caps the children one spawn group admits', () => { + const { roster, agents, appended } = createHarness() + for (let index = 0; index < MAX_CODEX_SUBAGENTS_PER_GROUP; index++) { + deliver( + roster, + activity({ kind: 'started', agentThreadId: `child-${index}`, agentPath: '/root/read' }) + ) + } + const atCap = appended.length + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-over-cap', agentPath: '/root/read' }) + ) + + expect(agents()).toHaveLength(MAX_CODEX_SUBAGENTS_PER_GROUP) + expect(agents().map((agent) => agent.id)).not.toContain('child-over-cap') + // Refusing the child must not burn a revision either. + expect(appended).toHaveLength(atCap) + }) + + // The eviction is the KNOWN LIMITATION the module documents: `groups` is never + // seeded from the journal, so the evicted group's next child rebuilds its + // durable row from that one child. Pinned so the boundary cannot move silently. + it('caps live spawn groups, and an evicted group rebuilds its row from one child', () => { + const { roster, appended, agents } = createHarness() + for (let index = 0; index <= MAX_CODEX_SUBAGENT_GROUPS; index++) { + deliver( + roster, + activity({ kind: 'started', agentThreadId: `child-${index}`, agentPath: '/root/read' }), + `turn-${index}` + ) + } + const evicted = codexSubagentGroupIdentity(codexSubagentGroupId(THREAD, 'turn-0')) + const rowsFor = (identity: AgentJournalItemIdentity): Appended[] => + appended.filter((entry) => JSON.stringify(entry.identity) === JSON.stringify(identity)) + expect(rowsFor(evicted)).toHaveLength(1) + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-late', agentPath: '/root/search' }), + 'turn-0' + ) + + expect(latestIdentity(appended)).toEqual(evicted) + expect(agents().map((agent) => agent.id)).toEqual(['child-late']) + }) + + it('keeps a token count a later thread-map eviction would otherwise retract', () => { + const { roster, agents } = createHarness() + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + roster.handleTokenUsage({ threadId: 'child-1', tokenUsage: { total: { totalTokens: 4242 } } }) + expect(agents()).toMatchObject([{ tokens: 4242 }]) + + for (let index = 0; index < MAX_CODEX_TOKEN_USAGE_THREADS; index++) { + roster.handleTokenUsage({ + threadId: `other-${index}`, + tokenUsage: { total: { totalTokens: index } } + }) + } + deliver( + roster, + activity({ kind: 'completed', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + + expect(agents()).toMatchObject([{ state: 'completed', tokens: 4242 }]) + }) + + it('caps retained usage threads, so a frame evicted before its child is dropped', () => { + const { roster, agents } = createHarness() + roster.handleTokenUsage({ threadId: 'child-1', tokenUsage: { total: { totalTokens: 900 } } }) + for (let index = 0; index < MAX_CODEX_TOKEN_USAGE_THREADS; index++) { + roster.handleTokenUsage({ + threadId: `other-${index}`, + tokenUsage: { total: { totalTokens: index } } + }) + } + + deliver( + roster, + activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + ) + + expect(agents()[0]).not.toHaveProperty('tokens') + }) + + it('declines a payload that is not a subagent item or a usage frame', () => { + const { roster } = createHarness() + + expect( + roster.handleItem({ + threadId: THREAD, + turnId: TURN, + item: { type: 'commandExecution', id: 'item-9' } + }) + ).toBeNull() + expect(roster.handleTokenUsage({ threadId: 'child-1' })).toBeNull() + }) + + // A refusal must never advance the duplicate-suppression state: an identical + // replay would short-circuit and the revision would never be retried. The + // append and the publish are the two ways to be refused, so both are covered. + it.each([{ refuse: 'append' as const }, { refuse: 'publish' as const }])( + 'retries the same revision after the $refuse is refused', + ({ refuse }) => { + let refusing = true + const appended: Appended[] = [] + const published: number[] = [] + const refusal = { accepted: false, reason: 'backpressure' } as const + const roster = new CodexSubagentRoster({ + sink: { + appendItem: () => {}, + appendTombstone: () => {}, + publish: () => {}, + tryAppendItem: (identity, body) => { + if (refusing && refuse === 'append') { + return refusal + } + appended.push({ identity, body }) + return { accepted: true } + }, + tryPublish: () => { + if (refusing && refuse === 'publish') { + return refusal + } + published.push(1) + return { accepted: true } + } + }, + primaryThreadId: () => THREAD, + activeTurn: () => TURN, + now: () => 1_000 + }) + const item = activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + + expect(roster.handleItem({ threadId: THREAD, turnId: TURN, item })).toEqual(refusal) + + // The wire redelivers the very same item; nothing about the roster changed, + // so only a cleared suppression state can get the revision out. + refusing = false + expect(roster.handleItem({ threadId: THREAD, turnId: TURN, item })).toEqual({ + accepted: true + }) + // The retry re-appends when the publish was the half that failed; the real + // queue coalesces those two by the group key into one journal write. What + // must not happen is the revision never being published at all. + expect(published).toHaveLength(1) + const body = appended.at(-1)?.body + expect( + body?.kind === 'message' ? body.blocks.filter(isSubagentGroupBlock) : [] + ).toMatchObject([{ agents: [{ id: 'child-1', state: 'working' }] }]) + } + ) + + // The sweep is the last event a group ever gets. A refusal there, left + // unretried, strands the settled roster's final revision — the exact "row + // stays stale forever" this row exists to prevent. + it('republishes the settled roster when the sweep publish was refused', () => { + let refusing = false + const appended: Appended[] = [] + const published: number[] = [] + const roster = new CodexSubagentRoster({ + sink: { + appendItem: () => {}, + appendTombstone: () => {}, + publish: () => {}, + tryAppendItem: (identity, body) => { + appended.push({ identity, body }) + return { accepted: true } + }, + tryPublish: () => { + if (refusing) { + return { accepted: false, reason: 'backpressure' } + } + published.push(1) + return { accepted: true } + } + }, + primaryThreadId: () => THREAD, + activeTurn: () => TURN, + now: () => 1_000 + }) + roster.handleItem({ + threadId: THREAD, + turnId: TURN, + item: activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + }) + const publishedBeforeSweep = published.length + + refusing = true + expect(roster.settleSession()).toEqual({ accepted: false, reason: 'backpressure' }) + + // The retry sweep flips no state — every child already latched — so only a + // cleared suppression state can carry the unverifiable roster out. + refusing = false + expect(roster.settleSession()).toEqual({ accepted: true }) + expect(published.length).toBe(publishedBeforeSweep + 1) + const body = appended.at(-1)?.body + expect(body?.kind === 'message' ? body.blocks.filter(isSubagentGroupBlock) : []).toMatchObject([ + { agents: [{ id: 'child-1', state: 'unverifiable' }] } + ]) + }) + + it('propagates sink backpressure instead of reporting the row as written', () => { + const roster = new CodexSubagentRoster({ + sink: { + appendItem: () => {}, + appendTombstone: () => {}, + publish: () => {}, + tryAppendItem: () => ({ accepted: false, reason: 'backpressure' }), + tryPublish: () => ({ accepted: true }) + }, + primaryThreadId: () => THREAD, + activeTurn: () => TURN + }) + + expect( + roster.handleItem({ + threadId: THREAD, + turnId: TURN, + item: activity({ kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' }) + }) + ).toEqual({ accepted: false, reason: 'backpressure' }) + }) +}) diff --git a/src/main/codex/codex-subagent-roster.ts b/src/main/codex/codex-subagent-roster.ts new file mode 100644 index 00000000000..257fe705764 --- /dev/null +++ b/src/main/codex/codex-subagent-roster.ts @@ -0,0 +1,347 @@ +// The Codex subagent roster: one journal row per spawn group, revised in place. +// +// There is no snapshot to read. `agentsStates` arrived empty in the live probe +// and children get no `thread/started`, so the roster is +// accumulated purely from `subAgentActivity` items — each of which arrives TWICE +// (`item/started` and `item/completed`). Every transition here is therefore +// idempotent, and a terminal state latches: duplicate and out-of-order delivery +// must not resurrect a settled child. +// +// KNOWN LIMITATION: `groups` is process-local and is never seeded from the +// journal, while the row's identity is keyed on the group id alone. So once a +// group leaves the map its row stays, and the next activity item rebuilds that +// row from one child — rewriting N down to one. Two ways in: eviction past +// MAX_CODEX_SUBAGENT_GROUPS, which drops the oldest-inserted group in-process +// even while it is live, and skips the sweep so its children never latch +// `unverifiable`; and a restart on `threadId:outside-turn`, the one group id +// that outlives the process — `thread/resume` is verified to return the same +// thread, and a real turn id is assumed freshly minted per turn. Seeding from +// the journal is the fix. + +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import { + canReplaceSubagentState, + isTerminalSubagentState, + MAX_SUBAGENT_FIELD_CHARS, + subagentGroupFallbackText +} from '../../shared/native-chat-subagent-summary' +import type { NativeChatSubagentEntry } from '../../shared/native-chat-types' +import type { + StructuredAgentSessionEventSink, + StructuredAgentSessionSinkAdmission +} from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { + codexSubagentLabel, + codexSubagentStateForKind, + isCodexRootAgentActivity, + readCodexSubagentActivity, + readCodexThreadTokenTotal +} from './codex-subagent-activity' +import type { CodexThreadItem } from './codex-structured-item-translation' +import { + MAX_CODEX_SUBAGENT_GROUPS, + MAX_CODEX_SUBAGENTS_PER_GROUP, + MAX_CODEX_TOKEN_USAGE_THREADS +} from './codex-structured-journal-limits' + +const ADMITTED: StructuredAgentSessionSinkAdmission = { accepted: true } + +/** The turn a group belongs to when Codex reports activity outside any turn. + * Mirrors the generic-frame bucket name so the two read alike in the journal. */ +const OUTSIDE_TURN = 'outside-turn' + +const UNLABELLED_AGENT = 'subagent' + +type RosterGroup = { + groupId: string + identity: AgentJournalItemIdentity + /** Insertion order is the display order; the map holds the state. */ + entries: Map + /** Times each label has been claimed, so a repeat gets an ordinal suffix. */ + labelCounts: Map + /** Last body written, so an idempotent replay writes no new revision. */ + lastSerialized: string | null +} + +/** Group identity: the parent turn that spawned the children. `agentPath` is a + * tree rooted at the parent thread, so every child of one turn shares a row + * no matter which thread's stream carried its activity item. */ +export function codexSubagentGroupId(threadId: string, turnId: string | null): string { + return `${threadId}:${turnId ?? OUTSIDE_TURN}` +} + +/** Durable journal identity for the group's row — stable across revisions and + * across a restart, so replay finds the same row instead of appending a new one. */ +export function codexSubagentGroupIdentity(groupId: string): AgentJournalItemIdentity { + return { provider: 'orca', clientMessageId: `codex-subagents:${groupId}` } +} + +export type CodexSubagentRosterDeps = { + sink: StructuredAgentSessionEventSink + /** The thread that owns the agent tree; falls back to the event's thread. */ + primaryThreadId: () => string | null + activeTurn: (threadId: string) => string | null + now?: () => number +} + +export class CodexSubagentRoster { + private readonly groups = new Map() + /** Latest reported total per thread, kept regardless of roster membership: a + * usage frame can arrive before the child's first activity item, and filtering + * at receipt would lose it permanently. Children are selected at write time; + * the map itself is LRU-capped in `handleTokenUsage`. */ + private readonly tokensByThread = new Map() + private readonly now: () => number + + constructor(private readonly deps: CodexSubagentRosterDeps) { + this.now = deps.now ?? (() => Date.now()) + } + + /** Consume a `subAgentActivity` item. Returns null when the item is not one. */ + handleItem(input: { + threadId: string + turnId: string | null + item: CodexThreadItem + }): StructuredAgentSessionSinkAdmission | null { + const activity = readCodexSubagentActivity(input.item) + if (!activity) { + return null + } + // The root node is the parent turn itself, not a child it spawned. + if (isCodexRootAgentActivity(activity)) { + return ADMITTED + } + const group = this.groupFor(input.threadId, input.turnId) + const existing = group.entries.get(activity.agentThreadId) + const state = codexSubagentStateForKind(activity.kind) + if (!existing) { + // Rule: the first event for a child may be ANY kind. An `interacted` or + // `completed` with no prior `started` creates the entry in the state its + // kind implies rather than being dropped for lacking a roster row. + if (group.entries.size >= MAX_CODEX_SUBAGENTS_PER_GROUP) { + return ADMITTED + } + const now = this.now() + group.entries.set(activity.agentThreadId, { + id: activity.agentThreadId, + label: this.claimLabel(group, codexSubagentLabel(activity)), + state, + startedAt: now, + ...(isTerminalSubagentState(state) ? { settledAt: now } : {}) + }) + } else if (canReplaceSubagentState(existing.state, state)) { + // A child's own verdict latches. Re-applying the same non-terminal state + // is a no-op, which is what makes the duplicate `item/started` + + // `item/completed` delivery idempotent. `unverifiable` does not latch: a + // child swept when contact was lost can still report what it actually did + // if contact returns. + group.entries.set(activity.agentThreadId, { + ...existing, + state, + ...(isTerminalSubagentState(state) ? { settledAt: this.now() } : {}) + }) + } + return this.write(group) + } + + /** Consume `thread/tokenUsage/updated`. Returns null when the params are not one. */ + handleTokenUsage(params: unknown): StructuredAgentSessionSinkAdmission | null { + const usage = readCodexThreadTokenTotal(params) + if (!usage) { + return null + } + // A running total: the newest frame REPLACES the previous one. Summing + // updates would multiply a single child's usage by its frame count. + // Re-insert so the eviction scan below sees recency: `set` on an existing + // key keeps its original position, which would age out an active thread. + this.tokensByThread.delete(usage.threadId) + this.tokensByThread.set(usage.threadId, usage.totalTokens) + while (this.tokensByThread.size > MAX_CODEX_TOKEN_USAGE_THREADS) { + const oldest = this.tokensByThread.keys().next().value + if (typeof oldest !== 'string') { + break + } + this.tokensByThread.delete(oldest) + } + for (const group of this.groups.values()) { + if (!group.entries.has(usage.threadId)) { + continue + } + const admission = this.write(group) + if (!admission.accepted) { + return admission + } + } + return ADMITTED + } + + /** + * The provider is gone, so any child still reported as working will never be + * settled by an event: it becomes `unverifiable` — contact was lost, which is + * NOT evidence the child exited. + * + * This is the ONLY sweep. A turn ending is not one: `spawn_agent` children + * routinely outlive their turn and keep reporting into the same group. + */ + settleSession(): StructuredAgentSessionSinkAdmission { + for (const group of this.groups.values()) { + const admission = this.sweep(group) + if (!admission.accepted) { + return admission + } + } + return ADMITTED + } + + dispose(): void { + this.groups.clear() + this.tokensByThread.clear() + } + + private sweep(group: RosterGroup | undefined): StructuredAgentSessionSinkAdmission { + if (!group) { + return ADMITTED + } + let changed = false + for (const [id, entry] of group.entries) { + if (isTerminalSubagentState(entry.state)) { + continue + } + group.entries.set(id, { ...entry, state: 'unverifiable', settledAt: this.now() }) + changed = true + } + // A null `lastSerialized` means the previous write was refused part-way, so + // the settled roster's last revision is queued but never published. Nothing + // is guaranteed to write this group again, so retry here even when the sweep + // itself changed nothing. + return changed || group.lastSerialized === null ? this.write(group) : ADMITTED + } + + private groupFor(threadId: string, turnId: string | null): RosterGroup { + const ownerThreadId = this.deps.primaryThreadId() ?? threadId + const ownerTurnId = + ownerThreadId === threadId ? turnId : (this.deps.activeTurn(ownerThreadId) ?? turnId) + const groupId = codexSubagentGroupId(ownerThreadId, ownerTurnId) + const existing = this.groups.get(groupId) + if (existing) { + return existing + } + const group: RosterGroup = { + groupId, + identity: codexSubagentGroupIdentity(groupId), + entries: new Map(), + labelCounts: new Map(), + lastSerialized: null + } + this.groups.set(groupId, group) + while (this.groups.size > MAX_CODEX_SUBAGENT_GROUPS) { + const oldest = this.groups.keys().next().value + if (typeof oldest !== 'string' || oldest === groupId) { + break + } + this.groups.delete(oldest) + } + return group + } + + /** Two children can share a trailing path segment; the ordinal keeps their + * rows apart without inventing a name the provider never sent. */ + private claimLabel(group: RosterGroup, label: string | null): string { + const base = label ?? UNLABELLED_AGENT + const seen = group.labelCounts.get(base) ?? 0 + group.labelCounts.set(base, seen + 1) + return seen === 0 ? base : `${base} ${seen + 1}` + } + + private write(group: RosterGroup): StructuredAgentSessionSinkAdmission { + const agents = [...group.entries].map(([id, entry]) => { + const tokens = this.tokensByThread.get(id) + if (typeof tokens !== 'number' || tokens === entry.tokens) { + return entry + } + // Persisted, not merely read: the thread map is LRU-capped, and reading it + // afresh each write would retract a count this row has already shown. + const merged = { ...entry, tokens } + group.entries.set(id, merged) + return merged + }) + const body = codexSubagentGroupBody(group.groupId, agents) + const serialized = JSON.stringify(body) + if (serialized === group.lastSerialized) { + // Nothing changed — a duplicate delivery must not burn a revision. + return ADMITTED + } + group.lastSerialized = serialized + // The append coalesces per group so a burst collapses to the latest roster. + // The publish must NOT reuse that key: the queue coalesces by key alone, + // with no op-kind check, so a publish carrying it would splice out the + // still-queued append and the row would never reach the journal. + const options = { coalescingKey: `codex-subagents:${group.groupId}` } + const admission = this.deps.sink.tryAppendItem + ? this.deps.sink.tryAppendItem(group.identity, body, options) + : (this.deps.sink.appendItem(group.identity, body, options), ADMITTED) + if (!admission.accepted) { + group.lastSerialized = null + return admission + } + const published = this.deps.sink.tryPublish + ? this.deps.sink.tryPublish() + : (this.deps.sink.publish(), ADMITTED) + if (!published.accepted) { + // Symmetric with the append refusal above: the suppression state may only + // advance once the revision is both queued AND published. Left set, an + // identical replay short-circuits and the last revision of a settled + // roster stays queued but never reaches the renderer. + group.lastSerialized = null + } + return published + } +} + +/** The roster row: the structured block plus the plain sentence an older client + * renders in its place. A message whose only block is the new variant would + * reach such a client with nothing it can draw. */ +export function codexSubagentGroupBody( + groupId: string, + agents: readonly NativeChatSubagentEntry[] +): AgentJournalItemBody { + const bounded = agents.map((agent, index) => ({ + ...agent, + id: boundSubagentField(agent.id, index), + label: boundSubagentField(agent.label, index) + })) + return { + kind: 'message', + role: 'system', + blocks: [ + { type: 'text', text: subagentGroupFallbackText(bounded) }, + { type: 'subagent-group', groupId, agents: bounded } + ] + } +} + +/** `id` and `label` are provider strings, so they take the bound both readers of + * this row already clip them to. A plain length check, not the tool-output + * bound: that one digests the whole value before it checks the length, and this + * runs twice per child on every streamed token-usage frame. + * + * A clip is not identity-preserving, so a clipped value carries the child's + * index: two ids sharing a long prefix collapse to one React key, and + * `claimLabel` writes its ordinal at the very tail the clip removes. The index + * is reserved out of the bound, not appended to it, because both readers + * re-clip to the same cap and would cut a suffix that overflowed it. */ +function boundSubagentField(value: string, index: number): string { + if (value.length <= MAX_SUBAGENT_FIELD_CHARS) { + return value + } + const suffix = `…~${index}` + const keep = MAX_SUBAGENT_FIELD_CHARS - suffix.length + // Slicing UTF-16 units can split a surrogate pair; a lone surrogate is + // malformed in a durable row and lossy through any non-JSON UTF-8 hop. + const last = value.charCodeAt(keep - 1) + const end = last >= 0xd800 && last <= 0xdbff ? keep - 1 : keep + return `${value.slice(0, end)}${suffix}` +} diff --git a/src/main/native-chat/agent-session-journal/journal-store-open.ts b/src/main/native-chat/agent-session-journal/journal-store-open.ts index 721e5f4ba7f..7b5b6d0dff8 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-open.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-open.ts @@ -1,4 +1,8 @@ import { mkdir } from 'node:fs/promises' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../../shared/agent-session-journal-types' import type { AgentType } from '../../../shared/agent-status-types' import { findJournalFileFormatRemnant, @@ -6,6 +10,7 @@ import { } from './journal-file-format-remnant' import type { JournalLoad } from './journal-open' import { journalRepairDisclosure, type JournalRepairDisclosure } from './journal-repair-disclosure' +import { staleSubagentRosterRevisions } from './journal-subagent-liveness' /** What any of this file's disclosures hands the store — a repair's, or the * pre-SQLite notice's. Same shape, and neither is only a repair. */ @@ -36,9 +41,9 @@ export async function openJournalStoreState(input: { adopt: (loaded: JournalLoad) => void /** Republishes an anchor row for an epoch a repair emptied. */ publishRepairEpoch: () => void - appendDisclosure: ( - identity: JournalRepairDisclosure['identity'], - body: JournalRepairDisclosure['body'], + appendItem: ( + identity: AgentJournalItemIdentity, + body: AgentJournalItemBody, fence: number ) => Promise agent: AgentType @@ -68,8 +73,9 @@ export async function openJournalStoreState(input: { } if (input.malformedRows() > 0 && !input.readOnly()) { const disclosure = journalRepairDisclosure({ malformedRows: input.malformedRows() }) - await input.appendDisclosure(disclosure.identity, disclosure.body, input.highestFence()) + await input.appendItem(disclosure.identity, disclosure.body, input.highestFence()) } + await settleStaleSubagentRosters(input, loaded) // Founding the epoch and appending the row are two transactions, and a // committed epoch sends every later open down this branch instead. Anything // that interrupts between them — a quit during startup restore, a failed @@ -92,7 +98,7 @@ export async function openJournalStoreState(input: { async function discloseFileFormatRemnant(input: { journalDir: string agent: AgentType - appendDisclosure: ( + appendItem: ( identity: JournalDisclosure['identity'], body: JournalDisclosure['body'], fence: number @@ -108,5 +114,32 @@ async function discloseFileFormatRemnant(input: { return } const disclosure = journalFileFormatRemnantDisclosure({ transcriptPath, agent: input.agent }) - await input.appendDisclosure(disclosure.identity, disclosure.body, input.highestFence()) + await input.appendItem(disclosure.identity, disclosure.body, input.highestFence()) +} + +/** + * Retires a `working` subagent roster the previous host never got to settle. + * + * Skipped on a corrupt load: that journal is still owed a rebuild from provider + * history, and content written past the repair's free sequence retires the + * demand for it. + */ +async function settleStaleSubagentRosters( + input: { + appendItem: ( + identity: AgentJournalItemIdentity, + body: AgentJournalItemBody, + fence: number + ) => Promise + highestFence: () => number + readOnly: () => boolean + }, + loaded: JournalLoad +): Promise { + if (input.readOnly() || loaded.corrupt) { + return + } + for (const revision of staleSubagentRosterRevisions(loaded.state.items.values())) { + await input.appendItem(revision.identity, revision.body, input.highestFence()) + } } diff --git a/src/main/native-chat/agent-session-journal/journal-store-restore.ts b/src/main/native-chat/agent-session-journal/journal-store-restore.ts index 3a5d3c7ac6e..fc69dd339d8 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-restore.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-restore.ts @@ -39,8 +39,7 @@ export function restoreJournalStore( publishRepairEpoch: () => collaborators.epochController.start('unreconcilable_prefix', host.state().highestFence), adopt: host.adopt, - appendDisclosure: (identity, body, fence) => - host.journal().appendItem(identity, body, { fence }), + appendItem: (identity, body, fence) => host.journal().appendItem(identity, body, { fence }), agent: host.identity.agent, highestFence: () => host.state().highestFence, malformedRows: host.malformedRows, diff --git a/src/main/native-chat/agent-session-journal/journal-subagent-liveness.test.ts b/src/main/native-chat/agent-session-journal/journal-subagent-liveness.test.ts new file mode 100644 index 00000000000..9d6887de61e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-subagent-liveness.test.ts @@ -0,0 +1,202 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { + AgentJournalRenderItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { isSubagentGroupBlock } from '../../../shared/native-chat-types' +import type { NativeChatSubagentEntry } from '../../../shared/native-chat-types' +import { + codexSubagentGroupBody, + codexSubagentGroupIdentity +} from '../../codex/codex-subagent-roster' +import type { openAgentSessionJournal } from './journal-store-factory' +import { createTrackedJournalOpener } from './journal-store-test-open' +import { staleSubagentRosterRevisions } from './journal-subagent-liveness' + +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: { kind: 'codex', threadId: 'thread-1' } +} + +const GROUP_ID = 'thread-1:turn-1' + +let root: string +let clock = 1_000 + +function tick(): number { + clock += 1 + return clock +} + +const journals = createTrackedJournalOpener() + +async function open(overrides: Partial[0]> = {}) { + return journals.open({ + identity: IDENTITY, + journalDir: root, + now: tick, + mintEpoch: () => `epoch-${clock}`, + ...overrides + }) +} + +/** The row as the producer writes it: the structured block plus its twin. */ +function rosterRow(agents: NativeChatSubagentEntry[]) { + return { + identity: codexSubagentGroupIdentity(GROUP_ID), + body: codexSubagentGroupBody(GROUP_ID, agents) + } +} + +function renderItem(agents: NativeChatSubagentEntry[]): AgentJournalRenderItem { + const row = rosterRow(agents) + return { + itemId: agentJournalItemKey(row.identity), + revision: 1, + body: row.body, + sequence: 2, + observedAt: 1 + } +} + +function rosterOf(body: AgentJournalRenderItem['body']): NativeChatSubagentEntry[] { + return body.kind === 'message' ? (body.blocks.find(isSubagentGroupBlock)?.agents ?? []) : [] +} + +function twinOf(body: AgentJournalRenderItem['body']): string | undefined { + return body.kind === 'message' + ? body.blocks.find((block) => block.type === 'text')?.text + : undefined +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-subagents-')) + clock = 1_000 +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +describe('staleSubagentRosterRevisions', () => { + it('settles a child the previous host left working, and moves the twin with it', () => { + const revisions = staleSubagentRosterRevisions([ + renderItem([ + { id: 'a', label: 'read_readme', state: 'working', startedAt: 10 }, + { id: 'b', label: 'read_package', state: 'completed', startedAt: 10, settledAt: 20 } + ]) + ]) + + expect(revisions).toHaveLength(1) + expect(rosterOf(revisions[0]!.body)).toMatchObject([ + { id: 'a', state: 'unverifiable' }, + { id: 'b', state: 'completed' } + ]) + // Mobile reads only this sentence, so it may not go on saying `Kicked off`. + expect(twinOf(revisions[0]!.body)).toBe('Ran 2 subagents (1 unverifiable)') + }) + + // The child stopped being observable at an unknown moment. A stamp taken now + // would report the time the app was down as how long the child ran. + it('records no terminal timestamp for a child whose run length is unknown', () => { + const revisions = staleSubagentRosterRevisions([ + renderItem([{ id: 'a', label: 'read', state: 'working', startedAt: 10 }]) + ]) + + expect(rosterOf(revisions[0]!.body)[0]).not.toHaveProperty('settledAt') + }) + + it('owes nothing for a roster whose children all settled', () => { + expect( + staleSubagentRosterRevisions([ + renderItem([{ id: 'a', label: 'read', state: 'completed', settledAt: 20 }]) + ]) + ).toEqual([]) + }) + + it('leaves rows that carry no roster alone', () => { + expect( + staleSubagentRosterRevisions([ + { + itemId: 'orca:plain', + revision: 1, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'hi' }] }, + sequence: 2, + observedAt: 1 + } + ]) + ).toEqual([]) + }) + + // Appending under a fresh identity would add a second row rather than revise + // the one on disk, so an unaddressable key is left exactly as it is. + it('skips a row whose key cannot be parsed back to its identity', () => { + expect( + staleSubagentRosterRevisions([ + { ...renderItem([{ id: 'a', label: 'r', state: 'working' }]), itemId: 'not-a-key' } + ]) + ).toEqual([]) + }) +}) + +describe('journal reopen after the writing host is gone', () => { + it('settles a persisted working roster to unverifiable, while the live row still reads working', async () => { + const live = await open() + const row = rosterRow([ + { id: 'a', label: 'read_readme', state: 'working', startedAt: 10 }, + { id: 'b', label: 'read_package', state: 'working', startedAt: 10 } + ]) + await live.appendItem(row.identity, row.body, { fence: 0 }) + + // Still the writing host: it can see the children, so the row says so. + const beforeRestart = live.snapshot().items.at(-1)! + expect(rosterOf(beforeRestart.body)).toMatchObject([{ state: 'working' }, { state: 'working' }]) + expect(twinOf(beforeRestart.body)).toBe('Kicked off 2 subagents') + + // The host dies without ever settling them — no `ended`, so no session sweep. + await live.close() + + const reopened = await open() + const afterRestart = reopened.snapshot().items.at(-1)! + expect(afterRestart.itemId).toBe(beforeRestart.itemId) + expect(rosterOf(afterRestart.body)).toMatchObject([ + { id: 'a', state: 'unverifiable' }, + { id: 'b', state: 'unverifiable' } + ]) + expect(twinOf(afterRestart.body)).toBe('Ran 2 subagents (2 unverifiable)') + }) + + it('revises the row in place rather than appending a second one', async () => { + const live = await open() + const row = rosterRow([{ id: 'a', label: 'read', state: 'working', startedAt: 10 }]) + await live.appendItem(row.identity, row.body, { fence: 0 }) + const before = live.snapshot().items.length + await live.close() + + const reopened = await open() + expect(reopened.snapshot().items).toHaveLength(before) + expect(reopened.snapshot().items.at(-1)?.revision).toBe(2) + }) + + it('writes nothing on a second reopen once every child is settled', async () => { + const live = await open() + const row = rosterRow([{ id: 'a', label: 'read', state: 'working', startedAt: 10 }]) + await live.appendItem(row.identity, row.body, { fence: 0 }) + await live.close() + + const once = await open() + const revision = once.snapshot().items.at(-1)?.revision + await once.close() + + const twice = await open() + expect(twice.snapshot().items.at(-1)?.revision).toBe(revision) + }) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-subagent-liveness.ts b/src/main/native-chat/agent-session-journal/journal-subagent-liveness.ts new file mode 100644 index 00000000000..9b2724e9d1d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-subagent-liveness.ts @@ -0,0 +1,101 @@ +// A roster row left claiming live children by a host that is gone. +// +// The writing host revises its `subagent-group` rows in place while it can see +// the children, and sweeps whatever is still `working` when the provider goes +// away. A host that DIED — crash, quit, force-restart — does neither: its last +// revision goes on saying `working`, and nothing replays those children, so no +// later event can ever settle them. Opening the journal is the one moment a new +// host can state the truth about the old one: contact was lost. That is +// `unverifiable`, never a synthesized exit — see +// `docs/reference/ssh-execution-boundary.md`. +// +// Reconciles JOURNAL ROWS, not roster state: nothing here seeds the producer's +// in-process group map, so the roster's known limitation is untouched. + +import { + agentJournalItemKey, + parseAgentJournalItemKey +} from '../../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentJournalRenderItem +} from '../../../shared/agent-session-journal-types' +import { + isSubagentGroupFallbackText, + normalizeSubagentState, + subagentGroupFallbackText +} from '../../../shared/native-chat-subagent-summary' +import { + isSubagentGroupBlock, + type NativeChatBlock, + type NativeChatSubagentGroupBlock +} from '../../../shared/native-chat-types' + +export type JournalSubagentLivenessRevision = { + identity: AgentJournalItemIdentity + body: AgentJournalItemBody +} + +/** The revisions a reopened journal owes: one per row still claiming a live + * child. Empty — the common case — when nothing was left mid-flight. */ +export function staleSubagentRosterRevisions( + items: Iterable +): JournalSubagentLivenessRevision[] { + const revisions: JournalSubagentLivenessRevision[] = [] + for (const item of items) { + const body = item.body + if (body.kind !== 'message' || !body.blocks.some(hasWorkingChild)) { + continue + } + // A key that will not parse cannot be re-addressed, and appending under a + // fresh identity would duplicate the row rather than revise it. + const identity = parseAgentJournalItemKey(item.itemId) + if (!identity || agentJournalItemKey(identity) !== item.itemId) { + continue + } + revisions.push({ identity, body: { ...body, blocks: settleBlocks(body.blocks) } }) + } + return revisions +} + +function hasWorkingChild(block: NativeChatBlock): boolean { + return ( + isSubagentGroupBlock(block) && + block.agents.some((agent) => normalizeSubagentState(agent.state) === 'working') + ) +} + +/** No `settledAt`: the child stopped being observable at an unknown moment, and + * stamping the reopen would report the time the app was down as how long it + * ran. Readers already draw an unverifiable child with no stamp as having no + * known run length. */ +function settleBlocks(blocks: readonly NativeChatBlock[]): NativeChatBlock[] { + const settled = blocks.map((block) => + hasWorkingChild(block) ? settleGroup(block as NativeChatSubagentGroupBlock) : block + ) + const rosters = settled.filter(isSubagentGroupBlock) + const only = rosters.length === 1 ? rosters[0] : undefined + if (!only) { + return settled + } + // The plain-text twin is all a client without the block type ever shows, so it + // has to move with the block or the two would disagree about the same row. + const twin = subagentGroupFallbackText(only.agents) + return settled.map((block) => + block.type === 'text' && isSubagentGroupFallbackText(block.text) + ? { ...block, text: twin } + : block + ) +} + +function settleGroup(block: NativeChatSubagentGroupBlock): NativeChatSubagentGroupBlock { + return { + ...block, + agents: block.agents.map((agent) => + normalizeSubagentState(agent.state) === 'working' + ? { ...agent, state: 'unverifiable' as const } + : agent + ) + } +} diff --git a/src/main/native-chat/agent-session-wire/provider-frame-activity.test.ts b/src/main/native-chat/agent-session-wire/provider-frame-activity.test.ts index 79d9e4205cf..40504873282 100644 --- a/src/main/native-chat/agent-session-wire/provider-frame-activity.test.ts +++ b/src/main/native-chat/agent-session-wire/provider-frame-activity.test.ts @@ -28,6 +28,16 @@ describe('provider frame activity', () => { expect(codexProviderFrameActivity('item/reasoning/summaryPartAdded', {})).toBeNull() }) + it('names a fan-out from either Codex item type that reports one', () => { + for (const type of ['collabAgentToolCall', 'subAgentActivity']) { + expect( + codexProviderFrameActivity('item/started', { + item: { type, kind: 'started', agentThreadId: 'child-1', agentPath: '/root/read' } + }) + ).toBe('Coordinating with another agent') + } + }) + it('uses Claude descriptions and safe semantic status without exposing tool labels', () => { expect( claudeProviderFrameActivity('message:system:task_started', { diff --git a/src/main/native-chat/agent-session-wire/provider-frame-disposition.test.ts b/src/main/native-chat/agent-session-wire/provider-frame-disposition.test.ts index 9860aaa81d8..d4726a9b602 100644 --- a/src/main/native-chat/agent-session-wire/provider-frame-disposition.test.ts +++ b/src/main/native-chat/agent-session-wire/provider-frame-disposition.test.ts @@ -6,6 +6,7 @@ import { isDeltaShapedProviderFrameKind, PROVIDER_FRAME_CLASSIFICATIONS } from './provider-frame-disposition' +import { unhandledProviderFrameJournalItem } from './unhandled-provider-frame' describe('provider frame classification catalog', () => { it('classifies every pinned Codex app-server notification method', () => { @@ -124,7 +125,7 @@ describe('provider frame classification catalog', () => { ) }) - it('keeps subagent items visible — the only evidence a spawned agent is working', () => { + it('suppresses subAgentActivity once the roster renders it, but never collabAgentToolCall', () => { expect( classifyProviderFrame('codex', 'item:subAgentActivity', { id: 'a-1', @@ -132,7 +133,9 @@ describe('provider frame classification catalog', () => { agentThreadId: 'thread-child', agentPath: '/root/list_directory' }) - ).toBe('timeline-substantive') + // The spawn-group roster row renders this now, so a raw gray row beside it + // would duplicate it. Suppressing it was gated on that renderer existing. + ).toBe('status-chrome') expect( classifyProviderFrame('codex', 'item:collabAgentToolCall', { id: 'c-1', @@ -161,3 +164,45 @@ describe('provider frame classification catalog', () => { } }) }) + +describe('codex subagent item disposition', () => { + it('keeps subagent lifecycle out of the transcript now that it renders as a roster row', () => { + expect( + classifyProviderFrame('codex', 'item:subAgentActivity', { + type: 'subAgentActivity', + kind: 'started', + agentThreadId: 'child-1', + agentPath: '/root/read' + }) + ).toBe('status-chrome') + }) + + it('leaves collab tool calls substantive — they may be the only subagent signal', () => { + // A session that reports no `subAgentActivity` gets no roster row, so + // suppressing this too would render its fan-out blank. + expect( + classifyProviderFrame('codex', 'item:collabAgentToolCall', { + type: 'collabAgentToolCall', + agentsStates: {} + }) + ).not.toBe('status-chrome') + }) + + it('journals no fallback row for subagent activity', () => { + expect( + unhandledProviderFrameJournalItem('codex', 'item:subAgentActivity', { + kind: 'completed', + agentThreadId: 'child-1' + }) + ).toBeNull() + }) + + it('still surfaces a subagent frame that reports a failure', () => { + expect( + classifyProviderFrame('codex', 'item:collabAgentToolCall', { + type: 'collabAgentToolCall', + status: 'failed' + }) + ).toBe('error-surface') + }) +}) diff --git a/src/main/native-chat/agent-session-wire/provider-frame-disposition.ts b/src/main/native-chat/agent-session-wire/provider-frame-disposition.ts index f05f4cd4c6c..35223a1971f 100644 --- a/src/main/native-chat/agent-session-wire/provider-frame-disposition.ts +++ b/src/main/native-chat/agent-session-wire/provider-frame-disposition.ts @@ -1,4 +1,5 @@ import type { CodexAppServerNotificationMethod } from '../../codex/codex-app-server-notification-schema' +import { CODEX_SUBAGENT_ITEM_TYPE } from '../../codex/codex-subagent-activity' import type { ClaudeStreamJsonFrameKind } from './claude-stream-json-frame-schema' export type ProviderFrameClassification = @@ -198,10 +199,21 @@ const CODEX_ITEM_CLASSIFICATIONS: Record = // The `thread/compacted` notification is already chrome; its item form is the // same event and must not read as a mysterious opcode row. contextCompaction: 'status-chrome', + // Subagent lifecycle renders as the spawn-group roster row, so its raw items + // must not print a gray `codex · item:` row beside it. The live + // notification path intercepts them before this catalog is reached; + // `restoreThread` replays them straight through `items.handle`, which is where + // the classification earns its keep. + // + // `collabAgentToolCall` is deliberately NOT suppressed with it. Nothing + // guarantees a session reports subagent work as `subAgentActivity` at all; one + // that only ever emits the collab tool call gets no roster row, and suppressing + // that too would leave its fan-out showing nothing. + [CODEX_SUBAGENT_ITEM_TYPE]: 'status-chrome', // `{id, durationMs}` and nothing else — Codex's own transcript renders it as // nothing at all. Every other item type this build does not model carries text - // a user would want (review output, an image path, hook prompt text, subagent - // progress), so those keep their visible fallback row. + // a user would want (review output, an image path, hook prompt text), so those + // keep their visible fallback row. sleep: 'status-chrome' } diff --git a/src/main/runtime/orchestration/worker-transcript-payload.test.ts b/src/main/runtime/orchestration/worker-transcript-payload.test.ts index 7899a63fb73..f47a46605e1 100644 --- a/src/main/runtime/orchestration/worker-transcript-payload.test.ts +++ b/src/main/runtime/orchestration/worker-transcript-payload.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { MAX_CODEX_SUBAGENTS_PER_GROUP } from '../../codex/codex-structured-journal-limits' import { boundWorkerTranscriptMessages, redactWorkerTerminalLines @@ -57,6 +58,80 @@ describe('worker transcript wire bounds', () => { ) }) + // The bound matches the producer's per-group cap, so nothing this build writes + // is clipped here. It stays because the journal schema declares no maximum and + // a remote host may run a build with a larger one — the transport's own + // invariant that no single block is huge. + it('caps and redacts a spawn group the way every other collection is capped', () => { + const result = boundWorkerTranscriptMessages([ + { + id: 'message-roster', + role: 'system', + timestamp: null, + source: 'transcript', + blocks: [ + { + type: 'subagent-group', + groupId: 'thread-1:turn-1', + agents: Array.from({ length: 80 }, (_unused, index) => ({ + id: `child-${index}`, + label: index === 0 ? `dcap_${'A'.repeat(24)}` : 'read', + state: 'working' as const + })) + } + ] + } + ]) + + const block = result.messages[0]?.blocks[0] + expect(block?.type).toBe('subagent-group') + expect(block?.type === 'subagent-group' ? block.agents : []).toHaveLength( + MAX_CODEX_SUBAGENTS_PER_GROUP + ) + expect(JSON.stringify(result.messages)).not.toContain('dcap_') + expect(result.limited).toBe(true) + expect(result.warnings).toEqual( + expect.arrayContaining([ + 'Some subagents were omitted from oversized spawn groups.', + 'Dispatch capability tokens were redacted from transcript output.' + ]) + ) + }) + + it('bounds a spawn-group state a newer build wrote as an oversized open string', () => { + const result = boundWorkerTranscriptMessages([ + { + id: 'message-roster-state', + role: 'system', + timestamp: null, + source: 'transcript', + blocks: [ + { + type: 'subagent-group', + groupId: 'g'.repeat(900), + agents: [ + { + id: 'i'.repeat(900), + label: 'l'.repeat(900), + state: 's'.repeat(900) as 'working' + } + ] + } + ] + } + ]) + + const block = result.messages[0]?.blocks[0] + const agent = block?.type === 'subagent-group' ? block.agents[0] : undefined + expect(block?.type === 'subagent-group' ? block.groupId.length : 0).toBe(512) + expect(agent?.id.length).toBe(512) + expect(agent?.label.length).toBe(512) + // A clipped state names no state any build knows, which is what + // `unverifiable` records — a 512-character fragment is not a state at all. + expect(agent?.state).toBe('unverifiable') + expect(result.limited).toBe(true) + }) + it('keeps complete bounded messages unlimited', () => { const result = boundWorkerTranscriptMessages([ { diff --git a/src/main/runtime/orchestration/worker-transcript-payload.ts b/src/main/runtime/orchestration/worker-transcript-payload.ts index bcfc7cb0b75..f9d83e20c62 100644 --- a/src/main/runtime/orchestration/worker-transcript-payload.ts +++ b/src/main/runtime/orchestration/worker-transcript-payload.ts @@ -1,5 +1,10 @@ import { createHash } from 'node:crypto' -import type { NativeChatBlock, NativeChatMessage } from '../../../shared/native-chat-types' +import { normalizeSubagentState } from '../../../shared/native-chat-subagent-summary' +import type { + NativeChatBlock, + NativeChatMessage, + NativeChatSubagentState +} from '../../../shared/native-chat-types' export const DEFAULT_WORKER_TRANSCRIPT_MESSAGE_LIMIT = 40 export const MAX_WORKER_TRANSCRIPT_MESSAGE_LIMIT = 50 @@ -7,6 +12,14 @@ const MAX_WORKER_TRANSCRIPT_BLOCKS = 6 const MAX_WORKER_TRANSCRIPT_BLOCK_CHARS = 1_200 const MAX_WORKER_TRANSCRIPT_INPUT_ITEMS = 20 const MAX_WORKER_TRANSCRIPT_INPUT_NODES = 100 +// Matches the producer's per-group cap, so no group this build writes is clipped +// here. The bound stays because the journal schema declares no maximum and a +// remote host may run a build with a larger one. +const MAX_WORKER_TRANSCRIPT_SUBAGENTS = 64 +// Message ids, turn ids, tool-call names and image urls, not only roster fields. +// Equal to `MAX_SUBAGENT_FIELD_CHARS` today, kept a separate literal so a +// roster-motivated change to that cap cannot silently move this one. +const MAX_WORKER_TRANSCRIPT_METADATA_CHARS = 512 const MAX_WORKER_TRANSCRIPT_RESPONSE_BYTES = 512 * 1024 const TRUNCATION_MARKER = '\n… (truncated)' const DISPATCH_CAPABILITY_PATTERN = /\bdcap_[A-Za-z0-9_-]{20,}\b/g @@ -128,6 +141,24 @@ function boundBlock(block: NativeChatBlock, state: TranscriptBoundState): Native input: boundToolInput(block.input, budget, 0, state) } } + if (block.type === 'subagent-group') { + const agents = block.agents.slice(0, MAX_WORKER_TRANSCRIPT_SUBAGENTS) + if (agents.length < block.agents.length) { + markClipped(state, 'Some subagents were omitted from oversized spawn groups.') + } + // Labels, ids and states come from provider-supplied strings, so they get the + // same redaction and clipping every other piece of transcript metadata gets. + return { + ...block, + groupId: clipMetadata(block.groupId, state), + agents: agents.map((agent) => ({ + ...agent, + id: clipMetadata(agent.id, state), + label: clipMetadata(agent.label, state), + state: clipSubagentState(agent.state, state) + })) + } + } if (block.path || (block.url && isLocalFileLocator(block.url))) { markClipped(state, 'Local image paths were omitted from transcript output.') return { @@ -165,11 +196,22 @@ function isLocalFileLocator(value: string): boolean { function clipMetadata(value: string, state: TranscriptBoundState): string { const redacted = redactSensitiveText(value, state.warnings) - if (redacted.length <= 512) { + if (redacted.length <= MAX_WORKER_TRANSCRIPT_METADATA_CHARS) { return redacted } markClipped(state, 'Oversized transcript metadata was clipped.') - return redacted.slice(0, 512) + return redacted.slice(0, MAX_WORKER_TRANSCRIPT_METADATA_CHARS) +} + +/** `state` is an open string on the wire, so it takes the same bound. A value + * that had to be redacted or clipped names no state any build knows, which is + * exactly what `unverifiable` records. */ +function clipSubagentState( + value: NativeChatSubagentState, + state: TranscriptBoundState +): NativeChatSubagentState { + const clipped = clipMetadata(value, state) + return clipped === value ? value : normalizeSubagentState(clipped) } function clipText(value: string, state: TranscriptBoundState): string { diff --git a/src/main/runtime/rpc/methods/native-chat-rpc-block-sanitize.ts b/src/main/runtime/rpc/methods/native-chat-rpc-block-sanitize.ts new file mode 100644 index 00000000000..fc19273d5ca --- /dev/null +++ b/src/main/runtime/rpc/methods/native-chat-rpc-block-sanitize.ts @@ -0,0 +1,132 @@ +import { + MAX_SUBAGENT_FIELD_CHARS, + normalizeSubagentState +} from '../../../../shared/native-chat-subagent-summary' +import type { NativeChatBlock, NativeChatSubagentState } from '../../../../shared/native-chat-types' +import type { RpcContext } from '../core' +import { sanitizeNativeChatRpcImageBlock } from './native-chat-rpc-image-block' + +// Why: the mobile-only payload diet. Inline image bytes are kept off every RPC +// transport; everything below that only applies to `mobile` clients, whose +// renderer previews block bodies rather than showing them whole. + +// Why: a single tool result (a big file read, a long diff) can be hundreds of KB. +// The mobile view only previews tool block bodies, so truncate them on the wire +// to keep the payload small; the marker tells the user content was clipped. +const MOBILE_BLOCK_CHAR_CAP = 4000 +// Why: text blocks are the message body itself, rendered in full by the chat +// view — a preview-sized cap cut long assistant replies mid-sentence with no way +// to read on (STA-3230). Keep only a generous safety ceiling: a transcript +// record can legally reach 2MB, and shipping that much markdown in one block +// would freeze the phone. +const MOBILE_TEXT_BLOCK_CHAR_CAP = 64_000 +const MOBILE_TOOL_INPUT_ITEMS_CAP = 20 +const MOBILE_TOOL_INPUT_NODE_CAP = 100 +// Why: a spawn group's roster is metadata, not a body — provider-supplied agent +// paths and an open-string lifecycle whose schema declares no maximum, so a +// journal from a newer build can carry more children and longer strings than +// this build ever writes. +const MOBILE_SUBAGENT_CAP = 64 +const TRUNCATION_MARKER = '\n… (truncated)' + +function clip(text: string, cap: number): string { + return text.length > cap ? text.slice(0, cap) + TRUNCATION_MARKER : text +} + +export function sanitizeNativeChatRpcBlock( + block: NativeChatBlock, + clientKind: RpcContext['clientKind'] +): NativeChatBlock { + if (block.type === 'image-ref') { + return sanitizeNativeChatRpcImageBlock(block) + } + if (clientKind !== 'mobile') { + return block + } + if (block.type === 'text') { + return block.text.length > MOBILE_TEXT_BLOCK_CHAR_CAP + ? { ...block, text: clip(block.text, MOBILE_TEXT_BLOCK_CHAR_CAP) } + : block + } + if (block.type === 'tool-result') { + return block.output.length > MOBILE_BLOCK_CHAR_CAP + ? { ...block, output: clip(block.output, MOBILE_BLOCK_CHAR_CAP) } + : block + } + if (block.type === 'tool-call') { + const budget = { remaining: MOBILE_BLOCK_CHAR_CAP, nodes: MOBILE_TOOL_INPUT_NODE_CAP } + return { ...block, input: sanitizeToolInput(block.input, budget, 0) } + } + if (block.type === 'subagent-group') { + return { + ...block, + groupId: clip(block.groupId, MAX_SUBAGENT_FIELD_CHARS), + agents: block.agents.slice(0, MOBILE_SUBAGENT_CAP).map((agent) => ({ + ...agent, + id: clip(agent.id, MAX_SUBAGENT_FIELD_CHARS), + label: clip(agent.label, MAX_SUBAGENT_FIELD_CHARS), + state: clipSubagentState(agent.state) + })) + } + } + return block +} + +/** A state too long to be one this build knows names no state at all, which is + * what `unverifiable` records — clipping it would ship a truncated word. */ +function clipSubagentState(value: NativeChatSubagentState): NativeChatSubagentState { + return value.length > MAX_SUBAGENT_FIELD_CHARS ? normalizeSubagentState(value) : value +} + +function sanitizeToolInput( + value: unknown, + budget: { remaining: number; nodes: number }, + depth: number +): unknown { + budget.nodes-- + if (budget.nodes < 0 || budget.remaining <= 0) { + return '… (truncated)' + } + if (typeof value === 'string') { + const length = Math.min(value.length, budget.remaining) + budget.remaining -= length + return length < value.length ? `${value.slice(0, length)}… (truncated)` : value + } + if (!value || typeof value !== 'object' || depth >= 5) { + return value && typeof value === 'object' ? '… (truncated)' : value + } + if (Array.isArray(value)) { + const result = value + .slice(0, MOBILE_TOOL_INPUT_ITEMS_CAP) + .map((item) => sanitizeToolInput(item, budget, depth + 1)) + if (value.length > MOBILE_TOOL_INPUT_ITEMS_CAP) { + result.push('… (truncated)') + } + return result + } + const result: Record = {} + let count = 0 + for (const key in value) { + if (!Object.hasOwn(value, key)) { + continue + } + if (count >= MOBILE_TOOL_INPUT_ITEMS_CAP || budget.remaining <= 0) { + result['…'] = 'truncated' + break + } + let boundedKey = key.slice(0, Math.min(key.length, budget.remaining, 128)) + // Why: sibling keys sharing a >=128-char (or budget-truncated) prefix collapse + // to the same bounded key; suffix collisions so neither field is silently lost. + if (Object.hasOwn(result, boundedKey)) { + boundedKey = `${boundedKey}~${count}` + } + budget.remaining -= boundedKey.length + result[boundedKey] = sanitizeToolInput( + (value as Record)[key], + budget, + depth + 1 + ) + count++ + } + return result +} diff --git a/src/main/runtime/rpc/methods/native-chat.test.ts b/src/main/runtime/rpc/methods/native-chat.test.ts index 65bb525e798..1417e716770 100644 --- a/src/main/runtime/rpc/methods/native-chat.test.ts +++ b/src/main/runtime/rpc/methods/native-chat.test.ts @@ -266,6 +266,39 @@ describe('nativeChat.readSession clientKind truncation gating', () => { expect(JSON.stringify(input)).toContain('truncated') }) + // The roster block reached mobile through a bare fall-through, uncapped, on the + // one path that exists to keep the payload off the phone. + it('bounds a spawn-group roster before sending it to mobile', async () => { + cachedResult.value = { + messages: [ + { + ...makeMessage('ignored'), + blocks: [ + { + type: 'subagent-group', + groupId: 'thread-1:turn-1', + agents: Array.from({ length: 80 }, (_unused, index) => ({ + id: `child-${index}`, + label: index === 0 ? OVERSIZED : 'read', + state: index === 0 ? (OVERSIZED as 'working') : ('working' as const) + })) + } + ] + } + ] + } + + const result = await readSessionHandler()({ agent: 'codex', sessionId: 's' }, ctxWith('mobile')) + const block = (result as { messages: NativeChatMessage[] }).messages[0].blocks[0] + if (block.type !== 'subagent-group') { + throw new Error('expected a subagent-group block') + } + + expect(block.agents).toHaveLength(64) + expect(block.agents[0].label.length).toBeLessThan(OVERSIZED.length) + expect(block.agents[0].state).toBe('unverifiable') + }) + it('preserves AskUserQuestion option objects at the supported nesting depth', async () => { cachedResult.value = { messages: [ diff --git a/src/main/runtime/rpc/methods/native-chat.ts b/src/main/runtime/rpc/methods/native-chat.ts index 8fc86bf695a..e1a92dd52db 100644 --- a/src/main/runtime/rpc/methods/native-chat.ts +++ b/src/main/runtime/rpc/methods/native-chat.ts @@ -1,9 +1,5 @@ import { z } from 'zod' -import type { - NativeChatBlock, - NativeChatMessage, - AgentType -} from '../../../../shared/native-chat-types' +import type { NativeChatMessage, AgentType } from '../../../../shared/native-chat-types' import { readNativeChatTranscriptTail, subscribeNativeChatTranscript, @@ -11,7 +7,7 @@ import { type SubscribeNativeChatTranscriptArgs } from '../../../native-chat/transcript-watch' import { defineMethod, defineStreamingMethod, type RpcAnyMethod, type RpcContext } from '../core' -import { sanitizeNativeChatRpcImageBlock } from './native-chat-rpc-image-block' +import { sanitizeNativeChatRpcBlock } from './native-chat-rpc-block-sanitize' // Why: native chat renders an agent's own transcript (Claude/Codex JSONL). The // desktop reaches the readers via Electron IPC; mobile/web clients reach the @@ -68,109 +64,15 @@ const NativeChatUnsubscribe = z.object({ // older history as the user scrolls back. const MOBILE_NATIVE_CHAT_DEFAULT_WINDOW = 40 const MOBILE_NATIVE_CHAT_MAX_WINDOW = 2000 -// Why: a single tool result (a big file read, a long diff) can be hundreds of KB. -// The mobile view only previews tool block bodies, so truncate them on the wire -// to keep the payload small; the marker tells the user content was clipped. -const MOBILE_BLOCK_CHAR_CAP = 4000 -// Why: text blocks are the message body itself, rendered in full by the chat -// view — a preview-sized cap cut long assistant replies mid-sentence with no way -// to read on (STA-3230). Keep only a generous safety ceiling: a transcript -// record can legally reach 2MB, and shipping that much markdown in one block -// would freeze the phone. -const MOBILE_TEXT_BLOCK_CHAR_CAP = 64_000 -const MOBILE_TOOL_INPUT_ITEMS_CAP = 20 -const MOBILE_TOOL_INPUT_NODE_CAP = 100 -const TRUNCATION_MARKER = '\n… (truncated)' - -function clip(text: string, cap: number): string { - return text.length > cap ? text.slice(0, cap) + TRUNCATION_MARKER : text -} - -function sanitizeBlock( - block: NativeChatBlock, - clientKind: RpcContext['clientKind'] -): NativeChatBlock { - if (block.type === 'image-ref') { - return sanitizeNativeChatRpcImageBlock(block) - } - if (clientKind !== 'mobile') { - return block - } - if (block.type === 'text') { - return block.text.length > MOBILE_TEXT_BLOCK_CHAR_CAP - ? { ...block, text: clip(block.text, MOBILE_TEXT_BLOCK_CHAR_CAP) } - : block - } - if (block.type === 'tool-result') { - return block.output.length > MOBILE_BLOCK_CHAR_CAP - ? { ...block, output: clip(block.output, MOBILE_BLOCK_CHAR_CAP) } - : block - } - if (block.type === 'tool-call') { - const budget = { remaining: MOBILE_BLOCK_CHAR_CAP, nodes: MOBILE_TOOL_INPUT_NODE_CAP } - return { ...block, input: sanitizeToolInput(block.input, budget, 0) } - } - return block -} - -function sanitizeToolInput( - value: unknown, - budget: { remaining: number; nodes: number }, - depth: number -): unknown { - budget.nodes-- - if (budget.nodes < 0 || budget.remaining <= 0) { - return '… (truncated)' - } - if (typeof value === 'string') { - const length = Math.min(value.length, budget.remaining) - budget.remaining -= length - return length < value.length ? `${value.slice(0, length)}… (truncated)` : value - } - if (!value || typeof value !== 'object' || depth >= 5) { - return value && typeof value === 'object' ? '… (truncated)' : value - } - if (Array.isArray(value)) { - const result = value - .slice(0, MOBILE_TOOL_INPUT_ITEMS_CAP) - .map((item) => sanitizeToolInput(item, budget, depth + 1)) - if (value.length > MOBILE_TOOL_INPUT_ITEMS_CAP) { - result.push('… (truncated)') - } - return result - } - const result: Record = {} - let count = 0 - for (const key in value) { - if (!Object.hasOwn(value, key)) { - continue - } - if (count >= MOBILE_TOOL_INPUT_ITEMS_CAP || budget.remaining <= 0) { - result['…'] = 'truncated' - break - } - let boundedKey = key.slice(0, Math.min(key.length, budget.remaining, 128)) - // Why: sibling keys sharing a >=128-char (or budget-truncated) prefix collapse - // to the same bounded key; suffix collisions so neither field is silently lost. - if (Object.hasOwn(result, boundedKey)) { - boundedKey = `${boundedKey}~${count}` - } - budget.remaining -= boundedKey.length - result[boundedKey] = sanitizeToolInput( - (value as Record)[key], - budget, - depth + 1 - ) - count++ - } - return result -} function sanitizeMessage( message: NativeChatMessage, clientKind: RpcContext['clientKind'] ): NativeChatMessage { - return { ...message, blocks: message.blocks.map((block) => sanitizeBlock(block, clientKind)) } + return { + ...message, + blocks: message.blocks.map((block) => sanitizeNativeChatRpcBlock(block, clientKind)) + } } function sanitizeAppendForClient( diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.test.tsx index 5b71136b86f..cb9ad6932f0 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.test.tsx @@ -4,6 +4,11 @@ import '@testing-library/jest-dom/vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' +import { subagentGroupFallbackText } from '../../../../shared/native-chat-subagent-summary' +import type { + NativeChatMessage, + NativeChatSubagentEntry +} from '../../../../shared/native-chat-types' import type { NativeChatLiveSession } from './use-native-chat-live-session' import { NativeChatMessageList } from './NativeChatMessageList' @@ -560,3 +565,293 @@ describe('NativeChatMessageList assistant messages', () => { ) }) }) + +// List-level, because every defect this feature has shipped so far lived in the +// assembly between rows — the roster is its own `role: 'system'` journal row, and +// what reaches the DOM depends on `foldToolMessages`, the turn-key mapping and the +// disclosure state the list owns. Rendering `NativeChatToolRun` in isolation +// supplies those by hand and agrees with whatever the caller was asked to assume. +describe('NativeChatMessageList spawn-group roster', () => { + const ROSTER: NativeChatSubagentEntry[] = [ + { id: 'a', label: 'read', state: 'completed' }, + { id: 'b', label: 'search', state: 'failed' } + ] + + /** The exact two-block row `codexSubagentGroupBody` writes: the structured + * block plus the plain-text twin a client without the block type reads. */ + function rosterMessage(agents: NativeChatSubagentEntry[], at: number): NativeChatMessage { + return { + id: 'roster-1', + role: 'system', + blocks: [ + { type: 'text', text: subagentGroupFallbackText(agents) }, + { type: 'subagent-group', groupId: 'thread-1:turn-1', agents } + ], + timestamp: at, + source: 'transcript' + } + } + + // Explicit ascending timestamps: the list re-sorts by (timestamp, id), so rows + // sharing a millisecond tie-break alphabetically and the user turn can land + // last — which would strand the roster outside its own turn. + function rosterSession( + agents: NativeChatSubagentEntry[], + startedAt: number + ): NativeChatLiveSession { + return { + ...session, + status: 'ready', + messages: [ + { + id: 'user-fanout', + role: 'user', + blocks: [{ type: 'text', text: 'Fan this out' }], + timestamp: startedAt, + source: 'transcript' + }, + { + id: 'assistant-fanout', + role: 'assistant', + blocks: [ + { type: 'tool-call', name: 'shell', input: { command: 'pwd' }, state: 'completed' }, + { type: 'tool-result', output: '/repo' } + ], + timestamp: startedAt + 1, + source: 'transcript' + }, + rosterMessage(agents, startedAt + 2) + ] + } + } + + // A settled turn with its activity collapsed is the resting state of the whole + // transcript, so this is the roster's normal appearance, not an edge case. The + // completed-turn disclosure guard used to swallow it here — the compact row the + // feature exists to leave behind vanished the moment its turn ended. + it('leaves the roster row behind on a settled turn whose activity is collapsed', () => { + const startedAt = Date.now() - 3000 + render( + + ) + + expect(screen.getByRole('button', { name: 'Toggle turn details' })).toHaveAttribute( + 'aria-expanded', + 'false' + ) + expect(screen.getByRole('button', { name: /Ran 2 subagents/ })).toHaveTextContent('1 failed') + // The twin is the roster written out for clients that cannot draw the block. + // This one draws it, so printing the sentence too would say it all twice. + expect(screen.queryByText('Ran 2 subagents (1 failed)')).toBeNull() + }) + + // The block is provider-agnostic — the Claude lane feeds it too — so a lane + // that folds a roster into a message carrying real prose is a live shape. The + // filter used to drop EVERY text block once a roster was present, so that + // prose vanished on desktop while mobile, which reads the raw blocks, kept it. + it('keeps prose beside a roster block and drops only the twin', () => { + const startedAt = Date.now() - 3000 + const twin = subagentGroupFallbackText(ROSTER) + render( + + ) + + expect(screen.getByText('Handing the audit to two children.')).toBeInTheDocument() + expect(screen.getByRole('button', { name: /Ran 2 subagents/ })).toBeInTheDocument() + expect(screen.queryByText(twin)).toBeNull() + }) + + // The reordering that kept the roster visible must not have let TOOL activity + // out from behind the same disclosure: a failed child command reading as live + // on a finished turn is what put that guard there. + it('keeps tool activity behind the disclosure the roster now bypasses', () => { + const startedAt = Date.now() - 3000 + render( + + ) + + expect(screen.queryByRole('button', { name: /1× shell/ })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Toggle turn details' })) + expect(screen.getByRole('button', { name: /1× shell/ })).toBeInTheDocument() + // Expanding must reveal the tools beside the roster, never a second copy of it. + expect(screen.getAllByRole('button', { name: /Ran 2 subagents/ })).toHaveLength(1) + }) + + it('reads as a live spawn while the turn is still working', () => { + render( + + ) + + expect(screen.getByRole('button', { name: /Kicked off 2 subagents/ })).toHaveTextContent( + '2 working' + ) + }) + + // The QA defect, at the seam that produced it. A mid-turn correction opens a + // NEW turn, so `isCurrentTurn` goes false for the fan-out's row and the list + // passes `activeTurnIsWorking={false}` down to the roster. The row used to + // relabel every live child `unverifiable` and flip its headline to "Ran" — + // claiming both that contact was lost and that the fan-out had finished, while + // the three real children were still running and completed 57-87s later. + it('keeps live children working after a newer turn supersedes their own', () => { + const startedAt = Date.now() - 3000 + const live = rosterSession( + [ + { id: 'a', label: 'read_readme', state: 'working', startedAt }, + { id: 'b', label: 'read_package', state: 'working', startedAt } + ], + startedAt + ) + render( + + ) + + const roster = screen.getByRole('button', { name: /Kicked off 2 subagents/ }) + expect(roster).toHaveTextContent('2 working') + expect(roster).not.toHaveTextContent('unverifiable') + expect(screen.queryByRole('button', { name: /Ran 2 subagents/ })).toBeNull() + }) +}) + +// The block schema admits `agents: []`, so a childless spawn group is a shape the +// wire allows even though no producer writes one. It draws nothing, so the row +// must not be mounted on its account: "counts as renderable" and "actually draws" +// have to answer the same. A row that passes the first and fails the second is an +// invisible div that still consumes one `gap-5` slot of the transcript. +describe('NativeChatMessageList childless spawn group', () => { + const NO_AGENTS: NativeChatSubagentEntry[] = [] + + function rosterSession(blocks: NativeChatMessage['blocks'], at: number): NativeChatLiveSession { + return { + ...session, + status: 'ready', + messages: [ + { + id: 'user-fanout', + role: 'user', + blocks: [{ type: 'text', text: 'Fan this out' }], + timestamp: at, + source: 'transcript' + }, + { id: 'roster-1', role: 'system', blocks, timestamp: at + 1, source: 'transcript' } + ] + } + } + + /** Every slot the transcript column lays out — one per row that mounted. */ + function emptySlots(container: HTMLElement): Element[] { + const column = container.querySelector('.max-w-4xl') + expect(column).not.toBeNull() + return Array.from(column!.children).filter((slot) => slot.textContent === '') + } + + it('mounts no row for a bare spawn group with no children', () => { + const startedAt = Date.now() - 3000 + const { container } = render( + + ) + + expect(screen.getByText('Fan this out')).toBeInTheDocument() + expect(emptySlots(container)).toEqual([]) + }) + + it('falls back to the plain-text twin when the block it stands in for cannot draw', () => { + const startedAt = Date.now() - 3000 + const { container } = render( + + ) + + // The twin is dropped only because the block draws the roster instead. This + // one cannot, so suppressing it too would leave the row with nothing at all. + expect(screen.getByText(subagentGroupFallbackText(NO_AGENTS))).toBeInTheDocument() + expect(emptySlots(container)).toEqual([]) + }) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx b/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx index 07ea51b5a62..64f489a1b48 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx @@ -4,7 +4,11 @@ import CommentMarkdown, { } from '@/components/sidebar/CommentMarkdown' import { cn } from '@/lib/utils' import { translate } from '@/i18n/i18n' -import type { NativeChatMessage } from '../../../../shared/native-chat-types' +import { + isSubagentGroupFallbackText, + subagentGroupBlocks +} from '../../../../shared/native-chat-subagent-summary' +import { isSubagentGroupBlock, type NativeChatMessage } from '../../../../shared/native-chat-types' import { splitNativeChatBlocks } from './native-chat-tool-fold' import { NativeChatToolRun } from './NativeChatToolRun' import { nativeChatProseToMarkdown } from './native-chat-prose' @@ -47,12 +51,28 @@ export const MessageRow = memo(function MessageRow({ const rowRef = useRef(null) // One pass per block set: a streaming turn re-renders this row on every frame, and these // derivations used to re-run each time even though `message.blocks` had not changed. - const { hasImages, markdown, prose, tools } = useMemo(() => { + const { hasImages, markdown, prose, subagentGroups, tools } = useMemo(() => { const split = splitNativeChatBlocks(message.blocks) + const groups = subagentGroupBlocks(split.prose) + // A spawn-group row carries a plain-text twin so a client without the block + // type still reads the roster. This one draws the block, so the twin is + // dropped rather than printed beside it — only the twin, never the prose + // beside it: the block is provider-agnostic, so a lane that folds a roster + // into a message with real text must not lose that text here. + const prose = + groups.length === 0 + ? split.prose + : split.prose.filter( + (block) => + !isSubagentGroupBlock(block) && + !(block.type === 'text' && isSubagentGroupFallbackText(block.text)) + ) return { - ...split, - markdown: nativeChatProseToMarkdown(split.prose), - hasImages: split.prose.some((block) => block.type === 'image-ref') + tools: split.tools, + prose, + subagentGroups: groups, + markdown: nativeChatProseToMarkdown(prose), + hasImages: prose.some((block) => block.type === 'image-ref') } }, [message.blocks]) const isUser = message.role === 'user' @@ -69,7 +89,7 @@ export const MessageRow = memo(function MessageRow({ // Skip rows with nothing renderable so the transcript shows no empty/ghost // bubble. // After all hooks, so hook order stays unconditional. - if (markdown.length === 0 && !hasImages && tools.length === 0) { + if (markdown.length === 0 && !hasImages && tools.length === 0 && subagentGroups.length === 0) { return null } @@ -151,9 +171,10 @@ export const MessageRow = memo(function MessageRow({ linkifyFilePaths={onLinkClick !== undefined} /> ) : null} - {tools.length > 0 ? ( + {tools.length > 0 || subagentGroups.length > 0 ? ( { + it('reads as a live spawn while children work', () => { + render( + + ) + + expect(screen.getByText('Kicked off 2 subagents')).toBeInTheDocument() + expect(screen.getByRole('button')).toHaveTextContent('1 working') + expect(screen.getByRole('button')).toHaveTextContent('40.7k tokens') + }) + + it('switches to Ran once every child completed', () => { + render( + + ) + + expect(screen.getByText('Ran 2 subagents')).toBeInTheDocument() + expect(screen.getByRole('button')).toHaveTextContent('completed') + }) + + it('shows the worst settled verdict, not the count of finished children', () => { + render( + + ) + + expect(screen.getByRole('button')).toHaveTextContent('2 failed') + }) + + it('surfaces a failed child while its siblings still work', () => { + const { container } = render( + + ) + + const row = screen.getByRole('button') + expect(row).toHaveTextContent('3 working') + expect(row).toHaveTextContent('+1 failed') + // The dot carries the failure; the pulse still says the group is in flight. + expect(container.querySelector('.bg-destructive.animate-pulse')).not.toBeNull() + }) + + it('leaves the dot neutral when nothing has gone wrong', () => { + const { container } = render( + + ) + + expect(screen.getByRole('button')).not.toHaveTextContent('failed') + expect(container.querySelector('.bg-destructive')).toBeNull() + }) + + // The QA defect: a mid-turn correction opened a new turn while three real + // children were still running, and the row relabelled every one of them + // `unverifiable` and flipped its headline to `Ran`. The children completed + // 57-87s later. A turn boundary says nothing about a child. + it('keeps a working child working once its turn is no longer the current one', () => { + render() + + const row = screen.getByRole('button') + expect(row).toHaveTextContent('working') + expect(row).not.toHaveTextContent('unverifiable') + expect(screen.getByText('Kicked off 1 subagent')).toBeInTheDocument() + }) + + it('reports the verdict a child lands after its turn ended', () => { + render( + + ) + + expect(screen.getByText('Ran 1 subagent')).toBeInTheDocument() + expect(screen.getByRole('button')).toHaveTextContent('completed') + }) + + // Only the writing host may claim loss of contact, and it writes that verdict + // into the row itself. The renderer draws it, and never infers it. + it('draws the unverifiable verdict the host recorded', () => { + render( + + ) + + expect(screen.getByRole('button')).toHaveTextContent('unverifiable') + }) + + it('leads with the bot glyph, decorative beside the word that names the group', () => { + const { container } = render( + + ) + + const glyph = container.querySelector('.lucide-bot') + expect(glyph).not.toBeNull() + expect(glyph).toHaveAttribute('aria-hidden', 'true') + // Never icon-only: the word is what carries the accessible name. + expect(screen.getByRole('button')).toHaveAccessibleName(/Kicked off 1 subagent/) + }) + + it('keeps the same glyph in every state, so a settling row never changes identity', () => { + const states: NativeChatSubagentState[] = [ + 'working', + 'idle', + 'completed', + 'failed', + 'stopped', + 'unverifiable' + ] + + for (const state of states) { + const { container } = render( + + ) + + expect(container.querySelectorAll('.lucide-bot')).toHaveLength(1) + expect(container.querySelector('.lucide-check')).toBeNull() + expect(container.querySelector('.lucide-users')).toBeNull() + cleanup() + } + }) + + // The only aria-hidden span carrying text is the elapsed-clock wrapper: the + // glyph's Bot is an and the status dots render empty. + function hiddenTextSpans(container: HTMLElement): Element[] { + return [...container.querySelectorAll('span[aria-hidden="true"]')].filter( + (element) => (element.textContent ?? '').trim().length > 0 + ) + } + + it('keeps the ticking clock out of the live region until it stops moving', () => { + const { container } = render( + + ) + + const row = screen.getByRole('button') + expect(row).toHaveAttribute('aria-live', 'polite') + // A clock that reticks every second would announce a new duration every + // second and bury the state changes the live region exists to report. + expect(hiddenTextSpans(container)).toHaveLength(1) + }) + + it('reads the elapsed time out once it has stopped moving', () => { + const { container } = render( + + ) + + // Settled: the duration is fixed, so hiding it would cost a reader real + // information for no announcement churn. + expect(hiddenTextSpans(container)).toHaveLength(0) + expect(screen.getByRole('button')).toHaveTextContent('4s') + }) + + it('shows no duration for a child whose run length was never recorded', () => { + render( + + ) + + const row = screen.getByRole('button') + expect(row).toHaveTextContent('unverifiable') + // `unverifiable` with no terminal timestamp has no known run length, so the + // clock would measure to `now` and report the time since we lost sight of + // the child as how long it ran — on a row that is not even counting. + expect(row.textContent).not.toContain('·') + }) + + // A partial sweep leaves one child settled and one whose fate is unknown. The + // group's clock would then report the settled sibling's duration as the + // group's run length while the other child is still unaccounted for. + it('shows no duration while one child settled and another is unaccounted for', () => { + render( + + ) + + const row = screen.getByRole('button') + expect(row).toHaveTextContent('unverifiable') + expect(row.textContent).not.toContain('·') + }) +}) + +describe('NativeChatToolRun with a spawn group', () => { + it('renders a roster with no tool calls without inventing a tool count', () => { + render( + + ) + + expect(screen.getByText('Kicked off 1 subagent')).toBeInTheDocument() + expect(screen.queryByText('1 tool call')).toBeNull() + }) + + // Every settled turn sits here by default: the list passes + // `expandOverride={expandedTurnIds.has(turnKey)}` — false until the reader + // opens that turn — and `activeTurnIsWorking={false}`. The completed-turn + // guard above bailed before the roster branch, so the one row this feature + // exists to draw vanished the moment its turn finished, and the message row + // that kept itself alive for it rendered an empty ghost bubble. + it('keeps the roster visible on a completed turn whose activity is collapsed', () => { + render( + + ) + + expect(screen.getByText('Ran 1 subagent')).toBeInTheDocument() + }) + + // The roster-only branch returns a `mt-3` wrapper whenever it has rows, so a + // group that draws nothing must not count as one — that wrapper would be the + // empty bubble with a margin that the message row refuses to emit. + it('draws nothing at all for a spawn group that carries no children', () => { + const { container } = render( + + ) + + expect(container).toBeEmptyDOMElement() + }) + + // The roster-only escape above is keyed on `blocks.length === 0`, so a group + // sharing its message with tool calls falls through to the settled-turn guard + // — which returned bare null and took the roster with it. + it('keeps a roster that shares its message with tool calls on a collapsed turn', () => { + render( + + ) + + expect(screen.getByText('Ran 1 subagent')).toBeInTheDocument() + expect(screen.queryByText('shell ls')).toBeNull() + }) + + it('renders the roster alongside the tool activity of its turn', () => { + render( + + ) + + expect(screen.getByText('Ran 1 subagent')).toBeInTheDocument() + expect(screen.getByText('shell ls')).toBeInTheDocument() + }) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatSubagentRun.tsx b/src/renderer/src/components/native-chat/NativeChatSubagentRun.tsx new file mode 100644 index 00000000000..af3bf468011 --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatSubagentRun.tsx @@ -0,0 +1,277 @@ +import { useMemo, useState } from 'react' +import { Bot, ChevronRight } from 'lucide-react' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' +import { useNow } from '@/hooks/use-now' +import { + normalizeSubagentState, + summarizeSubagentGroup +} from '../../../../shared/native-chat-subagent-summary' +import type { + NativeChatSubagentGroupBlock, + NativeChatSubagentState +} from '../../../../shared/native-chat-types' +import { formatNativeChatDuration } from './NativeChatWorkingStatus' + +/** Compact token counts: the row shows scale, not an exact ledger. */ +function formatSubagentTokens(tokens: number): string { + if (tokens < 1_000) { + return String(Math.round(tokens)) + } + const scaled = tokens < 1_000_000 ? tokens / 1_000 : tokens / 1_000_000 + const suffix = tokens < 1_000_000 ? 'k' : 'M' + return `${scaled.toFixed(1).replace(/\.0$/, '')}${suffix}` +} + +/** The group's one-line verdict. A single-child group reads as a bare word; any + * larger group always carries the count, because "working" alone would not say + * how many of the children it covers. `completed` never takes one: every child + * finishing is the whole group finishing. */ +function subagentStateLabel( + state: NativeChatSubagentState, + count: number, + groupTotal: number +): string { + if (state === 'completed') { + return translate('components.native-chat.subagents.state.completed', 'completed') + } + if (groupTotal <= 1) { + switch (state) { + case 'working': + return translate('components.native-chat.subagents.state.working', 'working') + case 'idle': + return translate('components.native-chat.subagents.state.idle', 'idle') + case 'failed': + return translate('components.native-chat.subagents.state.failed', 'failed') + case 'stopped': + return translate('components.native-chat.subagents.state.stopped', 'stopped') + case 'unverifiable': + return translate('components.native-chat.subagents.state.unverifiable', 'unverifiable') + } + } + switch (state) { + case 'working': + return translate( + 'components.native-chat.subagents.state.workingCount', + '{{value0}} working', + { + value0: count + } + ) + case 'idle': + return translate('components.native-chat.subagents.state.idleCount', '{{value0}} idle', { + value0: count + }) + case 'failed': + return translate('components.native-chat.subagents.state.failedCount', '{{value0}} failed', { + value0: count + }) + case 'stopped': + return translate( + 'components.native-chat.subagents.state.stoppedCount', + '{{value0}} stopped', + { + value0: count + } + ) + case 'unverifiable': + return translate( + 'components.native-chat.subagents.state.unverifiableCount', + '{{value0}} unverifiable', + { value0: count } + ) + } +} + +const STATE_DOT_CLASS: Record = { + working: 'bg-foreground/70', + idle: 'bg-muted-foreground/40', + completed: 'bg-muted-foreground/60', + failed: 'bg-destructive', + stopped: 'bg-muted-foreground', + unverifiable: 'bg-muted-foreground' +} + +/** + * The group's identity glyph, fixed across every state — a settling row must not + * appear to change identity. State is carried by {@link StatusDot} and the tone + * of the words beside it. + * + * SWAP POINT: once the shared category-icon component lands (PR #18760), this + * whole component becomes that component asked for the `bot` category, which is + * the same glyph the individual `subAgentActivity` rows use. + */ +function SubagentGlyph(): React.JSX.Element { + return ( + + + ) +} + +/** `pulsing` is separate from `state` so a group that is still working can show + * a failed sibling's colour without losing its in-flight cue. */ +function StatusDot({ + state, + pulsing = false +}: { + state: NativeChatSubagentState + pulsing?: boolean +}): React.JSX.Element { + return ( +