diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 30396cd5444..513d6b1aca0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -32,6 +32,7 @@ jobs: image-preview-back.spec.ts opencode-fork-buttons.spec.ts auth-network-recovery.spec.ts + session-list-blocked.spec.ts # playwright.config.ts already sets `trace: 'retain-on-failure'` and # the html reporter on CI, but nothing collected the output, so every # trace died with the runner — leaving CI-only Playwright failures diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index ffbfb50d13a..6a24e051dfd 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -101,7 +101,7 @@ android { targetSdk = 36 versionCode = gitCommitCount ?: 1 // Tracks the hapi CLI/hub release train. - versionName = providers.gradleProperty("hapiVersionName").orElse("0.37.0").get() + versionName = providers.gradleProperty("hapiVersionName").orElse("0.37.1").get() testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/pairing/PairingLinks.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/pairing/PairingLinks.kt index cdec230a8f1..5c87ba11055 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/pairing/PairingLinks.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/pairing/PairingLinks.kt @@ -23,10 +23,11 @@ object PairingLinks { fun parse(raw: String): BindLink? = BindLink.parse(raw) ?: parseWebUrl(raw) /** - * Parses the web direct-access QR: any absolute HTTPS URL whose query - * carries non-blank `hub` (itself an HTTPS URL) and `token` params. The - * host is deliberately not pinned to `app.hapi.run` — self-hosters may - * serve the web app from their own origin. Returns null otherwise. + * Parses the web direct-access QR: any absolute HTTPS URL whose fragment + * (preferred) or query carries non-blank `hub` (itself an HTTPS URL) and + * `token` params. The host is deliberately not pinned to `app.hapi.run` — + * self-hosters may serve the web app from their own origin. Returns null + * otherwise. */ fun parseWebUrl(raw: String): BindLink? { val uri = try { @@ -38,9 +39,18 @@ object PairingLinks { if (scheme != "https") return null if ((uri.host ?: uri.authority).isNullOrBlank()) return null - val params = BindLink.parseFormQuery(uri.rawQuery ?: return null) ?: return null - val hub = params["hub"]?.takeIf { it.isNotBlank() } ?: return null - val token = params["token"]?.takeIf { it.isNotBlank() } ?: return null + val fragmentParams = uri.rawFragment?.takeIf { it.isNotEmpty() }?.let { + BindLink.parseFormQuery(it) ?: return null + } + val queryParams = uri.rawQuery?.takeIf { it.isNotEmpty() }?.let { + BindLink.parseFormQuery(it) ?: return null + } + if (fragmentParams == null && queryParams == null) return null + + val hub = (if (fragmentParams != null && "hub" in fragmentParams) fragmentParams["hub"] else queryParams?.get("hub")) + ?.takeIf { it.isNotBlank() } ?: return null + val token = (if (fragmentParams != null && "token" in fragmentParams) fragmentParams["token"] else queryParams?.get("token")) + ?.takeIf { it.isNotBlank() } ?: return null if (!BindLink.isHttpsUrl(hub)) return null return BindLink(hubUrl = hub, accessToken = token) } diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/pairing/PairingLinksTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/pairing/PairingLinksTest.kt index 9cd02ce6a63..4abec271a1a 100644 --- a/android/core/protocol/src/test/kotlin/app/hapi/protocol/pairing/PairingLinksTest.kt +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/pairing/PairingLinksTest.kt @@ -82,4 +82,31 @@ class PairingLinksTest { assertNull(PairingLinks.parse("https://example.com/some/page")) assertNull(PairingLinks.parse("hello world")) } + + @Test + fun `parse accepts the fragment web direct-access form and prefers fragment over query`() { + val fragmentOnly = PairingLinks.parse( + "https://app.hapi.run/#hub=https%3A%2F%2Fdemo.hapi.run&token=tok_9f8%3Adefault" + ) + assertEquals(BindLink(hubUrl = "https://demo.hapi.run", accessToken = "tok_9f8:default"), fragmentOnly) + + val mixed = PairingLinks.parse( + "https://app.hapi.run/?hub=https%3A%2F%2Fdemo.hapi.run#token=frag_tok" + ) + assertEquals(BindLink(hubUrl = "https://demo.hapi.run", accessToken = "frag_tok"), mixed) + + val overridden = PairingLinks.parse( + "https://app.hapi.run/?hub=https%3A%2F%2Fquery.example.com&token=query_tok#hub=https%3A%2F%2Ffrag.example.com&token=frag_tok" + ) + assertEquals(BindLink(hubUrl = "https://frag.example.com", accessToken = "frag_tok"), overridden) + + assertNull( + PairingLinks.parse( + "https://app.hapi.run/?hub=https%3A%2F%2Fquery.example.com&token=query_tok#token=" + ) + ) + assertNull( + PairingLinks.parse("https://app.hapi.run/#hub=https%3A%2F%2Fdemo.hapi.run&token=%zz") + ) + } } diff --git a/bun.lock b/bun.lock index 8aff092fa07..ff219dcf861 100644 --- a/bun.lock +++ b/bun.lock @@ -13,7 +13,7 @@ }, "cli": { "name": "@twsxtd/hapi", - "version": "0.37.0", + "version": "0.37.1", "bin": { "hapi": "bin/hapi.cjs", }, diff --git a/cli/bin/hapi.cjs b/cli/bin/hapi.cjs index 4d4908b0848..a2fae627d9a 100755 --- a/cli/bin/hapi.cjs +++ b/cli/bin/hapi.cjs @@ -65,56 +65,28 @@ function getBinaryPath(platformName = platform, archName = arch) { return path.join(path.dirname(pkgPath), 'bin', binName); } -function formatCommand(binPath, args) { - return [binPath, ...args].map((arg) => JSON.stringify(String(arg))).join(' '); -} - -/** - * Any `hapi [ -- ] job … -- ` argv can carry tokens in flags / - * shell -c text. Binary strips one leading runtime `--` (cliArgs); parser - * also accepts flags before the action word. Keep CLI diagnostics (stdio - * inherit), but never echo workload args from the npm launcher. - */ -function jobWorkloadSeparatorIndex(args) { - if (!Array.isArray(args) || args.length === 0) { - return -1; - } - let commandIndex = 0; - if (args[0] === '--') { - commandIndex = 1; - } - if (args[commandIndex] !== 'job') { - return -1; - } - const separator = args.indexOf('--', commandIndex + 1); - if (separator === -1 || separator === args.length - 1) { - return -1; - } - return separator; -} - -function displayArgsForFailure(args) { - const separator = jobWorkloadSeparatorIndex(args); - if (separator === -1) { - return args; - } - return args.slice(0, separator + 1).concat(['']); -} - function normalizeExecError(error) { return { status: typeof error?.status === 'number' ? error.status : null, signal: typeof error?.signal === 'string' ? error.signal : null, - message: error?.message ? String(error.message) : null, + code: typeof error?.code === 'string' ? error.code : null, }; } +/** + * argv can carry secrets (tokens in flags, `job run -- ` text), and + * Node's exec error message repeats the whole command line. Print only the + * binary path, why it failed, and its exit status or signal; the binary's own + * diagnostics already reached stderr through stdio: 'inherit'. + */ function reportExecutionFailure(error, binPath, args, log = console.error) { - const { status, signal, message } = normalizeExecError(error); - const displayArgs = displayArgsForFailure(args); - const omitRawExecMessage = jobWorkloadSeparatorIndex(args) !== -1; + const { status, signal, code } = normalizeExecError(error); - log(`Failed to execute: ${formatCommand(binPath, displayArgs)}`); + log(`Failed to execute: ${JSON.stringify(String(binPath))}`); + + if (code) { + log(`Binary could not be started: ${code}.`); + } if (signal) { log(`Binary terminated by signal ${signal}.`); @@ -124,13 +96,6 @@ function reportExecutionFailure(error, binPath, args, log = console.error) { log(`Binary exited with status ${status}.`); } - // Token-by-token redaction of Node's argv-bearing message is unsafe when a - // short flag overlaps a longer credential arg. For job + workload argv, - // drop the raw message entirely — CLI diagnostics already went to stderr. - if (message && !omitRawExecMessage) { - log(message); - } - return { status, signal }; } @@ -221,12 +186,9 @@ if (require.main === module) { } module.exports = { - displayArgsForFailure, - formatCommand, getPlatformKey, getBinaryPath, isSupportedPlatform, - jobWorkloadSeparatorIndex, normalizeExecError, reportExecutionFailure, reportMissingPlatformPackage, diff --git a/cli/package.json b/cli/package.json index 36e47625ddb..4ae99402d4d 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@twsxtd/hapi", - "version": "0.37.0", + "version": "0.37.1", "description": "App for agentic coding - access coding agent anywhere", "author": "Kirill Dubovitskiy & weishu", "license": "AGPL-3.0-only", diff --git a/cli/src/agent/agentQuotas.spawnArgs.test.ts b/cli/src/agent/agentQuotas.spawnArgs.test.ts new file mode 100644 index 00000000000..177ab0554f4 --- /dev/null +++ b/cli/src/agent/agentQuotas.spawnArgs.test.ts @@ -0,0 +1,147 @@ +import { EventEmitter } from 'node:events' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const spawnMock = vi.hoisted(() => vi.fn()) +vi.mock('node:child_process', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, spawn: spawnMock } +}) + +const killMock = vi.hoisted(() => vi.fn()) +vi.mock('@/utils/process', () => ({ killProcessByChildProcess: killMock })) + +import * as agentAvailability from './agentAvailability' +import { _resetAgentQuotasCacheForTests, probeAgyQuota } from './agentQuotas' + +const USAGE_JSON = JSON.stringify({ command: { name: 'usage', data: { groups: [] } } }) +const CREDITS_JSON = JSON.stringify({ command: { name: 'credits', data: { remaining_credits: 10 } } }) + +type SpawnCall = { command: string; args: string[] } + +function respondingChild(output: string) { + const child = Object.assign(new EventEmitter(), { + stdout: new EventEmitter(), + stderr: new EventEmitter(), + kill: vi.fn() + }) + queueMicrotask(() => { + child.stdout.emit('data', `${output}\n`) + child.emit('close', 0) + }) + return child +} + +describe('agy quota subprocess arguments', () => { + beforeEach(() => { + _resetAgentQuotasCacheForTests() + spawnMock.mockReset() + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'agy' + })) + }) + + it('sends models, usage, and credits as separate calls with their full arguments', async () => { + const calls: SpawnCall[] = [] + spawnMock.mockImplementation((command: string, args: string[]) => { + calls.push({ command, args }) + if (args[0] === 'models') return respondingChild('gemini-3-pro') + if (args[1] === '/usage') return respondingChild(USAGE_JSON) + if (args[1] === '/credits') return respondingChild(CREDITS_JSON) + throw new Error(`Unexpected agy arguments: ${args.join(' ')}`) + }) + + const result = await probeAgyQuota({}) + + expect(result.status).toBe('ok') + expect(calls).toEqual([ + { command: 'agy', args: ['models'] }, + { command: 'agy', args: ['-p', '/usage', '--output-format', 'json'] }, + { command: 'agy', args: ['-p', '/credits', '--output-format', 'json'] } + ]) + }) + + it('starts usage and credits together after models within the shared probe budget', async () => { + vi.useFakeTimers() + killMock.mockResolvedValue(false) + const spawnTimes: number[] = [] + spawnMock.mockImplementation((_command: string, args: string[]) => { + spawnTimes.push(Date.now()) + const child = Object.assign(new EventEmitter(), { + stdout: new EventEmitter(), + stderr: new EventEmitter(), + kill: vi.fn() + }) + const output = args[0] === 'models' ? 'gemini-3-pro' : args[1] === '/usage' ? USAGE_JSON : null + if (output) { + setTimeout(() => { + child.stdout.emit('data', `${output}\n`) + child.emit('close', 0) + }, 4_000) + } + return child + }) + + try { + const startedAt = Date.now() + const probe = probeAgyQuota({}) + await vi.advanceTimersByTimeAsync(4_000) + expect(spawnTimes).toHaveLength(3) + expect(spawnTimes[1] - startedAt).toBe(4_000) + expect(spawnTimes[2] - startedAt).toBe(4_000) + + const settled: { result?: Awaited>; at?: number } = {} + void probe.then((value) => { + settled.result = value + settled.at = Date.now() + }) + await vi.advanceTimersByTimeAsync(5_000) + expect(settled.result).toBeDefined() + expect(settled.result?.status).toBe('ok') + expect(settled.at).toBe(startedAt + 9_000) + } finally { + vi.useRealTimers() + killMock.mockReset() + } + }) + + it('returns a usage error before a hung credits command settles', async () => { + vi.useFakeTimers() + killMock.mockResolvedValue(false) + const creditsChildren: EventEmitter[] = [] + spawnMock.mockImplementation((_command: string, args: string[]) => { + const child = Object.assign(new EventEmitter(), { + stdout: new EventEmitter(), + stderr: new EventEmitter(), + kill: vi.fn() + }) + if (args[0] === 'models') { + queueMicrotask(() => { + child.stdout.emit('data', 'gemini-3-pro\n') + child.emit('close', 0) + }) + } else if (args[1] === '/usage') { + queueMicrotask(() => { + child.stdout.emit('data', 'not quota json\n') + child.emit('close', 0) + }) + } else { + creditsChildren.push(child) + } + return child + }) + + try { + const startedAt = Date.now() + const result = await probeAgyQuota({}) + + expect(result.status).toBe('error') + expect(result.note).toBe('Unable to parse Antigravity quota output') + expect(Date.now() - startedAt).toBe(0) + expect(creditsChildren).toHaveLength(1) + } finally { + vi.useRealTimers() + killMock.mockReset() + } + }) +}) diff --git a/cli/src/agent/agentQuotas.test.ts b/cli/src/agent/agentQuotas.test.ts index 5a2a886545f..1c2bada86a3 100644 --- a/cli/src/agent/agentQuotas.test.ts +++ b/cli/src/agent/agentQuotas.test.ts @@ -1,7 +1,7 @@ import { spawn, spawnSync } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { delimiter, join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' import * as agentAvailability from './agentAvailability' import { CodexAppServerClient } from '@/codex/codexAppServerClient' @@ -28,6 +28,446 @@ describe('agentQuotas parsers and probes', () => { vi.restoreAllMocks() }) + function createFakeAgy(): { directory: string; eventLog: string; usageDone: string; env: NodeJS.ProcessEnv } { + const directory = mkdtempSync(join(tmpdir(), 'hapi-agy-fake-')) + const eventLog = join(directory, 'events.log') + const usageDone = join(directory, 'usage-done') + const script = join(directory, 'fake-agy.cjs') + writeFileSync(script, ` +const fs = require('node:fs') +const argv = process.argv.slice(2) +const log = (line) => fs.appendFileSync(process.env.AGY_EVENT_LOG, line + '\\n') +log(argv.join(' ')) +const wait = (seconds) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, seconds * 1000) +const out = (line) => fs.writeSync(1, line + '\\n') +const err = (line) => fs.writeSync(2, line + '\\n') +const countFile = (name) => { + const file = process.env[name] + if (!file) return 0 + const count = fs.existsSync(file) ? Number(fs.readFileSync(file, 'utf8') || '0') : 0 + fs.writeFileSync(file, String(count + 1)) + return count +} +if (argv[0] === 'models') { + const modelsCount = countFile('AGY_MODELS_COUNT_FILE') + if (process.env.AGY_FAKE_MODELS_DELAY) wait(Number(process.env.AGY_FAKE_MODELS_DELAY)) + if (process.env.AGY_FAKE_MODELS_FAIL === 'hang') { + wait(6) + out('gemini-3-pro') + process.exit(0) + } + if (process.env.AGY_FAKE_AUTH === 'unauthenticated-delayed-once' && modelsCount === 0) { + err('Error: Please sign in to view available models. Launch the CLI without arguments to sign in.') + wait(Number(process.env.AGY_FAKE_UNAUTH_DELAY ?? '1.5')) + process.exit(1) + } + if (process.env.AGY_FAKE_AUTH === 'error-delayed-once' && modelsCount === 0) { + err('unexpected failure') + wait(Number(process.env.AGY_FAKE_ERROR_DELAY ?? '1.5')) + process.exit(2) + } + if (process.env.AGY_FAKE_AUTH === 'unauthenticated') { + err('Error: Please sign in to view available models. Launch the CLI without arguments to sign in.') + process.exit(1) + } + if (process.env.AGY_FAKE_AUTH === 'not-logged-in-exit2') { + err('Error: not logged in') + process.exit(2) + } + if (process.env.AGY_FAKE_AUTH === 'diagnostic-zero-exit') { + err('Authentication failed (session expired)') + process.exit(0) + } + if (process.env.AGY_FAKE_MODELS_FAIL === 'no-listing') { + out('Fetching available models...') + process.exit(0) + } + if (process.env.AGY_FAKE_MODELS_FAIL === 'exit2') { + err('unexpected failure') + process.exit(2) + } + out('gemini-3-pro') + process.exit(0) +} +if (argv[0] === '-p' && argv[1] === '/usage') { + log('usage-start') + if (process.env.AGY_FAKE_USAGE_FAIL === 'hang') wait(6) + wait(0.1) + fs.writeFileSync(process.env.AGY_USAGE_DONE, '') + log('usage-complete') + out('{"command":{"name":"usage","data":{"groups":[]}}}') + process.exit(process.env.AGY_FAKE_USAGE_EXIT ? Number(process.env.AGY_FAKE_USAGE_EXIT) : 0) +} +if (argv[0] === '-p' && argv[1] === '/credits') { + if (!fs.existsSync(process.env.AGY_USAGE_DONE)) log('credits-before-usage-complete') + log('credits-start') + if (process.env.AGY_FAKE_CREDITS_FORK === 'hang') { + const grandchild = require('node:child_process').spawn(process.execPath, ['-e', 'Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 60_000)'], { stdio: 'ignore' }) + fs.writeFileSync(process.env.AGY_CREDITS_PID, String(process.pid)) + fs.writeFileSync(process.env.AGY_GRANDCHILD_PID, String(grandchild.pid)) + wait(60) + } + out('{"command":{"name":"credits","data":{"remaining_credits":10}}}') + process.exit(0) +} +process.exit(2) +`, 'utf8') + // This shebang fixture is POSIX only. Windows command dispatch is + // covered by the subprocess mock in agentQuotas.spawnArgs.test.ts. + writeFileSync(join(directory, 'agy'), `#!/usr/bin/env node\nrequire(${JSON.stringify(script)})\n`, { mode: 0o755 }) + return { + directory, + eventLog, + usageDone, + env: { + ...process.env, + PATH: `${directory}${delimiter}${process.env.PATH ?? ''}`, + AGY_EVENT_LOG: eventLog, + AGY_USAGE_DONE: usageDone + } + } + } + + const agyFixtureIt = process.platform === 'win32' ? it.skip : it + + agyFixtureIt('treats a not-logged-in message as unauthenticated even on a non-zero models exit', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_AUTH: 'not-logged-in-exit2' } + const result = await probeAgyQuota(env) + + expect(result.status).toBe('unauthenticated') + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models']) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('treats a zero models exit with only a sign-in diagnostic on stderr as unauthenticated', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_AUTH: 'diagnostic-zero-exit' } + const result = await probeAgyQuota(env) + + expect(result.status).toBe('unauthenticated') + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models']) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('does not launch print commands when the models probe exits zero without a listing', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_MODELS_FAIL: 'no-listing' } + const result = await probeAgyQuota(env) + + expect(result.status).toBe('error') + expect(result.note).toContain('model listing') + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models']) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('rechecks agy auth on ordinary polls and explicit refreshes', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_AUTH: 'unauthenticated' } + expect((await probeAgyQuota(env)).status).toBe('unauthenticated') + // a normal poll re-runs the safe models check instead of replaying the verdict + expect((await probeAgyQuota(env)).status).toBe('unauthenticated') + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models', 'models']) + + // an explicit refresh runs the same safe check + expect((await probeAgyQuota(env, { refresh: true })).status).toBe('unauthenticated') + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models', 'models', 'models']) + + // the user signs in; refresh recovers to ok + const recovered = await probeAgyQuota(fakeAgy.env, { refresh: true }) + expect(recovered.status).toBe('ok') + const events = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + expect(events.filter((event) => event === 'models')).toHaveLength(4) + expect(events.filter((event) => event === '-p /usage --output-format json')).toHaveLength(1) + expect(events.filter((event) => event === '-p /credits --output-format json')).toHaveLength(1) + expect(events.filter((event) => event === 'usage-start')).toHaveLength(1) + expect(events.filter((event) => event === 'credits-start')).toHaveLength(1) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('starts a new guarded preflight when explicit refresh joins an unauthenticated in-flight probe', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { + ...fakeAgy.env, + AGY_FAKE_AUTH: 'unauthenticated-delayed-once', + AGY_FAKE_UNAUTH_DELAY: '1.5', + AGY_MODELS_COUNT_FILE: join(fakeAgy.directory, 'models-count') + } + + const ordinary = probeAgyQuota(env) + await new Promise((resolve) => setTimeout(resolve, 200)) + const refresh = probeAgyQuota(env, { refresh: true }) + + const [ordinaryResult, refreshResult] = await Promise.all([ordinary, refresh]) + expect(ordinaryResult.status).toBe('unauthenticated') + expect(refreshResult.status).toBe('ok') + + const events = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + expect(events.filter((event) => event === 'models')).toHaveLength(2) + expect(events.filter((event) => event === '-p /usage --output-format json')).toHaveLength(1) + expect(events.filter((event) => event === '-p /credits --output-format json')).toHaveLength(1) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('starts a new guarded preflight when explicit refresh joins an errored in-flight probe', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { + ...fakeAgy.env, + AGY_FAKE_AUTH: 'error-delayed-once', + AGY_FAKE_ERROR_DELAY: '1.5', + AGY_MODELS_COUNT_FILE: join(fakeAgy.directory, 'models-count') + } + + const ordinary = probeAgyQuota(env) + await new Promise((resolve) => setTimeout(resolve, 200)) + const refresh = probeAgyQuota(env, { refresh: true }) + + const [ordinaryResult, refreshResult] = await Promise.all([ordinary, refresh]) + expect(ordinaryResult.status).toBe('error') + expect(refreshResult.status).toBe('ok') + + const events = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + expect(events.filter((event) => event === 'models')).toHaveLength(2) + expect(events.filter((event) => event === '-p /usage --output-format json')).toHaveLength(1) + expect(events.filter((event) => event === '-p /credits --output-format json')).toHaveLength(1) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('bounds a refresh that joins a failing probe by the deadline it arrived under', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { + ...fakeAgy.env, + AGY_FAKE_MODELS_DELAY: '4.5', + AGY_FAKE_USAGE_FAIL: 'hang' + } + + const ordinary = probeAgyQuota(env) + await new Promise((resolve) => setTimeout(resolve, 200)) + const refreshStartedAt = Date.now() + const refresh = probeAgyQuota(env, { refresh: true }) + + const [ordinaryResult, refreshResult] = await Promise.all([ordinary, refresh]) + const elapsed = Date.now() - refreshStartedAt + + expect(ordinaryResult.status).toBe('error') + expect(refreshResult.status).toBe('error') + const events = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + expect(events.filter((event) => event === 'models')).toHaveLength(2) + // The fresh attempt must run on the budget left from when the + // refresh arrived, so the joined sequence stays inside one probe + // budget instead of getting a second full budget after the join. + expect(elapsed).toBeLessThan(18_000) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }, 30_000) + + agyFixtureIt('recovers agy quotas on the next ordinary request after the user signs in', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({ + agent, + available: agent === 'agy' + })) + try { + const fakeAgy = createFakeAgy() + try { + const agyStatus = async (env: NodeJS.ProcessEnv) => + (await getAgentQuotasResponse({ env })).accounts.find((account) => account.agent === 'agy')?.status + + expect(await agyStatus({ ...fakeAgy.env, AGY_FAKE_AUTH: 'unauthenticated' })).toBe('unauthenticated') + // the one-minute response cache still serves the last verdict + expect(await agyStatus(fakeAgy.env)).toBe('unauthenticated') + // the next uncached poll must run the safe models check again + vi.setSystemTime(Date.now() + 61_000) + expect(await agyStatus(fakeAgy.env)).toBe('ok') + const events = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + expect(events.filter((event) => event === 'models')).toHaveLength(2) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + } finally { + vi.useRealTimers() + } + }, 15_000) + + agyFixtureIt('single-flights the agy probe across concurrent callers including refresh', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_MODELS_DELAY: '0.3' } + const [first, second, third] = await Promise.all([ + probeAgyQuota(env), + probeAgyQuota(env, { refresh: true }), + probeAgyQuota(env) + ]) + + expect(first.status).toBe('ok') + expect(second.status).toBe('ok') + expect(third.status).toBe('ok') + const events = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + expect(events.filter((event) => event === 'models')).toHaveLength(1) + expect(events.filter((event) => event.startsWith('-p /usage'))).toHaveLength(1) + expect(events.filter((event) => event.startsWith('-p /credits'))).toHaveLength(1) + + // the inflight guard clears after completion so later probes run fresh + await probeAgyQuota(env) + const eventsAfter = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + expect(eventsAfter.filter((event) => event === 'models')).toHaveLength(2) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('reports an error status without print commands when the models check fails for reasons other than the sign-in message', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_MODELS_FAIL: 'exit2' } + const first = await probeAgyQuota(env) + expect(first.status).toBe('error') + expect(first.note).toBeTruthy() + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models']) + + // a short error cache keeps immediate polls from re-spawning the check + expect((await probeAgyQuota(env)).status).toBe('error') + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models']) + + // refresh bypasses the short error cache and re-runs the safe check + expect((await probeAgyQuota(env, { refresh: true })).status).toBe('error') + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models', 'models']) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('returns an error status when the models check times out and never runs print commands', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_MODELS_FAIL: 'hang' } + const startedAt = Date.now() + const result = await probeAgyQuota(env) + + expect(result.status).toBe('error') + expect(Date.now() - startedAt).toBeLessThan(9_000) + expect(readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n')).toEqual(['models']) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }, 15_000) + + agyFixtureIt('treats a non-zero usage exit as an error even when the usage JSON parses', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_USAGE_EXIT: '7' } + const result = await probeAgyQuota(env) + + expect(result.status).toBe('error') + expect(result.buckets).toEqual([]) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + + agyFixtureIt('caches the error after a usage timeout so immediate polls do not re-spawn', async () => { + const fakeAgy = createFakeAgy() + try { + const env = { ...fakeAgy.env, AGY_FAKE_USAGE_FAIL: 'hang' } + const timedOut = await probeAgyQuota(env) + expect(timedOut.status).toBe('error') + expect(timedOut.note).toContain('timed out') + + const next = await probeAgyQuota(env) + expect(next.status).toBe('error') + const events = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + expect(events.filter((event) => event === 'models')).toHaveLength(1) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }, 15_000) + + agyFixtureIt('stops a hung credits child and its grandchild without a tree scan on timeout', async () => { + const fakeAgy = createFakeAgy() + const pgrepDir = mkdtempSync(join(tmpdir(), 'hapi-agy-pgrep-')) + writeFileSync(join(pgrepDir, 'pgrep'), '#!/bin/sh\nsleep 3.5\nexit 1\n', { mode: 0o755 }) + const creditsPidFile = join(fakeAgy.directory, 'credits.pid') + const grandchildPidFile = join(fakeAgy.directory, 'grandchild.pid') + const pidFrom = (file: string) => Number(readFileSync(file, 'utf8').trim()) + const isAlive = (pid: number) => { + try { + process.kill(pid, 0) + return true + } catch (error) { + return (error as NodeJS.ErrnoException).code !== 'ESRCH' + } + } + const waitForGone = async (pid: number) => { + const deadline = Date.now() + 2_000 + while (isAlive(pid) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 20)) + } + return !isAlive(pid) + } + const originalPath = process.env.PATH + process.env.PATH = `${pgrepDir}${delimiter}${originalPath ?? ''}` + try { + const env = { + ...fakeAgy.env, + AGY_FAKE_CREDITS_FORK: 'hang', + AGY_CREDITS_PID: creditsPidFile, + AGY_GRANDCHILD_PID: grandchildPidFile + } + const startedAt = Date.now() + const result = await probeAgyQuota(env) + const elapsed = Date.now() - startedAt + + expect(result.status).toBe('ok') + expect(elapsed).toBeLessThan(7_000) + expect(await waitForGone(pidFrom(creditsPidFile))).toBe(true) + expect(await waitForGone(pidFrom(grandchildPidFile))).toBe(true) + } finally { + for (const file of [creditsPidFile, grandchildPidFile]) { + try { + process.kill(pidFrom(file), 'SIGKILL') + } catch {} + } + process.env.PATH = originalPath + rmSync(pgrepDir, { recursive: true, force: true }) + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }, 20_000) + + agyFixtureIt('starts agy credits alongside usage after the sign-in check', async () => { + const fakeAgy = createFakeAgy() + try { + const result = await probeAgyQuota(fakeAgy.env) + const events = readFileSync(fakeAgy.eventLog, 'utf8').trim().split('\n') + + expect(result.status).toBe('ok') + expect(events[0]).toBe('models') + expect(events.filter((event) => event === '-p /usage --output-format json')).toHaveLength(1) + expect(events.filter((event) => event === '-p /credits --output-format json')).toHaveLength(1) + } finally { + rmSync(fakeAgy.directory, { recursive: true, force: true }) + } + }) + it('extracts Codex rate limit buckets across primary, secondary, and rateLimitsByLimitId', () => { const buckets = extractCodexQuotaBuckets({ rateLimits: { diff --git a/cli/src/agent/agentQuotas.ts b/cli/src/agent/agentQuotas.ts index 9e84e87e6fa..16c1cb21b98 100644 --- a/cli/src/agent/agentQuotas.ts +++ b/cli/src/agent/agentQuotas.ts @@ -18,6 +18,7 @@ import type { CodexRateLimitWindow } from '@/codex/appServerTypes' import { resolveHapiHomeDir } from '@/configuration' +import { hasAgyAuthRequiredOutput, hasAgyModelListing } from '@/modules/common/agyModels' import { withBunRuntimeEnv } from '@/utils/bunRuntime' import { killProcessByChildProcess } from '@/utils/process' import { getAgentAvailability } from './agentAvailability' @@ -26,6 +27,12 @@ import { getAgentLaunchCommand } from './agentLaunchCommand' const CACHE_TTL_MS = 60_000 const DEFAULT_PROVIDER_PROBE_TIMEOUT_MS = 5_000 const AGY_PROBE_TIMEOUT_MS = DEFAULT_PROVIDER_PROBE_TIMEOUT_MS +// One deadline bounds the models check plus the parallel usage and credits +// pair: each command gets only the time left in the hub's 20s quota window, +// minus 3s to write the response. A slow agy then cannot time out the whole +// machine quota request. +const AGY_PROBE_BUDGET_MS = 20_000 - 3_000 +const AGY_ERROR_CACHE_TTL_MS = 60_000 const CLAUDE_PROBE_TIMEOUT_MS = DEFAULT_PROVIDER_PROBE_TIMEOUT_MS const CLAUDE_INIT_REQ_ID = 'hapi-claude-quota-init' const CLAUDE_STATUS_REQ_ID = 'hapi-claude-quota-status' @@ -195,6 +202,10 @@ let cachedResponse: { startedAt: number; expiresAt: number; response: AgentQuota let inflightPromise: Promise | null = null const liveClaudeBuckets = new Map() let liveAgyTierLabel: string | null = null +let agyErrorUntil = 0 +let agyErrorNote: string | null = null +let agyProbeInflight: Promise | null = null +let agyRefreshInflight: Promise | null = null function shortHash(value: string): string { return createHash('sha256').update(value).digest('hex').slice(0, 16) @@ -634,12 +645,7 @@ export function parseAgyUsageCommandJson(stdout: string): { buckets: AgentQuotaBucket[] unauthenticated?: boolean } | null { - const lower = stdout.toLowerCase() - if ( - lower.includes('authentication required') - || lower.includes('please sign in') - || lower.includes('not logged in') - ) { + if (hasAgyAuthRequiredOutput(stdout)) { return { buckets: [], unauthenticated: true } } @@ -716,14 +722,32 @@ export function parseAgyCreditsCommandJson(stdout: string): number | null { return null } -function runAgyHeadlessCommand(command: string, promptCommand: string, env: NodeJS.ProcessEnv): Promise<{ stdout: string; stderr: string }> { +type AgyCommandOutput = { + stdout: string + stderr: string + exitCode: number | null +} + +function agyCommandTimeoutMs(deadlineAt: number): number { + return Math.min(AGY_PROBE_TIMEOUT_MS, Math.max(0, deadlineAt - Date.now())) +} + +async function runAgyCommand( + command: string, + args: string[], + label: string, + env: NodeJS.ProcessEnv, + timeoutMs: number = AGY_PROBE_TIMEOUT_MS +): Promise { return new Promise((resolve, reject) => { - const child = spawn(command, ['-p', promptCommand, '--output-format', 'json'], { + const useProcessGroup = process.platform !== 'win32' + const child = spawn(command, args, { cwd: homedir(), env: buildAgyAcpEnv(env), stdio: ['ignore', 'pipe', 'pipe'], shell: false, - windowsHide: process.platform === 'win32' + windowsHide: process.platform === 'win32', + ...(useProcessGroup ? { detached: true } : {}) }) let stdout = '' @@ -738,9 +762,15 @@ function runAgyHeadlessCommand(command: string, promptCommand: string, env: Node } const timer = setTimeout(() => { - void killProcessByChildProcess(child, true).catch(() => undefined) - finish(() => reject(new Error(`Antigravity ${promptCommand} timed out`))) - }, AGY_PROBE_TIMEOUT_MS) + if (useProcessGroup && child.pid) { + try { + process.kill(-child.pid, 'SIGKILL') + } catch {} + } else { + void killProcessByChildProcess(child, true).catch(() => undefined) + } + finish(() => reject(new Error(`Antigravity ${label} timed out`))) + }, timeoutMs) child.stdout?.on('data', (chunk) => { stdout += chunk.toString() @@ -751,13 +781,80 @@ function runAgyHeadlessCommand(command: string, promptCommand: string, env: Node child.on('error', (error) => { finish(() => reject(error)) }) - child.on('close', () => { - finish(() => resolve({ stdout, stderr })) + child.on('close', (exitCode) => { + finish(() => resolve({ stdout, stderr, exitCode })) }) }) } -export async function probeAgyQuota(env: NodeJS.ProcessEnv = process.env): Promise { +function runAgyHeadlessCommand( + command: string, + promptCommand: string, + env: NodeJS.ProcessEnv, + timeoutMs?: number +): Promise { + return runAgyCommand(command, ['-p', promptCommand, '--output-format', 'json'], promptCommand, env, timeoutMs) +} + +function clearAgyErrorCache(): void { + agyErrorUntil = 0 + agyErrorNote = null +} + +function cacheAgyError(note: string): void { + agyErrorUntil = Date.now() + AGY_ERROR_CACHE_TTL_MS + agyErrorNote = note +} + +type AgyAuthCheck = + | { outcome: 'authenticated' } + | { outcome: 'unauthenticated' } + | { outcome: 'error'; note: string } + +function classifyAgyAuthCheck(result: AgyCommandOutput): AgyAuthCheck { + // The sign-in message can arrive on either stream, but only stdout carries + // the model listing; a diagnostic on stderr must not stand in for one. + if (hasAgyAuthRequiredOutput(`${result.stdout}\n${result.stderr}`)) { + return { outcome: 'unauthenticated' } + } + if (result.exitCode !== 0) { + const exitLabel = result.exitCode === null ? 'signal' : `exit ${result.exitCode}` + return { outcome: 'error', note: `Antigravity auth check failed (${exitLabel})` } + } + if (!hasAgyModelListing(result.stdout)) { + return { outcome: 'error', note: 'Antigravity auth check found no model listing' } + } + return { outcome: 'authenticated' } +} + +async function checkAgyAuthentication( + command: string, + env: NodeJS.ProcessEnv, + options?: { refresh?: boolean; timeoutMs?: number } +): Promise { + if (!options?.refresh) { + if (agyErrorUntil > Date.now() && agyErrorNote) return { outcome: 'error', note: agyErrorNote } + } + try { + const result = await runAgyCommand(command, ['models'], 'models', env, options?.timeoutMs) + const classified = classifyAgyAuthCheck(result) + if (classified.outcome === 'unauthenticated') clearAgyErrorCache() + if (classified.outcome === 'error') cacheAgyError(classified.note) + return classified + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + const note = message.includes('timed out') + ? 'Antigravity auth check timed out' + : 'Antigravity auth check failed' + cacheAgyError(note) + return { outcome: 'error', note } + } +} + +export async function probeAgyQuota( + env: NodeJS.ProcessEnv = process.env, + options?: { refresh?: boolean; deadlineAt?: number } +): Promise { const updatedAt = Date.now() const availability = getAgentAvailability('agy', env) if (!availability.available) { @@ -771,14 +868,65 @@ export async function probeAgyQuota(env: NodeJS.ProcessEnv = process.env): Promi } const executable = getAgentLaunchCommand('agy', env) - try { - const [usageOut, creditsOut] = await Promise.all([ - runAgyHeadlessCommand(executable, '/usage', env), - runAgyHeadlessCommand(executable, '/credits', env).catch(() => ({ stdout: '', stderr: '' })) - ]) + const refresh = options?.refresh === true + if (!refresh) { + if (agyErrorUntil > updatedAt && agyErrorNote) { + return { + agent: 'agy', + available: true, + status: 'error', + buckets: [], + note: agyErrorNote, + updatedAt + } + } + } + // One auth check + print sequence at a time, shared by every caller, so + // concurrent quota requests can never multiply the print-mode invocations. + if (agyProbeInflight) { + if (!refresh) return agyProbeInflight + if (agyRefreshInflight) return agyRefreshInflight + // The hub bounds the whole machine quota response, so the refresh's + // budget starts when the refresh arrives, not when the joined probe + // finishes: the fresh attempt only gets the time that is left. + const deadlineAt = Date.now() + AGY_PROBE_BUDGET_MS + const previous = agyProbeInflight + agyRefreshInflight = previous.then((result) => { + // The joined probe may have failed before the refresh started, so + // any non-success verdict can be stale: one fresh attempt lets the + // refresh answer from the current connection instead. + if (result.status !== 'unauthenticated' && result.status !== 'error') return result + if (agyProbeInflight && agyProbeInflight !== previous) return agyProbeInflight + agyProbeInflight = null + if (deadlineAt <= Date.now()) { + // The response window closed while the joined probe ran, so a + // fresh sequence must not start; the other accounts still ship. + const expired: AgentQuotaAccount = { + agent: 'agy', + available: true, + status: 'error', + buckets: [], + note: 'Antigravity quota refresh ran out of time', + updatedAt: Date.now() + } + return expired + } + return probeAgyQuota(env, { refresh: true, deadlineAt }) + }).finally(() => { + agyRefreshInflight = null + }) + return agyRefreshInflight + } - const parsedUsage = parseAgyUsageCommandJson(`${usageOut.stdout}\n${usageOut.stderr}`) - if (parsedUsage?.unauthenticated) { + const probe = (async (): Promise => { + // A refresh that joined an in-flight probe hands down the deadline it + // arrived under, so the fresh attempt cannot outlive the response window. + const deadlineAt = options?.deadlineAt ?? Date.now() + AGY_PROBE_BUDGET_MS + const auth = await checkAgyAuthentication(executable, env, { + refresh, + timeoutMs: agyCommandTimeoutMs(deadlineAt) + }) + if (auth.outcome === 'unauthenticated') { return { agent: 'agy', available: true, @@ -788,43 +936,88 @@ export async function probeAgyQuota(env: NodeJS.ProcessEnv = process.env): Promi updatedAt } } - - if (!parsedUsage) { + if (auth.outcome === 'error') { return { agent: 'agy', available: true, status: 'error', buckets: [], - note: 'Unable to parse Antigravity quota output', + note: auth.note, updatedAt } } + // The auth check succeeded: a stale error verdict must not short-circuit + // later normal polls. + clearAgyErrorCache() - const remainingCredits = parseAgyCreditsCommandJson(creditsOut.stdout) - const creditsLabel = remainingCredits !== null && remainingCredits > 0 - ? `${remainingCredits.toLocaleString('en-US')} G1 credits` - : null + try { + // Start both commands before waiting: credits must not wait for + // usage, but a failed usage still drops credits instead of + // returning partial data. + const usage = runAgyHeadlessCommand(executable, '/usage', env, agyCommandTimeoutMs(deadlineAt)) + // If usage fails, credits can run until its own timeout while an explicit refresh starts a new probe. + const credits = runAgyHeadlessCommand(executable, '/credits', env, agyCommandTimeoutMs(deadlineAt)) + .catch(() => ({ stdout: '', stderr: '', exitCode: null })) + const usageOut = await usage + + const parsedUsage = parseAgyUsageCommandJson(`${usageOut.stdout}\n${usageOut.stderr}`) + if (parsedUsage?.unauthenticated) { + clearAgyErrorCache() + return { + agent: 'agy', + available: true, + status: 'unauthenticated', + buckets: [], + note: 'Not signed in to Antigravity', + updatedAt + } + } - return { - agent: 'agy', - available: true, - status: 'ok', - accountLabel: null, - planLabel: liveAgyTierLabel ?? readPersistedLiveQuotaState(env).agyTierLabel ?? null, - creditsLabel, - buckets: parsedUsage.buckets, - updatedAt - } - } catch (error) { - return { - agent: 'agy', - available: true, - status: 'error', - buckets: [], - note: error instanceof Error ? error.message : 'Failed to query Antigravity quota', - updatedAt + if (usageOut.exitCode !== 0 || !parsedUsage) { + cacheAgyError('Unable to parse Antigravity quota output') + return { + agent: 'agy', + available: true, + status: 'error', + buckets: [], + note: 'Unable to parse Antigravity quota output', + updatedAt + } + } + + const creditsOut = await credits + const remainingCredits = parseAgyCreditsCommandJson(creditsOut.stdout) + const creditsLabel = remainingCredits !== null && remainingCredits > 0 + ? `${remainingCredits.toLocaleString('en-US')} G1 credits` + : null + + return { + agent: 'agy', + available: true, + status: 'ok', + accountLabel: null, + planLabel: liveAgyTierLabel ?? readPersistedLiveQuotaState(env).agyTierLabel ?? null, + creditsLabel, + buckets: parsedUsage.buckets, + updatedAt + } + } catch (error) { + const note = error instanceof Error ? error.message : 'Failed to query Antigravity quota' + cacheAgyError(note) + return { + agent: 'agy', + available: true, + status: 'error', + buckets: [], + note, + updatedAt + } } - } + })() + agyProbeInflight = probe + return await probe.finally(() => { + if (agyProbeInflight === probe) agyProbeInflight = null + }) } type ClaudeControlProbeResult = { @@ -1230,7 +1423,7 @@ export async function getAgentQuotasResponse(options?: { const promise = (async (): Promise => { const accounts = await Promise.all([ probeCodexQuota(env, probeTimeoutMs), - probeAgyQuota(env), + probeAgyQuota(env, { refresh }), probeClaudeQuota(env) ]) const fetchedAt = Date.now() @@ -1259,5 +1452,9 @@ export function _resetAgentQuotasCacheForTests(): void { inflightPromise = null liveClaudeBuckets.clear() liveAgyTierLabel = null + agyErrorUntil = 0 + agyErrorNote = null + agyProbeInflight = null + agyRefreshInflight = null claudeStatusProbeOverrideForTests = null } diff --git a/cli/src/agent/sessionBase.ts b/cli/src/agent/sessionBase.ts index 45a66c73986..cdce03a6978 100644 --- a/cli/src/agent/sessionBase.ts +++ b/cli/src/agent/sessionBase.ts @@ -77,7 +77,11 @@ export class AgentSessionBase { this.queue.onBatchConsumed = opts.acknowledgeMessagesOnDequeue === false ? null - : (localIds) => this.client.emitMessagesConsumed(localIds); + // Same reason as `commitBatch`: an ordinary acknowledgement keeps + // its one-argument shape (#1717). + : (localIds, options) => (options?.maintenance + ? this.client.emitMessagesConsumed(localIds, { maintenance: true }) + : this.client.emitMessagesConsumed(localIds)); this.client.keepAlive(this.thinking, this.mode, this.getKeepAliveRuntime()); this.keepAliveInterval = setInterval(() => { diff --git a/cli/src/agy/agyAcpRemoteLauncher.test.ts b/cli/src/agy/agyAcpRemoteLauncher.test.ts index c8e3ce311e5..c8397cdd27f 100644 --- a/cli/src/agy/agyAcpRemoteLauncher.test.ts +++ b/cli/src/agy/agyAcpRemoteLauncher.test.ts @@ -362,6 +362,11 @@ function agentState(client: ReturnType): { requests?: Record< .reduce((state, [update]) => (update as (s: object) => object)(state), {} as object); } +function metadataOf(client: ReturnType): { hapiMcpUrl?: string } { + return client.updateMetadata.mock.calls + .reduce((metadata, [update]) => (update as (m: object) => object)(metadata), {} as object) as { hapiMcpUrl?: string }; +} + function sessionEvents(client: ReturnType): unknown[] { return client.sendSessionEvent.mock.calls.map(([event]) => event); } @@ -404,6 +409,22 @@ describe('AgyAcpRemoteLauncher', () => { expect(backend.disconnected).toBe(true); }); + it.each([['http://127.0.0.1:0/mcp', undefined], ['http://newer/', 'http://newer/']])( + 'cleans up its MCP URL on startup failure without removing a replacement', + async (storedUrl, expectedUrl) => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + client.updateMetadata((metadata: object) => ({ ...metadata, hapiMcpUrl: storedUrl })); + backend.initialize = async () => { throw new Error('startup failed'); }; + await expect(launch(session, [backend]).run).rejects.toThrow('startup failed'); + const metadata = client.updateMetadata.mock.calls + .reduce((current, [update]) => (update as (m: object) => object)(current), {}) as { hapiMcpUrl?: string }; + expect(metadata.hapiMcpUrl).toBe(expectedUrl); + expect(mcpBridgeHarness.stop).toHaveBeenCalledOnce(); + queue.close(); + } + ); + it('acknowledges a prompt as soon as session/prompt is sent even without a user_message_chunk echo', async () => { const { session, queue, client } = makeSession(); const backend = new FakeAgyBackend(); @@ -1859,6 +1880,30 @@ describe('AgyAcpRemoteLauncher delivery and recovery', () => { expect(sessionEvents(client).filter((event) => (event as { type: string }).type === 'error')).toEqual([]); }); + it('unpublishes its MCP URL before kill returns while ACP initialization is still waiting', async () => { + const { session, queue, client } = makeSession(); + const backend = new FakeAgyBackend(); + let failStart!: (error: Error) => void; + backend.initializeGate = new Promise((_resolve, reject) => { failStart = reject; }); + const { run } = launch(session, [backend]); + const stopsBefore = mcpBridgeHarness.stop.mock.calls.length; + await vi.waitFor(() => expect(backend.calls).toEqual(['initialize'])); + // What startHappyServer published once the bridge was listening. + client.updateMetadata((metadata: object) => ({ ...metadata, hapiMcpUrl: 'http://127.0.0.1:0/mcp' })); + expect(metadataOf(client).hapiMcpUrl).toBe('http://127.0.0.1:0/mcp'); + + await session.kill(); + // The runner archives the session and closes the client as soon as kill + // returns, so the launcher's own cleanup is too late to unpublish here. + expect(metadataOf(client).hapiMcpUrl).toBeUndefined(); + + failStart(new Error('ACP transport closed')); + queue.close(); + await run; + // One stop for the launcher, however many teardown paths ran. + expect(mcpBridgeHarness.stop.mock.calls.length - stopsBefore).toBe(1); + }); + it('holds steers that a later steer answered early when Stop comes before their echo', async () => { const backend = new FakeAgyBackend(); const { queue, client, run, release } = await heldTurn(backend); diff --git a/cli/src/agy/agyAcpRemoteLauncher.ts b/cli/src/agy/agyAcpRemoteLauncher.ts index 7f54639c9ed..fd17abf79ff 100644 --- a/cli/src/agy/agyAcpRemoteLauncher.ts +++ b/cli/src/agy/agyAcpRemoteLauncher.ts @@ -2495,9 +2495,30 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { }); } + /** + * The runner archives the session and closes the client as soon as the kill + * handler returns, so the bridge URL has to be unpublished there and not + * only in cleanup, which may run after the client is gone. Idempotent: both + * paths call it and only the first one owns the server. + */ + private stopMcpBridge(): void { + const server = this.happyServer; + if (!server) return; + this.happyServer = null; + try { + server.stop(); + } finally { + // Guarded by URL so a bridge that replaced this one keeps its own. + this.session.client.updateMetadata((metadata) => metadata.hapiMcpUrl === server.url + ? { ...metadata, hapiMcpUrl: undefined } + : metadata); + } + } + private async handleKill(): Promise { const turnSettled = this.turnSettled; this.clearBackgroundTasksSnapshot(); + this.stopMcpBridge(); await this.requestExit('exit', async () => { await this.handleAbort(); await this.cancelPendingStart(); @@ -2527,10 +2548,11 @@ export class AgyAcpRemoteLauncher extends RemoteLauncherBase { this.permissionHandler = null; const backend = this.backend; this.backend = null; - await this.disconnectBackend(backend); - const happyServer = this.happyServer; - this.happyServer = null; - happyServer?.stop(); + try { + await this.disconnectBackend(backend); + } finally { + this.stopMcpBridge(); + } logger.debug('[agy-acp] cleanup done'); } } diff --git a/cli/src/api/apiSession.ts b/cli/src/api/apiSession.ts index fd9bcd5680e..a4572b0bc48 100644 --- a/cli/src/api/apiSession.ts +++ b/cli/src/api/apiSession.ts @@ -1392,7 +1392,10 @@ if (isReconnect) { }, 'droppable') } - emitMessagesConsumed(localIds: string[], options?: { clearQueuedThinkingGrace?: boolean; steered?: boolean }): void { + emitMessagesConsumed( + localIds: string[], + options?: { clearQueuedThinkingGrace?: boolean; steered?: boolean; maintenance?: boolean } + ): void { if (localIds.length === 0) return // `clearQueuedThinkingGrace` is an opt-in signal for the hub to drop // the 15s queued-thinking grace immediately. Only synchronous handlers @@ -1400,11 +1403,15 @@ if (isReconnect) { // inside `onUserMessage`) should set it — normal queue drains still // need the grace so the spinner doesn't flicker between drain and // backend.prompt start. + // `maintenance` is a separate axis from the grace: it says this + // acknowledgement consumed a COMMAND rather than delivering a prompt, + // so the hub must not read it as an answer to a blocked report (#1717). const payload: { sid: string localIds: string[] clearQueuedThinkingGrace?: boolean steered?: boolean + maintenance?: boolean } = { sid: this.sessionId, localIds @@ -1415,6 +1422,9 @@ if (isReconnect) { if (options?.steered) { payload.steered = true } + if (options?.maintenance) { + payload.maintenance = true + } this.emitOrQueue(() => this.socket.emit('messages-consumed', payload)) } diff --git a/cli/src/bin/hapiBin.test.ts b/cli/src/bin/hapiBin.test.ts index ee3fc3dc069..d1d4e28e54f 100644 --- a/cli/src/bin/hapiBin.test.ts +++ b/cli/src/bin/hapiBin.test.ts @@ -10,8 +10,6 @@ const require = createRequire(import.meta.url); const binModulePath = path.resolve(process.cwd(), 'bin/hapi.cjs'); const packageVersion = require(path.resolve(process.cwd(), 'package.json')).version; const { - displayArgsForFailure, - formatCommand, isSupportedPlatform, normalizeExecError, reportExecutionFailure, @@ -101,6 +99,20 @@ describe('hapi binary launcher package versions', () => { expect(args).toEqual(['runner', 'start-sync']); }); + it.skipIf(process.platform === 'win32')('keeps argv out of stderr when the binary fails', () => { + const binaryPath = installPlatformPackage(version); + mkdirSync(path.dirname(binaryPath), { recursive: true }); + writeFileSync(binaryPath, '#!/bin/sh\necho "child diagnostic" >&2\nexit 3\n', { mode: 0o755 }); + const sentinel = 'sekrit-launcher-e2e'; + + const result = spawnSync(process.execPath, [launcherPath, 'hub', '--token', sentinel], { encoding: 'utf-8' }); + + expect(result.status).toBe(3); + expect(result.stderr).toContain('child diagnostic'); + expect(result.stderr).toContain('Binary exited with status 3.'); + expect(result.stderr).not.toContain(sentinel); + }); + it('still diagnoses a missing optional dependency', () => { expect(require(launcherPath).getBinaryPath()).toBeNull(); @@ -113,22 +125,18 @@ describe('hapi binary launcher package versions', () => { }); describe('hapi binary launcher error reporting', () => { - it('formats command with shell-safe JSON quoting', () => { - const command = formatCommand('/tmp/hapi', ['serve', '--name', 'my agent']); - expect(command).toBe('"/tmp/hapi" "serve" "--name" "my agent"'); - }); - it('normalizes child process execution errors', () => { const normalized = normalizeExecError({ status: 132, signal: 'SIGILL', + code: 'ERR', message: 'Command failed: /tmp/hapi', }); expect(normalized).toEqual({ status: 132, signal: 'SIGILL', - message: 'Command failed: /tmp/hapi', + code: 'ERR', }); }); @@ -140,7 +148,7 @@ describe('hapi binary launcher error reporting', () => { { status: 132, signal: 'SIGILL', - message: 'Illegal instruction (core dumped)', + message: 'Command failed: /tmp/hapi serve --port 3000', }, '/tmp/hapi', ['serve', '--port', '3000'], @@ -149,111 +157,38 @@ describe('hapi binary launcher error reporting', () => { expect(result).toEqual({ status: 132, signal: 'SIGILL' }); expect(lines).toEqual([ - 'Failed to execute: "/tmp/hapi" "serve" "--port" "3000"', + 'Failed to execute: "/tmp/hapi"', 'Binary terminated by signal SIGILL.', 'Binary exited with status 132.', - 'Illegal instruction (core dumped)', ]); }); - it('omits job run workload argv from npm launcher failure output', () => { - const sentinel = 'sekrit-token-not-for-stderr'; - const args = [ - 'job', - 'run', - 'sess', - 'migrate', - '--label=m', - '--detach', - '--', - 'curl', - '-H', - `Authorization: Bearer ${sentinel}`, - ]; - expect(displayArgsForFailure(args)).toEqual([ - 'job', - 'run', - 'sess', - 'migrate', - '--label=m', - '--detach', - '--', - '', - ]); - + it('reports why the binary could not start', () => { const lines: string[] = []; + const result = reportExecutionFailure( - { - status: 1, - message: - `Command failed: /tmp/hapi ${args.join(' ')}\n` - + 'job registration precondition failed', - }, + { code: 'EACCES', message: 'spawnSync /tmp/hapi EACCES' }, '/tmp/hapi', - args, + ['serve'], (line: string) => lines.push(line), ); - expect(result).toEqual({ status: 1, signal: null }); - expect(lines.join('\n')).not.toContain(sentinel); + expect(result).toEqual({ status: null, signal: null }); expect(lines).toEqual([ - 'Failed to execute: "/tmp/hapi" "job" "run" "sess" "migrate" "--label=m" "--detach" "--" ""', - 'Binary exited with status 1.', + 'Failed to execute: "/tmp/hapi"', + 'Binary could not be started: EACCES.', ]); }); - it('omits raw exec message when short flags overlap credential args', () => { - // `-u` is a prefix of the userinfo token; token-by-token redact would - // corrupt the longer arg and leave credential text behind. - const credential = 'user:sekrit-overlap-token'; - const args = [ - 'job', - 'run', - 'sess', - 'k', - '--label=x', - '--detach', - '--', - 'curl', - '-u', - credential, - 'https://example.test/', - ]; - const lines: string[] = []; - reportExecutionFailure( - { - status: 1, - message: `Command failed: /tmp/hapi ${args.join(' ')}`, - }, - '/tmp/hapi', - args, - (line: string) => lines.push(line), - ); - - expect(lines.join('\n')).not.toContain('sekrit-overlap-token'); - expect(lines.join('\n')).not.toContain(credential); - expect(lines.some((line) => line.startsWith('Command failed:'))).toBe(false); - expect(lines[0]).toContain('""'); - }); - - it('redacts workload when flags precede the run action', () => { - // Parser accepts `job --detach run … -- `; launcher must not - // require `run` immediately after `job`. - const sentinel = 'sekrit-flag-before-run'; - const args = [ - 'job', - '--detach', - 'run', - 'sess', - 'k', - '--label=x', - '--', - 'curl', - '-H', - `Authorization: Bearer ${sentinel}`, - ]; + const sentinel = 'sekrit-token-not-for-stderr'; + it.each([ + ['a plain command flag', ['hub', '--relay-token', sentinel]], + ['a job run workload', ['job', 'run', 'sess', 'k', '--label=m', '--', 'curl', '-H', `Authorization: Bearer ${sentinel}`]], + ['a short flag overlapping a credential', ['job', 'run', 'sess', 'k', '--', 'curl', '-u', `user:${sentinel}`]], + ['a leading runtime separator', ['--', 'job', 'run', 'sess', 'k', '--', 'sh', '-c', `echo ${sentinel}`]], + ])('omits argv and the raw exec message for %s', (_name, args) => { const lines: string[] = []; - reportExecutionFailure( + const result = reportExecutionFailure( { status: 1, message: `Command failed: /tmp/hapi ${args.join(' ')}`, @@ -263,60 +198,12 @@ describe('hapi binary launcher error reporting', () => { (line: string) => lines.push(line), ); - expect(displayArgsForFailure(args)).toEqual([ - 'job', - '--detach', - 'run', - 'sess', - 'k', - '--label=x', - '--', - '', - ]); + expect(result).toEqual({ status: 1, signal: null }); expect(lines.join('\n')).not.toContain(sentinel); - expect(lines.some((line) => line.startsWith('Command failed:'))).toBe(false); - }); - - it('redacts workload after a leading runtime CLI separator', () => { - // Binary strips a leading `--` before dispatch; npm launcher sees raw argv. - const sentinel = 'sekrit-leading-separator'; - const args = [ - '--', - 'job', - 'run', - 'sess', - 'k', - '--label=x', - '--detach', - '--', - 'curl', - '-H', - `Authorization: Bearer ${sentinel}`, - ]; - const lines: string[] = []; - reportExecutionFailure( - { - status: 1, - message: `Command failed: /tmp/hapi ${args.join(' ')}`, - }, - '/tmp/hapi', - args, - (line: string) => lines.push(line), - ); - - expect(displayArgsForFailure(args)).toEqual([ - '--', - 'job', - 'run', - 'sess', - 'k', - '--label=x', - '--detach', - '--', - '', + expect(lines).toEqual([ + 'Failed to execute: "/tmp/hapi"', + 'Binary exited with status 1.', ]); - expect(lines.join('\n')).not.toContain(sentinel); - expect(lines.some((line) => line.startsWith('Command failed:'))).toBe(false); }); it('handles unknown failures with generic output', () => { diff --git a/cli/src/claude/runClaude.ts b/cli/src/claude/runClaude.ts index e36c2eff85e..5afdcf53b90 100644 --- a/cli/src/claude/runClaude.ts +++ b/cli/src/claude/runClaude.ts @@ -961,7 +961,13 @@ export async function runClaude(options: StartOptions = {}): Promise { if (!specialCommand.prompt) { if (localId) { - session.emitMessagesConsumed([localId]); + // Every other synchronous, locally-handled command + // (Codex, Pi, OpenCode, Copilot) sets this — a bare + // /plan only changes permission mode, it never reaches + // the agent, so without it the hub recorded genuine + // agent delivery and could clear an unanswered footer + // (#1717 cold-review round 36). + session.emitMessagesConsumed([localId], { clearQueuedThinkingGrace: true }); } logger.debugLargeJson('[start] /plan command applied without prompt:', message); return; diff --git a/cli/src/modules/common/agyModels.ts b/cli/src/modules/common/agyModels.ts index d5e02b2fd8a..37a5b45e259 100644 --- a/cli/src/modules/common/agyModels.ts +++ b/cli/src/modules/common/agyModels.ts @@ -7,8 +7,10 @@ import type { AgyModelsResponse } from '@hapi/protocol/apiTypes' export type ListAgyModelsResponse = AgyModelsResponse const AUTH_REQUIRED_PATTERNS = [ - 'Authentication required', - 'Please sign in', + 'authentication required', + 'authentication failed', + 'please sign in', + 'not logged in', 'accounts.google.com/o/oauth2/auth' ] @@ -169,6 +171,9 @@ function parseAgyModelsOutput(output: string): AgyModelsResponse['availableModel continue } // Accept a known name verbatim, or anything shaped like "Name (Variant)". + // A sign-in diagnostic has that shape ("Authentication failed (session + // expired)"), so only rows that carry no auth message may become models. + if (hasAgyAuthRequiredOutput(line)) continue const isKnown = NAME_TO_ID.has(line) const looksLikeModel = /^[A-Za-z][\w.\-/ ]*\([^)]+\)$/.test(line) if (!isKnown && !looksLikeModel) continue @@ -182,13 +187,19 @@ function parseAgyModelsOutput(output: string): AgyModelsResponse['availableModel export const _parseAgyModelsOutputForTests = parseAgyModelsOutput +export function hasAgyModelListing(output: string): boolean { + return parseAgyModelsJson(output) !== null || parseAgyModelsOutput(output) !== null +} + +export function hasAgyAuthRequiredOutput(output: string): boolean { + const lower = output.toLowerCase() + return AUTH_REQUIRED_PATTERNS.some((pattern) => lower.includes(pattern)) +} + function checkOutputForAuthError(output: string): string | null { - for (const pattern of AUTH_REQUIRED_PATTERNS) { - if (output.includes(pattern)) { - return 'Authentication required. Please run `agy` in a terminal to sign in with Google.' - } - } - return null + return hasAgyAuthRequiredOutput(output) + ? 'Authentication required. Please run `agy` in a terminal to sign in with Google.' + : null } // Build the env for the one-shot `agy models` probe. Auth must be as robust as diff --git a/cli/src/modules/sessionJob/attachSessionJob.test.ts b/cli/src/modules/sessionJob/attachSessionJob.test.ts index 13fd66c1193..9e05a770215 100644 --- a/cli/src/modules/sessionJob/attachSessionJob.test.ts +++ b/cli/src/modules/sessionJob/attachSessionJob.test.ts @@ -1,7 +1,18 @@ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { windowsSystemTool } from '@/utils/windowsSystemTools' import { attachSessionJob } from './attachSessionJob' import { SessionJobError } from './sessionJob' +const { spawnSyncMock } = vi.hoisted(() => ({ + spawnSyncMock: vi.fn() +})) + +vi.mock('cross-spawn', () => ({ + default: { + sync: spawnSyncMock + } +})) + vi.mock('./sessionJob', async () => { const actual = await vi.importActual('./sessionJob') return { @@ -228,4 +239,78 @@ describe('attachSessionJob', () => { }) } }) + + describe('on Windows with the real liveness probe', () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')! + + afterEach(() => { + Object.defineProperty(process, 'platform', originalPlatform) + spawnSyncMock.mockReset() + vi.restoreAllMocks() + }) + + function timedOut(command: string) { + const error = new Error(`spawnSync ${command} ETIMEDOUT`) as NodeJS.ErrnoException + error.code = 'ETIMEDOUT' + return { status: null, signal: 'SIGTERM', stdout: Buffer.from(''), stderr: Buffer.from(''), error } + } + + function completed(stdout: string) { + return { status: 0, stdout: Buffer.from(stdout), stderr: Buffer.from('') } + } + + it('keeps watching through a timed-out tasklist and completes only after confirmed exit', async () => { + Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) + const sessionJob = await import('./sessionJob') + vi.mocked(sessionJob.updateSessionJob).mockClear() + // Signal-0 is unreliable on win32; here it always throws, as it can + // for a live process. + vi.spyOn(process, 'kill').mockImplementation(() => { + throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' }) + }) + + // Process state per poll: attach check, then watcher polls. + const states = ['running', 'query-timeout', 'query-timeout', 'running', 'exited'] as const + let poll = 0 + const state = () => states[Math.min(poll, states.length - 1)]! + spawnSyncMock.mockImplementation((command: string) => { + if (command === windowsSystemTool('tasklist')) { + if (state() === 'query-timeout') return timedOut(command) + return completed(state() === 'running' ? 'job.exe 4242 Console 1 10,000 K' : 'INFO: No tasks are running') + } + if (command === windowsSystemTool('powershell')) { + if (state() === 'query-timeout') return timedOut(command) + return completed(state() === 'running' ? '2026-12-01T00:00:00.0000000Z' : '') + } + return completed('') + }) + + let pollsBeforeCompleted: number | undefined + vi.mocked(sessionJob.updateSessionJob).mockImplementation(async (opts) => { + if ((opts.body as { status?: string }).status === 'completed') { + pollsBeforeCompleted = poll + } + return { sessionId: 'sess-1', job: { key: 'xfer', label: 'xfer', status: 'completed' } } as never + }) + + const err = vi.spyOn(console, 'error').mockImplementation(() => {}) + const exitCode = await attachSessionJob({ + sessionIdPrefix: 'sess', + jobKey: 'xfer', + label: 'xfer', + pid: 4242, + pollMs: 5, + heartbeatMs: 10_000, + readStarttimeImpl: () => '2026-12-01T00:00:00.0000000Z', + sleepImpl: async () => { + poll += 1 + }, + onRegistered: vi.fn() + }) + err.mockRestore() + + expect(exitCode).toBe(0) + expect(pollsBeforeCompleted).toBe(states.length - 1) + }) + }) }) diff --git a/cli/src/modules/sessionJob/attachSessionJob.ts b/cli/src/modules/sessionJob/attachSessionJob.ts index 92eb99112b0..163c94c50eb 100644 --- a/cli/src/modules/sessionJob/attachSessionJob.ts +++ b/cli/src/modules/sessionJob/attachSessionJob.ts @@ -6,7 +6,7 @@ import { randomUUID } from 'node:crypto' import { readFileSync } from 'node:fs' import type { AttachedJobUpsert } from '@hapi/protocol' -import { getProcessStartMarker, isProcessAlive } from '@/utils/process' +import { getProcessStartMarker, probeProcessLiveness } from '@/utils/process' import { SessionJobError, clearSessionJob, @@ -106,7 +106,9 @@ function defaultIsAlive(pid: number, expectedStartMarker?: string): boolean { } } - if (!isProcessAlive(pid)) return false + // 'unknown' (Windows tasklist failed) is not proof of exit: fall through to + // the start-marker check, and keep watching if that is unavailable too. + if (probeProcessLiveness(pid) === 'exited') return false if (expectedStartMarker !== undefined) { const marker = getProcessStartMarker(pid) // Unavailable probe (ps/CIM timeout) is not proof of exit or reuse — diff --git a/cli/src/opencode/opencodeRemoteLauncher.ts b/cli/src/opencode/opencodeRemoteLauncher.ts index f74efc3a8c8..11967d2da7c 100644 --- a/cli/src/opencode/opencodeRemoteLauncher.ts +++ b/cli/src/opencode/opencodeRemoteLauncher.ts @@ -1285,8 +1285,18 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { // Keep /compact's dequeue-time consumption and cancellation // semantics separate and unchanged (see runOpencode.ts's // "No manual emitMessagesConsumed" comment). + // + // `maintenance`: this acknowledgement fires when the + // command is DEQUEUED, before compaction starts, and it + // consumes a command rather than delivering a prompt. The + // hub was reading it as an answer and clearing an + // unanswered blocker — and if the operator then cancelled + // during setup, the second acknowledgement consumed no + // rows, so the blocker stayed gone (#1717). Deliberately + // NOT `clearQueuedThinkingGrace`: /compact must keep that + // grace for the prompts queued behind it. batchSettled = true; - session.queue.commitBatch(batch); + session.queue.commitBatch(batch, { maintenance: true }); } const compactAbortController = isCompactBatch ? new AbortController() : null; if (compactAbortController) { diff --git a/cli/src/ui/doctor.test.ts b/cli/src/ui/doctor.test.ts index e4b8972f523..fc34f7cba65 100644 --- a/cli/src/ui/doctor.test.ts +++ b/cli/src/ui/doctor.test.ts @@ -20,4 +20,57 @@ describe('redactSettingsForDisplay', () => { expect(JSON.stringify(displaySettings)).not.toContain('cli-secret') expect(JSON.stringify(displaySettings)).not.toContain('client-secret') }) + + it('masks the VAPID private key but keeps the public key', () => { + const displaySettings = redactSettingsForDisplay({ + vapidKeys: { + publicKey: 'vapid-public', + privateKey: 'vapid-private-secret' + } + }) + + expect(displaySettings).toEqual({ + vapidKeys: { + publicKey: 'vapid-public', + privateKey: '***' + } + }) + expect(JSON.stringify(displaySettings)).not.toContain('vapid-private-secret') + }) + + it('masks hub secrets that share settings.json', () => { + const displaySettings = redactSettingsForDisplay({ + telegramBotToken: 'telegram-secret', + serverChanSendKey: 'serverchan-secret', + relayAuthKey: 'relay-secret', + providerCredentials: { OPENAI_API_KEY: 'provider-secret' } + }) + + const serialized = JSON.stringify(displaySettings) + for (const secret of ['telegram-secret', 'serverchan-secret', 'relay-secret', 'provider-secret']) { + expect(serialized).not.toContain(secret) + } + expect(displaySettings).toEqual({ + telegramBotToken: '***', + serverChanSendKey: '***', + relayAuthKey: '***', + providerCredentials: '***' + }) + }) + + it('masks fields it does not know about', () => { + const displaySettings = redactSettingsForDisplay({ + listenPort: 3006, + someFutureSecret: 'future-secret' + }) + + expect(displaySettings).toEqual({ + listenPort: 3006, + someFutureSecret: '***' + }) + }) + + it('omits unset fields', () => { + expect(redactSettingsForDisplay({ cliApiToken: undefined, telegramBotToken: '' })).toEqual({}) + }) }) diff --git a/cli/src/ui/doctor.ts b/cli/src/ui/doctor.ts index 4daae9948c6..1c45a36c3a4 100644 --- a/cli/src/ui/doctor.ts +++ b/cli/src/ui/doctor.ts @@ -47,12 +47,59 @@ export function getEnvironmentInfo(): Record { }; } +// settings.json is shared by the CLI and the hub. Only these fields are known to +// hold no secrets; every other field, including ones added later, is masked. +const DISPLAY_SAFE_SETTINGS = new Set([ + 'apiUrl', + 'serverUrl', + 'machineId', + 'machineIdConfirmedByServer', + 'runnerAutoStartWhenRunningHappy', + 'telegramNotification', + 'serverChanNotification', + 'serverChanBackgroundOnly', + 'listenHost', + 'listenPort', + 'publicUrl', + 'corsOrigins', + 'githubPrAwareness', + 'androidPushMode', + 'fcmServiceAccountPath', + 'iosPushMode', + 'iosPushRelayUrl', + 'apnsKeyP8Path', + 'apnsKeyId', + 'apnsTeamId', + 'apnsBundleId', + 'apnsEnv', + 'sessionSummaryContract', + 'peerSpawnDefaults', + 'sessionSummaryInChat', + 'autoBridgeTransientModelErrors', + 'translateInputByDefault', + 'followUpDefault', + 'elevenLabsMaxDurationSeconds' +]) + +const MASK = '***' + +function isUnset(value: unknown): boolean { + return value === undefined || value === null || value === '' +} + export function redactSettingsForDisplay(settings: Record): Record { - return { - ...settings, - cliApiToken: settings.cliApiToken ? '***' : undefined, - extraHeaders: settings.extraHeaders === undefined ? undefined : '***' + const display: Record = {} + for (const [key, value] of Object.entries(settings)) { + if (DISPLAY_SAFE_SETTINGS.has(key)) { + display[key] = value + } else if (key === 'vapidKeys' && value && typeof value === 'object') { + const { publicKey, privateKey } = value as Record + display[key] = { publicKey, privateKey: isUnset(privateKey) ? undefined : MASK } + } else if (!isUnset(value)) { + display[key] = MASK + } } + return display } function getLogFiles(logDir: string): { file: string, path: string, modified: Date }[] { diff --git a/cli/src/utils/MessageQueue2.ts b/cli/src/utils/MessageQueue2.ts index cd5b8ef4816..340dd15bed3 100644 --- a/cli/src/utils/MessageQueue2.ts +++ b/cli/src/utils/MessageQueue2.ts @@ -63,7 +63,10 @@ export class MessageQueue2 { private waiter: ((hasMessages: boolean) => void) | null = null; private closed = false; private onMessageHandler: ((message: string, mode: T) => void) | null = null; - onBatchConsumed: ((localIds: string[]) => void) | null = null; + /** #1717: `maintenance` marks a batch that consumed a command rather than + * delivering a prompt to the agent, so the hub does not read it as an + * answer to a blocked report. */ + onBatchConsumed: ((localIds: string[], options?: { maintenance?: boolean }) => void) | null = null; /** Optional synchronous admission, before removing or acknowledging a batch. */ beforeDequeue: (() => void) | null = null; modeHasher: (mode: T) => string; @@ -731,11 +734,18 @@ export class MessageQueue2 { } /** Clear in-flight marks for a deferred batch and emit its hub ACK. */ - commitBatch(batch: Pick, 'items'>): void { + commitBatch( + batch: Pick, 'items'>, + options?: { maintenance?: boolean } + ): void { const consumedLocalIds = this.clearInFlightBatch(batch); - if (consumedLocalIds.length > 0) { - this.onBatchConsumed?.(consumedLocalIds); - } + if (consumedLocalIds.length === 0) return; + // One argument for an ordinary commit. Passing an explicit `undefined` + // changed the observed call shape and broke exact-call assertions + // across Copilot, Cursor and Grok — the disposition is only ever + // supplied for a maintenance acknowledgement (#1717). + if (options) this.onBatchConsumed?.(consumedLocalIds, options); + else this.onBatchConsumed?.(consumedLocalIds); } /** Clear in-flight marks for a deferred batch that is dropped without ACK. */ diff --git a/cli/src/utils/process.test.ts b/cli/src/utils/process.test.ts index 43da3a65e42..61297909e62 100644 --- a/cli/src/utils/process.test.ts +++ b/cli/src/utils/process.test.ts @@ -10,7 +10,7 @@ vi.mock('cross-spawn', () => ({ } })) -import { getHapiRunnerProcessIdentity, killProcess, killProcessTreeByPid } from './process' +import { getHapiRunnerProcessIdentity, isProcessAlive, killProcess, killProcessTreeByPid, probeProcessLiveness } from './process' import { monotonicTimeMs } from './time' import { windowsSystemTool } from './windowsSystemTools' @@ -645,3 +645,48 @@ describe('getHapiRunnerProcessIdentity on POSIX', () => { expect(getHapiRunnerProcessIdentity(8328)).toBe('unknown') }) }) + +describe('probeProcessLiveness', () => { + afterEach(() => { + vi.restoreAllMocks() + spawnSyncMock.mockReset() + if (originalPlatformDescriptor) Object.defineProperty(process, 'platform', originalPlatformDescriptor) + }) + + function throwingKill() { + vi.spyOn(process, 'kill').mockImplementation(() => { + throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' }) + }) + } + + it('trusts tasklist on Windows', () => { + setPlatform('win32') + throwingKill() + spawnSyncMock.mockReturnValueOnce(completed('job.exe 4242 Console 1 10,000 K')) + expect(probeProcessLiveness(4242)).toBe('alive') + spawnSyncMock.mockReturnValueOnce(completed('INFO: No tasks are running which match the specified criteria.')) + expect(probeProcessLiveness(4242)).toBe('exited') + }) + + it('reports unknown on Windows when tasklist fails and signal-0 throws', () => { + setPlatform('win32') + throwingKill() + spawnSyncMock.mockReturnValue(unavailable(windowsSystemTool('tasklist'))) + expect(probeProcessLiveness(4242)).toBe('unknown') + expect(isProcessAlive(4242)).toBe(false) + }) + + it('falls back to signal-0 on Windows when tasklist fails', () => { + setPlatform('win32') + vi.spyOn(process, 'kill').mockReturnValue(true) + spawnSyncMock.mockReturnValue(unavailable(windowsSystemTool('tasklist'))) + expect(probeProcessLiveness(4242)).toBe('alive') + }) + + it('treats a failed signal-0 as exited on POSIX', () => { + setPlatform('linux') + throwingKill() + expect(probeProcessLiveness(4242)).toBe('exited') + expect(spawnSyncMock).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/utils/process.ts b/cli/src/utils/process.ts index 759cdd4b2aa..1476bba7548 100644 --- a/cli/src/utils/process.ts +++ b/cli/src/utils/process.ts @@ -10,9 +10,16 @@ export const isWindows = (): boolean => process.platform === 'win32'; /** Bound hung WMI/tasklist/ps so a wedged spawn cannot darken the runner (#1911 Overseer B3). */ const SPAWN_SYNC_TIMEOUT_MS = 10_000; -export function isProcessAlive(pid: number): boolean { +export type ProcessLiveness = 'alive' | 'exited' | 'unknown'; + +/** + * 'unknown' only on Windows, when tasklist failed (e.g. timed out) and the + * signal-0 fallback threw: that fallback is unreliable on win32, so its + * failure is not proof that the process exited. + */ +export function probeProcessLiveness(pid: number): ProcessLiveness { if (!Number.isFinite(pid) || pid <= 0) { - return false; + return 'exited'; } // Windows: prefer tasklist. Bun/Node `process.kill(pid, 0)` is unreliable as a @@ -26,8 +33,8 @@ export function isProcessAlive(pid: number): boolean { ); if (!result.error && result.status === 0) { const out = (result.stdout?.toString() ?? '').trim(); - if (!out || /no tasks/i.test(out)) return false; - return new RegExp(`(^|\\D)${pid}(\\D|$)`).test(out); + if (!out || /no tasks/i.test(out)) return 'exited'; + return new RegExp(`(^|\\D)${pid}(\\D|$)`).test(out) ? 'alive' : 'exited'; } } catch { // fall through to signal-0 probe @@ -36,12 +43,16 @@ export function isProcessAlive(pid: number): boolean { try { process.kill(pid, 0); - return true; + return 'alive'; } catch { - return false; + return isWindows() ? 'unknown' : 'exited'; } } +export function isProcessAlive(pid: number): boolean { + return probeProcessLiveness(pid) === 'alive'; +} + /** * Shared Win32 generation marker: CIM CreationDate as UTC round-trip ISO. * Must match orphan list + recheck — ConvertTo-Json of a raw DateTime emits diff --git a/docs/api/client-contract/auth.md b/docs/api/client-contract/auth.md index 06181486c2a..eea4b0d573c 100644 --- a/docs/api/client-contract/auth.md +++ b/docs/api/client-contract/auth.md @@ -26,10 +26,10 @@ The hub terminal (when started with `--relay`) prints two QR codes; the web app' | QR | Format | Params | |----|--------|--------| -| Web direct-access | `https://app.hapi.run/?hub=&token=` | `hub`, `token` | +| Web direct-access | `https://app.hapi.run/#hub=&token=` | `hub`, `token` (in `#fragment`; legacy `?query` still accepted) | | Companion deeplink | `hapicompanion://bind?hub=&code=` | `hub`, `code` | -Native clients register the `hapicompanion://` scheme and parse `bind` links: `hub` is the hub base URL, `code` is the access token. Note the param-name mismatch: the web QR carries the same value under `token=`, the companion deeplink under `code=`. A robust scanner may accept both forms; the deeplink form is the canonical one for natives. Always provide a manual fallback (type hub URL + access token) for `--relay`-less local hubs. +The web direct-access link places `hub` and `token` in the URL `#fragment` so credentials never appear in HTTP request paths, proxy logs or `Referer` headers; web and native parsers prefer fragment parameters and fall back to legacy `?hub=…&token=…` query parameters. Native clients register the `hapicompanion://` scheme and parse `bind` links: `hub` is the hub base URL, `code` is the access token. Note the param-name mismatch: the web QR carries the same value under `token=`, the companion deeplink under `code=`. A robust scanner may accept both forms; the deeplink form is the canonical one for natives. Always provide a manual fallback (type hub URL + access token) for `--relay`-less local hubs. Both repository apps accept both QR forms in their in-app scanners. Android requires HTTPS for the hub and web-QR URL, and disables cleartext traffic in diff --git a/docs/api/client-contract/rest.md b/docs/api/client-contract/rest.md index ae93a6aaa50..e6e4a48fd61 100644 --- a/docs/api/client-contract/rest.md +++ b/docs/api/client-contract/rest.md @@ -151,8 +151,8 @@ Source: `hub/src/web/routes/sessions.ts`; flavor gates in `shared/src/modes.ts` | Method & path | Request | Applies to | |---|---|---| | `POST /api/sessions/:id/permission-mode` | `{mode: PermissionMode}` | All flavors except `pi` and `dsh` (per-flavor allowed sets in `modes.ts`) | -| `POST /api/sessions/:id/model` | `{model: string \| {provider, modelId} \| null, effort?: string \| null}` | Flavors with `supportsModelChange` (not `dsh`); remote-only for codex/cursor/grok. Only claude and agy accept `effort` with a model change. | -| `POST /api/sessions/:id/effort` | `{effort: string \| null}` | agy, claude, copilot, grok, kimi, pi (`supportsEffort`) | +| `POST /api/sessions/:id/model` | `{model: string \| {provider, modelId} \| null, effort?: string \| null}` | Flavors with `supportsModelChange` (not `dsh`); remote-only for claude, codex, copilot, cursor, grok, kimi and opencode. Only claude and agy accept `effort` with a model change. | +| `POST /api/sessions/:id/effort` | `{effort: string \| null}` | agy, claude, copilot, grok, kimi, pi (`supportsEffort`); remote-only for claude, copilot, grok and kimi | | `POST /api/sessions/:id/model-reasoning-effort` | `{modelReasoningEffort: string \| null}` | codex, opencode (remote-only) | | `POST /api/sessions/:id/service-tier` | `{serviceTier: 'fast' \| 'standard'}` | codex (remote-only) | | `POST /api/sessions/:id/collaboration-mode` | `{mode: 'default' \| 'plan'}` | codex (remote-only) | diff --git a/docs/api/native-companion-contract.md b/docs/api/native-companion-contract.md index 8568daca148..7cd135890ed 100644 --- a/docs/api/native-companion-contract.md +++ b/docs/api/native-companion-contract.md @@ -33,7 +33,13 @@ support for `wear` registrations; the repository does not include a Wear OS app. "token": "", "platform": "phone", "deviceId": "", - "pushKey": "" + "pushKey": "", + "preferences": { + "ready": true, + "permissionRequest": true, + "inputRequest": true, + "modelError": true + } } ``` @@ -43,11 +49,17 @@ support for `wear` registrations; the repository does not include a Wear OS app. clients always provide it. Phone registrations without it remain valid for direct FCM; supplied phone keys must decode to exactly 32 bytes. Wear ignores this field. The hub canonicalizes and stores phone/iOS keys in the existing -registry; no schema or database version change is required. +registry. + +`preferences`: optional per-device event filter (`ready`, `permissionRequest`, +`inputRequest`, `modelError`). Omitted keys within `preferences` default to +`true`; omitting `preferences` altogether preserves any previously stored +filter on re-registration (defaulting to all enabled on first insert). Unknown +future event types remain enabled. `deviceId`: any string of 1-128 characters chosen by the client (does not have to be a UUID). Must be stable across re-registrations of the same install. -**Response:** `{ "ok": true }` +**Response:** `{ "ok": true, "hubId": "" }` (`hubId` is omitted on older hubs) Upsert on `(namespace, deviceId, platform)` - same device re-registering replaces its push token. @@ -88,6 +100,7 @@ receipt. | `contractVersion` | `1` | Present on every message; see [Versioning](#versioning) | | `notifySummary` | JSON string | Only on `ready`: parsed `AGENT_NOTIFY_SUMMARY` line from agent text, when present | | `tag` | `model-error--` | Coalescing identity. Required for `model-error` so distinct errors do not overwrite. Clients must prefer `tag` over reconstructing `type-`. | +| `hubId` | uuid | Stable UUID identifying the originating hub (also advertised by `GET /health` and `POST /api/devices/register`). Enables O(1) multi-hub routing; absent on older hubs. | Direct FCM is data-only. Android relay messages contain the encrypted wrapper below; after decryption the same data contract drives rendering and actions. diff --git a/docs/guide/native-apps.md b/docs/guide/native-apps.md index 564887a5cde..77f90703cba 100644 --- a/docs/guide/native-apps.md +++ b/docs/guide/native-apps.md @@ -103,6 +103,7 @@ directory browsing and session creation. | Android incoming shares | Share files, photos, text or links to HAPI, choose a session and confirm sending from its composer. The picker can switch paired hubs and explicitly restore stopped sessions. | | Session controls | Both support pin, rename, stopping a turn and sending to resume an inactive session. Active sessions can be archived; inactive sessions can be reopened explicitly or deleted. | | Files and Git | Open **Session files** from the chat menu to browse/search files, inspect Git status and read diffs. | +| Remote terminal | On iOS, open **Terminal** from an active session's … menu (`⌘⇧T` on iPad/Mac) for a native interactive shell in the session workspace and live Agent PTY view/control on active PTY sessions, with scrollback, quick keys and **Send to Chat** excerpts. | | Scratchlist | On iOS, tap the tray beside the composer attachment button to enter **Save draft** mode; Android uses the chat menu. Text and attachments sync within the session. | | Dictation | Record audio, transcribe through a configured hub provider, then edit the inserted text before sending. | | Usage and storage | Available only to the hub owner (`default` namespace). | @@ -132,8 +133,7 @@ Web sidebar adds directory grouping, client-side search ranking and a sort and filter menu. Both native apps mirror that menu: sort by last message or date created, **Active first** (on by default; manual pins still come first), show all, active or archived sessions, and an unread-only lens, alongside machine -filtering and relevance-ranked text search. Android adds a date range; iOS adds -**Mark All as Read**. Rows in all three clients use the same presence badges +filtering and relevance-ranked text search. Android adds a date range; iOS adds **Mark All as Read**, session groups under their leader with **Dissolve group**, and clickable `/sessions/` links in chat. Rows in all three clients use the same presence badges and show a running [attached job](./session-jobs.md). Android and iOS README files describe their platform-specific filter presentation and session-row differences. @@ -163,12 +163,14 @@ send it automatically. See [Voice input and assistant](./voice-assistant.md). ### Features available through the web -Use the web app for the remote terminal, Work Graph, realtime dictation and -voice assistant, Markdown export, and the skills picker. These have no native -UI. On iOS, the chat's … menu forks the current conversation, rewinds or forks -at a user message with a native history point, and exports the session as -JSON; Android has no fork, rewind or export UI. Session history actions also -depend on the agent's capabilities. +Use the web app for Work Graph, realtime dictation and voice assistant, and +Markdown export. These have no native UI. On iOS, active sessions also include a +native remote terminal (interactive shell + live Agent PTY) and a composer +skills picker; the chat's … menu forks the current conversation, rewinds or +forks at a user message with a native history point, and exports the session as +JSON. Android does not yet include the remote terminal, skills picker, fork, +rewind or JSON export UI. Session history actions also depend on the agent's +capabilities. Both apps display existing scheduled messages and can schedule new ones: the composer's clock schedules a text-only send up to 7 days ahead (relative presets or a specific time). diff --git a/docs/guide/peer-sessions.md b/docs/guide/peer-sessions.md index 102841e8700..e575a7ad1e5 100644 --- a/docs/guide/peer-sessions.md +++ b/docs/guide/peer-sessions.md @@ -91,7 +91,7 @@ When a session spawns a peer (MCP `spawn_peer`, or `hapi spawn-peer` with `HAPI_ A session and the sessions it spawns form a group: the spawning session is the leader and the spawned sessions are its members. Groups have two levels only. When a member spawns a session, the new session joins the same group as another member of the same leader; its `## Parent` block still names the session that spawned it. -The web session list shows members under their leader. See [Session list → Session groups](./session-list.md#session-groups). +The web and iOS session lists show members under their leader. See [Session list → Session groups](./session-list.md#session-groups). Resuming a session can give it a new session id. The group follows: a resumed member stays in its group, and the members of a resumed leader stay with it. diff --git a/docs/guide/session-list.md b/docs/guide/session-list.md index 7dab43c87c1..0a3b648c71c 100644 --- a/docs/guide/session-list.md +++ b/docs/guide/session-list.md @@ -67,8 +67,8 @@ rather than as waiting for input. A session that spawns other sessions with [`spawn_peer`](./peer-sessions.md#session-groups) leads a group, and the Web list keeps the group together: -- Members are not listed as rows of their own. A line under the leader's row shows the member count; select it to open or fold the member list. Lists start folded, and the ones you open are remembered in this browser for the current hub and namespace. -- The line also counts the members that are waiting on you (an approval or a question), working, and unread, so a folded group still shows what needs attention. +- Members are not listed as rows of their own. The leader's row has a second line with the member count; select it to open or fold the member list. Lists start folded, and the ones you open are remembered in this browser for the current hub and namespace. +- That line also counts the members that are waiting on you (an approval or a question), working, and unread, so a folded group still shows what needs attention. - A member in another directory or on another machine still appears under its leader, with its own project and machine on the row. - The group is placed by its leader: the leader's project folder, pin, and position in the order. Member activity does not move it. - With **Pin in-progress sessions**, a group moves to **In progress** when its leader or any member qualifies. Members do not move there on their own. @@ -78,7 +78,7 @@ A session that spawns other sessions with [`spawn_peer`](./peer-sessions.md#sess ### Dissolving a group -When a group's work is done, hover the member line under the leader (the action is always shown on touch screens, and the line stays even when every member is pinned or filtered out) and choose **Dissolve group**. This archives every running member and then the leader. If a member cannot be archived, the leader is left running so it can still collect that member's reply; dissolve again once the member has stopped. The same applies when the leader spawned another member, or a member was reopened, while the group was being dissolved. A session whose archive was not confirmed keeps **Dissolve group** available, even after it shows as archived and after a reload, until a retry succeeds. Nothing is deleted: the archived sessions stay grouped and searchable, and they appear under **Sort and filter → Show → Archived**. +When a group's work is done, open the leader's action menu (right-click, or long-press on touch screens) and choose **Dissolve group**. The action stays available even when every member is pinned or filtered out. This archives every running member and then the leader. If a member cannot be archived, the leader is left running so it can still collect that member's reply; dissolve again once the member has stopped. The same applies when the leader spawned another member, or a member was reopened, while the group was being dissolved. A session whose archive was not confirmed keeps **Dissolve group** available, even after it shows as archived and after a reload, until a retry succeeds. Nothing is deleted: the archived sessions stay grouped and searchable, and they appear under **Sort and filter → Show → Archived**. The confirmation lists what dissolving interrupts: @@ -90,7 +90,7 @@ Known limitation: a member the leader spawned more than two minutes earlier whos Before dissolving, ask the leader for a closing summary. A leader's context is not carried into a later group, and its last message is what you will find when you search for this work again. -The iOS and Android apps list members as ordinary rows. +The iOS app also groups members under their leader with waiting/working/unread counts, search/filter expansion, and **Dissolve group** (from the leader's context menu). The Android app lists members as ordinary rows. ## Text search diff --git a/e2e/session-list-blocked.spec.ts b/e2e/session-list-blocked.spec.ts new file mode 100644 index 00000000000..807221ec4ce --- /dev/null +++ b/e2e/session-list-blocked.spec.ts @@ -0,0 +1,162 @@ +import { expect, test } from '@playwright/test' + +const FIXTURE = '/e2e-fixtures/session-list-blocked-fixture.html' + +test.describe('#1717 blocked session-list chrome', () => { + test.beforeEach(async ({ page }) => { + await page.goto(FIXTURE) + await page.waitForSelector('[data-testid="blocked-section"]') + }) + + test('surfaces every kind of blocked agent at the top of a 96-session list', async ({ page }) => { + const section = page.getByTestId('blocked-section') + await expect(section).toBeVisible() + // Every blocker class the operator named: self-reported footers + // (blocked / stalled / decision / review / failed / non-contract + // "pending"), and agents parked on a prompt (permission / question). + await expect(section.getByTestId('session-blocked-chip')).toHaveCount(11) + for (const label of ['Permission', 'Question', 'Decision', 'Review', 'Failed', 'Blocked', 'Stalled']) { + await expect(section.getByText(label, { exact: true }).first()).toBeVisible() + } + // `completed` is a non-contract synonym for done — must stay quiet. + await expect(section.getByText('Completed', { exact: true })).toHaveCount(0) + + const pill = page.getByTestId('blocked-jump-pill') + await expect(pill).toBeVisible() + await expect(pill).toContainText('11') + + await page.screenshot({ path: 'test-results/blocked-1-list-top.png' }) + }) + + test('demotes a blocked report older than the loud window', async ({ page }) => { + await expect(page.locator('[data-session-blocked]')).toHaveCount(11) + await expect(page.locator('[data-session-blocked="active"]')).toHaveCount(10) + await expect(page.locator('[data-session-blocked="stale"]')).toHaveCount(1) + }) + + test('the pill stays reachable and travels to a blocked row after scrolling away', async ({ page }) => { + const scroller = page.locator('.app-scroll-y').first() + await scroller.evaluate((el) => { el.scrollTop = el.scrollHeight }) + await expect(page.getByTestId('blocked-section')).not.toBeInViewport() + + const pill = page.getByTestId('blocked-jump-pill') + // The header does not scroll: the count is still on screen after the + // blocked rows have left it. This is the off-viewport guarantee. + await expect(pill).toBeInViewport() + await expect(pill).toContainText('↑') + await page.screenshot({ path: 'test-results/blocked-2-scrolled-away.png' }) + + await pill.click() + // `chooseBlockedJumpTarget`'s "up" branch picks `above[above.length - + // 1]` — nearest the (scrolled-to-bottom) viewport, which is the LAST + // blocked row in document order, not the first (#1717 cold-review + // round 29). Asserting `.first()` here checked an element the jump + // never targets and could pass or fail independent of whether the + // jump itself worked. + await expect(page.locator('[data-session-blocked="active"]').last()).toBeInViewport() + await page.screenshot({ path: 'test-results/blocked-3-after-jump.png' }) + }) + + test('still hints off-screen work when the section is collapsed', async ({ page }) => { + // The collapsible panel animates grid-template-rows to 0fr rather than + // unmounting, so collapsed rows stay in the DOM. Measuring presence + // alone would report "all visible" while nothing is on screen — but + // `collectOffscreenBlockers` positions a collapsed section's rows at + // its OWN header, so collapsing while that header is still on screen + // (as it is here, at the top of the list) genuinely means nothing is + // off-screen yet, and the pill correctly shows no direction. + const pill = page.getByTestId('blocked-jump-pill') + const section = page.getByTestId('blocked-section') + await expect(pill).not.toContainText('↑') + await expect(pill).not.toContainText('↓') + + await section.locator('[role="button"]').first().click() + await expect(pill).not.toContainText(/[↑↓↕]/) + + // Now scroll the collapsed header itself out of view — the position + // the hint is actually measured from. + const scroller = page.locator('.app-scroll-y').first() + await scroller.evaluate((el) => { el.scrollTop = el.scrollHeight }) + await expect(section).not.toBeInViewport() + await expect(pill).toContainText(/[↑↓↕]/) + + // Clicking the pill expands the section (a collapsed, zero-height + // panel cannot be jumped into) and scrolls the target row into view. + await pill.click() + await expect(section.locator('[role="button"]').first()).toHaveAttribute('aria-expanded', 'true') + // Same "up" target as the non-collapsed case: the LAST blocked row + // in document order (#1717 cold-review round 29). + await expect(page.locator('[data-session-blocked="active"]').last()).toBeInViewport() + }) + + test('the combined filter menu narrows the list to blocked work only (#1996)', async ({ page }) => { + await page.getByRole('button', { name: 'Sort and filter', exact: true }).click() + const checkbox = page.getByRole('menuitemcheckbox', { name: 'Blocked only', exact: true }) + await checkbox.click() + + await expect(checkbox).toHaveAttribute('aria-checked', 'true') + await expect(page.getByTestId('session-blocked-chip')).toHaveCount(11) + // Every remaining row carries the blocked flag. + const rows = page.locator('[data-session-id]') + const blockedRows = page.locator('[data-session-blocked]') + expect(await rows.count()).toBe(await blockedRows.count()) + // The lens must not leave bare project headers behind for the + // directories whose only remaining rows floated into the section. + await expect(page.locator('[data-testid="blocked-section"] ~ * >> text=coding/')).toHaveCount(0) + + await page.screenshot({ path: 'test-results/blocked-4-lens.png' }) + }) +}) + +test.describe('#1717 blocker alerting', () => { + test('pulses the counter when a new blocker arrives', async ({ page }) => { + await page.goto(FIXTURE) + await page.waitForSelector('[data-testid="blocked-section"]') + + const pill = page.getByTestId('blocked-jump-pill') + // Pre-existing backlog must be quiet on first paint. + await expect(pill).not.toHaveClass(/animate-blocked-alert/) + + await page.evaluate(() => (window as unknown as { __addBlocker?: () => void }).__addBlocker?.()) + + await expect(pill).toHaveClass(/animate-blocked-alert/) + await page.screenshot({ path: 'test-results/blocked-5-alert-pulse.png' }) + }) +}) + +test.describe('#1717 manual unblock', () => { + test('right-click a blocked row offers Mark unblocked and demands a reason', async ({ page }) => { + await page.goto(FIXTURE) + await page.waitForSelector('[data-testid="blocked-section"]') + + const row = page.locator('[data-session-blocked="active"]').first() + await row.click({ button: 'right' }) + + const item = page.getByTestId('session-action-mark-unblocked') + await expect(item).toBeVisible() + await item.click() + + const dialog = page.getByTestId('unblock-reason-dialog') + await expect(dialog).toBeVisible() + await page.screenshot({ path: 'test-results/blocked-6-unblock-dialog.png' }) + + // Empty reason is refused — the whole point of the prompt. + await page.getByTestId('unblock-confirm').click() + await expect(dialog.getByRole('alert')).toBeVisible() + await expect(dialog).toBeVisible() + + // A preset fills a real, comparable rationale in one tap. + await dialog.getByText('Handled outside HAPI', { exact: true }).click() + await page.screenshot({ path: 'test-results/blocked-7-unblock-reason.png' }) + }) + + test('an unblocked row is not offered the action', async ({ page }) => { + await page.goto(FIXTURE) + await page.waitForSelector('[data-testid="blocked-section"]') + + const clean = page.locator('[data-session-id]:not([data-session-blocked])').first() + await clean.click({ button: 'right' }) + + await expect(page.getByTestId('session-action-mark-unblocked')).toHaveCount(0) + }) +}) diff --git a/hub/src/config/hubId.test.ts b/hub/src/config/hubId.test.ts new file mode 100644 index 00000000000..d5762760771 --- /dev/null +++ b/hub/src/config/hubId.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'bun:test' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { getOrCreateHubId } from './hubId' + +describe('getOrCreateHubId', () => { + it('generates and persists a stable UUID per data directory', async () => { + const dirA = mkdtempSync(join(tmpdir(), 'hapi-hub-id-a-')) + const dirB = mkdtempSync(join(tmpdir(), 'hapi-hub-id-b-')) + try { + const first = await getOrCreateHubId(dirA) + expect(first).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i) + + // Reload from same directory (cached) and via another directory (forces re-read of dirA). + expect(await getOrCreateHubId(dirA)).toBe(first) + const second = await getOrCreateHubId(dirB) + expect(second).not.toBe(first) + expect(await getOrCreateHubId(dirA)).toBe(first) + + const persisted = JSON.parse(readFileSync(join(dirA, 'hub-id.json'), 'utf8')) as { hubId: string } + expect(persisted.hubId).toBe(first) + } finally { + rmSync(dirA, { recursive: true, force: true }) + rmSync(dirB, { recursive: true, force: true }) + } + }) + + it('reads an existing pre-seeded hub-id.json', async () => { + const dir = mkdtempSync(join(tmpdir(), 'hapi-hub-id-seed-')) + try { + writeFileSync(join(dir, 'hub-id.json'), JSON.stringify({ hubId: 'hub-uuid-custom' }), 'utf8') + expect(await getOrCreateHubId(dir)).toBe('hub-uuid-custom') + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/hub/src/config/hubId.ts b/hub/src/config/hubId.ts new file mode 100644 index 00000000000..fd5c3b4ba95 --- /dev/null +++ b/hub/src/config/hubId.ts @@ -0,0 +1,37 @@ +import { randomUUID } from 'node:crypto' +import { join } from 'node:path' +import { z } from 'zod' +import { getConfiguration } from '../configuration' +import { getOrCreateJsonFile } from './generators' + +const hubIdFileSchema = z.object({ + hubId: z.string().trim().min(1) +}) + +let cachedHubId: string | null = null +let cachedDataDir: string | null = null + +export async function getOrCreateHubId(dataDir?: string): Promise { + const resolvedDir = dataDir ?? getConfiguration().dataDir + if (cachedHubId !== null && cachedDataDir === resolvedDir) { + return cachedHubId + } + + const hubIdFile = join(resolvedDir, 'hub-id.json') + + const result = await getOrCreateJsonFile({ + filePath: hubIdFile, + readValue: (raw) => { + const parsed = hubIdFileSchema.parse(JSON.parse(raw)) + return parsed.hubId + }, + writeValue: (hubId) => JSON.stringify({ hubId }, null, 4), + generate: () => randomUUID(), + fileMode: 0o600, + dirMode: 0o700 + }) + + cachedHubId = result.value + cachedDataDir = resolvedDir + return result.value +} diff --git a/hub/src/config/settings.ts b/hub/src/config/settings.ts index 5bfcbb25b1f..c7286e44c1b 100644 --- a/hub/src/config/settings.ts +++ b/hub/src/config/settings.ts @@ -278,6 +278,15 @@ export async function withSettingsLock( settingsFile: string, work: () => Promise ): Promise { + // The cross-process lock is itself a `mkdir` next to the settings file, so + // the parent has to exist before we try to take it. `writeSettingsUnlocked` + // creates the directory, but it runs INSIDE the lock — on a fresh data dir + // the lock's own mkdir therefore failed with ENOENT and retried until the + // attempt budget ran out (50 x 100ms, the ~5s failure seen in CI). + const dir = dirname(settingsFile) + if (!existsSync(dir)) { + await mkdir(dir, { recursive: true, mode: 0o700 }) + } return withInProcessSettingsLock(settingsFile, () => withSettingsFileLock(settingsFile, work)) } diff --git a/hub/src/config/settingsLockDir.test.ts b/hub/src/config/settingsLockDir.test.ts new file mode 100644 index 00000000000..f7f0a309e58 --- /dev/null +++ b/hub/src/config/settingsLockDir.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'bun:test' +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { getSettingsFile, withSettingsLock } from './settings' + +describe('withSettingsLock on a fresh data dir', () => { + it('creates the parent before taking the lock', async () => { + // The cross-process lock is a `mkdir` next to the settings file, but + // the directory was only created inside `writeSettingsUnlocked` — i.e. + // inside the lock. On a data dir that did not exist yet the lock's own + // mkdir failed with ENOENT and retried the full attempt budget + // (50 x 100ms), surfacing as an unnamed ~5s test failure. + const base = mkdtempSync(join(tmpdir(), 'hapi-settings-lock-')) + const settingsFile = getSettingsFile(join(base, 'never-created')) + + const started = Date.now() + await expect(withSettingsLock(settingsFile, async () => 'held')).resolves.toBe('held') + // Also guards the symptom: a retry storm would blow past this. + expect(Date.now() - started).toBeLessThan(2_000) + }) +}) diff --git a/hub/src/fcm/androidRelayService.test.ts b/hub/src/fcm/androidRelayService.test.ts index 389fa097d33..14cd29a9c78 100644 --- a/hub/src/fcm/androidRelayService.test.ts +++ b/hub/src/fcm/androidRelayService.test.ts @@ -61,4 +61,47 @@ describe('Android relay fan-out', () => { expect(encryptEnvelope(Buffer.alloc(32), minimal).length).toBeLessThanOrEqual(MAX_ANDROID_RELAY_ENVELOPE_BYTES) expect(androidRelayPlaintext({ ...largeSummary, sessionId: 's'.repeat(4000) })).toBeNull() }) + + it('preserves hubId in minimal fallback and respects per-device preferences', async () => { + const store = new Store(':memory:') + const keyKeep = Buffer.alloc(32, 3) + const keyMuted = Buffer.alloc(32, 4) + store.fcm.upsertDevice('ns', { + token: 'tok-keep', + deviceId: 'dev-keep', + platform: 'phone', + pushKey: keyKeep.toString('base64'), + preferences: { ready: true, permissionRequest: true, inputRequest: true, modelError: true } + }) + store.fcm.upsertDevice('ns', { + token: 'tok-muted', + deviceId: 'dev-muted', + platform: 'phone', + pushKey: keyMuted.toString('base64'), + preferences: { permissionRequest: false } + }) + + const requests: EncryptedPushRequest[] = [] + const service = new AndroidRelayService({ async send(request) { requests.push(request); return 'sent' } }, store) + const withHubId: FcmSendPayload = { + ...payload, + data: { ...payload.data, hubId: 'hub-android-1' } + } + expect(await service.sendToNamespace('ns', withHubId)).toEqual({ sent: 1, failed: 0, invalidTokens: [] }) + expect(requests.map((r) => r.token)).toEqual(['tok-keep']) + expect(JSON.parse(decryptEnvelope(keyKeep, requests[0].envelope))).toMatchObject({ hubId: 'hub-android-1' }) + + const minimalWithHub = androidRelayPlaintext({ + ...withHubId.data, + body: '😀'.repeat(4000), + title: '大'.repeat(4000) + })! + expect(JSON.parse(minimalWithHub)).toMatchObject({ + type: 'permission-request', + sessionId: 's1', + requestId: 'r1', + hubId: 'hub-android-1' + }) + store.close() + }) }) diff --git a/hub/src/fcm/androidRelayService.ts b/hub/src/fcm/androidRelayService.ts index 7d688864c67..368d081d4d1 100644 --- a/hub/src/fcm/androidRelayService.ts +++ b/hub/src/fcm/androidRelayService.ts @@ -1,4 +1,5 @@ import type { Store } from '../store' +import { isNativePushEventEnabled } from '../store/fcmDevices' import { canonicalJson, encryptEnvelope, PUSH_KEY_LENGTH, PUSH_NONCE_LENGTH, PUSH_TAG_LENGTH } from '../push-native/envelope' import type { EncryptedPushTransport } from '../push-native/transport' import type { AndroidPushSender, FcmSendPayload, FcmSendResult } from './fcmService' @@ -23,6 +24,7 @@ export function androidRelayPlaintext(data: FcmSendPayload['data']): string | nu sessionId: data.sessionId, requestId: data.requestId, contractVersion: data.contractVersion, + ...(data.hubId ? { hubId: data.hubId } : {}), title: 'HAPI', body: 'New activity' }) @@ -33,7 +35,9 @@ export class AndroidRelayService implements AndroidPushSender { constructor(private readonly transport: EncryptedPushTransport, private readonly store: Store) {} async sendToNamespace(namespace: string, payload: FcmSendPayload): Promise { - const devices = this.store.fcm.getDevicesByNamespace(namespace, ['phone']) + const devices = this.store.fcm + .getDevicesByNamespace(namespace, ['phone']) + .filter((device) => isNativePushEventEnabled(device.preferences, payload.data.type)) const result: FcmSendResult = { sent: 0, failed: 0, invalidTokens: [] } if (!devices.length) return result const plaintext = androidRelayPlaintext(payload.data) diff --git a/hub/src/fcm/fcmNotificationChannel.ts b/hub/src/fcm/fcmNotificationChannel.ts index 7c0588c0e79..ebdd74a9c6a 100644 --- a/hub/src/fcm/fcmNotificationChannel.ts +++ b/hub/src/fcm/fcmNotificationChannel.ts @@ -16,7 +16,8 @@ export class FcmNotificationChannel implements NotificationChannel { private readonly fcmService: AndroidPushSender, private readonly sseManager: SSEManager, private readonly visibilityTracker: VisibilityTracker, - private readonly store?: Store + private readonly store?: Store, + private readonly hubId?: string ) { this.composer = new NativeNotificationComposer(store) } @@ -65,7 +66,8 @@ export class FcmNotificationChannel implements NotificationChannel { body, contractVersion: NATIVE_CONTRACT_VERSION, severity: 'error', - tag + tag, + ...(this.hubId ? { hubId: this.hubId } : {}) } }, ctx) if ((result?.sent ?? 0) > 0) { @@ -93,7 +95,8 @@ export class FcmNotificationChannel implements NotificationChannel { body: composed.body, contractVersion: NATIVE_CONTRACT_VERSION, severity: composed.severity, - ...(composed.notifySummary ? { notifySummary: composed.notifySummary } : {}) + ...(composed.notifySummary ? { notifySummary: composed.notifySummary } : {}), + ...(this.hubId ? { hubId: this.hubId } : {}) } } } diff --git a/hub/src/fcm/fcmService.test.ts b/hub/src/fcm/fcmService.test.ts index c5feda3da65..c9956c78cea 100644 --- a/hub/src/fcm/fcmService.test.ts +++ b/hub/src/fcm/fcmService.test.ts @@ -21,7 +21,13 @@ function makeService(store: FakeStore): FcmService { ) } -function makeStore(devices: Array<{ token: string; platform: 'phone' | 'wear'; deviceId: string; namespace: string }>): FakeStore { +function makeStore(devices: Array<{ + token: string + platform: 'phone' | 'wear' + deviceId: string + namespace: string + preferences?: { ready: boolean; permissionRequest: boolean; inputRequest: boolean; modelError: boolean } | null +}>): FakeStore { return { fcm: { getDevicesByNamespace: mock((ns: string) => @@ -33,6 +39,7 @@ function makeStore(devices: Array<{ token: string; platform: 'phone' | 'wear'; d token: d.token, platform: d.platform, deviceId: d.deviceId, + preferences: d.preferences ?? null, createdAt: 0, updatedAt: 0 })) @@ -466,4 +473,30 @@ describe('FcmService.isHealthy (rolling outcome window)', () => { for (let i = 0; i < 5; i += 1) await svc.sendToNamespace('default', makePayload()) expect(svc.isHealthy()).toBe(false) }) + + it('filters devices by per-device preferences and forwards hubId in message.data', async () => { + const store = makeStore([ + { namespace: 'default', token: 'tok-enabled', platform: 'phone', deviceId: 'p1', preferences: null }, + { + namespace: 'default', + token: 'tok-muted', + platform: 'phone', + deviceId: 'p2', + preferences: { ready: false, permissionRequest: true, inputRequest: true, modelError: true } + } + ]) + const sentBodies: Array<{ message?: { token?: string; data?: Record } }> = [] + globalThis.fetch = mock(async (_url: string, init?: RequestInit) => { + sentBodies.push(JSON.parse(String(init?.body ?? '{}'))) + return new Response('{}', { status: 200 }) + }) as unknown as typeof fetch + + const svc = makeService(store) + const result = await svc.sendToNamespace('default', makePayload({ type: 'ready', hubId: 'hub-fcm-7' })) + + expect(result).toEqual({ sent: 1, failed: 0, invalidTokens: [] }) + expect(sentBodies).toHaveLength(1) + expect(sentBodies[0].message?.token).toBe('tok-enabled') + expect(sentBodies[0].message?.data?.hubId).toBe('hub-fcm-7') + }) }) diff --git a/hub/src/fcm/fcmService.ts b/hub/src/fcm/fcmService.ts index 71371c5afbe..b5e5cd5c936 100644 --- a/hub/src/fcm/fcmService.ts +++ b/hub/src/fcm/fcmService.ts @@ -1,4 +1,5 @@ import type { Store } from '../store' +import { isNativePushEventEnabled } from '../store/fcmDevices' import { getFcmAccessToken, FCM_REQUEST_TIMEOUT_MS, type ServiceAccount } from './fcmAuth' export type FcmDataPayload = { @@ -32,6 +33,8 @@ export type FcmDataPayload = { * `model-error--` so distinct errors do not overwrite. */ tag?: string + /** Stable UUID identifying the originating hub for O(1) multi-hub routing. */ + hubId?: string } export type FcmSendPayload = { @@ -118,7 +121,9 @@ export class FcmService { async sendToNamespace(namespace: string, payload: FcmSendPayload): Promise { // The registry also holds iOS rows (APNs tokens + E2E push keys); // those go through IosPushService, never through FCM. - const devices = this.store.fcm.getDevicesByNamespace(namespace, ['phone', 'wear']) + const devices = this.store.fcm + .getDevicesByNamespace(namespace, ['phone', 'wear']) + .filter((device) => isNativePushEventEnabled(device.preferences, payload.data.type)) if (devices.length === 0) { return { sent: 0, failed: 0, invalidTokens: [] } } @@ -192,6 +197,9 @@ export class FcmService { } else if (payload.data.tag) { dataRecord.tag = payload.data.tag } + if (payload.data.hubId) { + dataRecord.hubId = payload.data.hubId + } // Data-only: if we also send `notification`, Android does not call // onMessageReceived while backgrounded — Wear relay never runs. diff --git a/hub/src/push-ios/iosPushChannel.test.ts b/hub/src/push-ios/iosPushChannel.test.ts index 476b6d155f0..edbbe16bc6c 100644 --- a/hub/src/push-ios/iosPushChannel.test.ts +++ b/hub/src/push-ios/iosPushChannel.test.ts @@ -20,14 +20,14 @@ type FakeService = { calls: Array<{ namespace: string; payload: IosPushNotificationPayload }> } -function makeChannel(result: IosPushSendResult): { channel: IosPushNotificationChannel; service: FakeService } { +function makeChannel(result: IosPushSendResult, hubId?: string): { channel: IosPushNotificationChannel; service: FakeService } { const service: FakeService = { calls: [] } const channel = new IosPushNotificationChannel({ sendToNamespace: async (namespace: string, payload: IosPushNotificationPayload) => { service.calls.push({ namespace, payload }) return result } - } as never) + } as never, undefined, hubId) return { channel, service } } @@ -126,4 +126,24 @@ describe('IosPushNotificationChannel', () => { expect(payload.tag).toBe('model-error-session-1-evt-1') expect(payload.contractVersion).toBe('1') }) + + it('stamps hubId onto ready, permission-request, and model-error payloads when configured', async () => { + const { channel, service } = makeChannel({ sent: 1, failed: 0, invalidTokens: [] }, 'hub-uuid-99') + + await channel.sendReady(createSession()) + await channel.sendPermissionRequest(createSession({ + agentState: { requests: { 'req-1': { tool: 'Bash', arguments: {} } } } + } as Partial)) + await channel.sendModelError(createSession(), { + eventId: 'evt-2', + kind: 'rate_limited', + transient: true, + rawSnippet: '429', + priorAssistantClaimsDone: false, + atTs: 1710000000000 + }) + + expect(service.calls).toHaveLength(3) + expect(service.calls.every((call) => call.payload.hubId === 'hub-uuid-99')).toBe(true) + }) }) diff --git a/hub/src/push-ios/iosPushChannel.ts b/hub/src/push-ios/iosPushChannel.ts index 359cf9c58fc..e058ce2b6b5 100644 --- a/hub/src/push-ios/iosPushChannel.ts +++ b/hub/src/push-ios/iosPushChannel.ts @@ -20,7 +20,8 @@ export class IosPushNotificationChannel implements NotificationChannel { constructor( private readonly iosPushService: IosPushService, - store?: Store + store?: Store, + private readonly hubId?: string ) { this.composer = new NativeNotificationComposer(store) } @@ -61,7 +62,8 @@ export class IosPushNotificationChannel implements NotificationChannel { body, contractVersion: NATIVE_CONTRACT_VERSION, severity: 'error', - tag + tag, + ...(this.hubId ? { hubId: this.hubId } : {}) }) if ((result?.sent ?? 0) > 0) { if (ctx?.nativeGate) { @@ -86,7 +88,8 @@ export class IosPushNotificationChannel implements NotificationChannel { contractVersion: NATIVE_CONTRACT_VERSION, ...(composed.severity ? { severity: composed.severity } : {}), ...(composed.requestId ? { requestId: composed.requestId } : {}), - ...(composed.notifySummary ? { notifySummary: composed.notifySummary } : {}) + ...(composed.notifySummary ? { notifySummary: composed.notifySummary } : {}), + ...(this.hubId ? { hubId: this.hubId } : {}) } } diff --git a/hub/src/push-ios/iosPushService.test.ts b/hub/src/push-ios/iosPushService.test.ts index 9cadb7c52ac..08dfa083ff6 100644 --- a/hub/src/push-ios/iosPushService.test.ts +++ b/hub/src/push-ios/iosPushService.test.ts @@ -264,4 +264,47 @@ describe('IosPushService.isHealthy (rolling outcome window)', () => { await service.sendToNamespace('default', makePayload()) expect(service.isHealthy()).toBe(true) }) + + it('filters devices per event preference and includes hubId in encrypted payload', async () => { + const store = new Store(':memory:') + const keyAll = randomBytes(32) + const keyCriticalOnly = randomBytes(32) + store.fcm.upsertDevice('default', { + token: 'tok-all', + platform: 'ios', + deviceId: 'iphone-all', + pushKey: keyAll.toString('base64') + }) + store.fcm.upsertDevice('default', { + token: 'tok-critical', + platform: 'ios', + deviceId: 'iphone-critical', + pushKey: keyCriticalOnly.toString('base64'), + preferences: { ready: false, permissionRequest: true, inputRequest: false, modelError: true } + }) + const transport = makeTransport(() => 'sent') + const service = new IosPushService(transport, store) + + const readyResult = await service.sendToNamespace('default', makePayload({ type: 'ready', hubId: 'hub-42' })) + expect(readyResult).toEqual({ sent: 1, failed: 0, invalidTokens: [] }) + expect(transport.requests.map((r) => r.token)).toEqual(['tok-all']) + expect(JSON.parse(decryptEnvelope(keyAll, transport.requests[0].envelope))).toMatchObject({ + type: 'ready', + hubId: 'hub-42' + }) + + transport.requests.length = 0 + const permResult = await service.sendToNamespace('default', makePayload({ + type: 'permission-request', + requestId: 'req-1', + hubId: 'hub-42' + })) + expect(permResult).toEqual({ sent: 2, failed: 0, invalidTokens: [] }) + expect(transport.requests.map((r) => r.token).sort()).toEqual(['tok-all', 'tok-critical']) + + transport.requests.length = 0 + const inputResult = await service.sendToNamespace('default', makePayload({ type: 'input-request', hubId: 'hub-42' })) + expect(inputResult).toEqual({ sent: 1, failed: 0, invalidTokens: [] }) + expect(transport.requests.map((r) => r.token)).toEqual(['tok-all']) + }) }) diff --git a/hub/src/push-ios/iosPushService.ts b/hub/src/push-ios/iosPushService.ts index 13d0a826490..a358e1a4dcf 100644 --- a/hub/src/push-ios/iosPushService.ts +++ b/hub/src/push-ios/iosPushService.ts @@ -1,4 +1,5 @@ import type { Store } from '../store' +import { isNativePushEventEnabled } from '../store/fcmDevices' import { PUSH_KEY_LENGTH, canonicalJson, encryptEnvelope } from '../push-native/envelope' import type { NativePushSendOutcome, EncryptedPushTransport } from '../push-native/transport' @@ -21,6 +22,8 @@ export type IosPushNotificationPayload = { notifySummary?: string /** Coalescing identity; when set, used as APNs collapse-id. */ tag?: string + /** Stable UUID identifying the originating hub for O(1) multi-hub routing. */ + hubId?: string } export type IosPushSendResult = { @@ -87,7 +90,9 @@ export class IosPushService { } async sendToNamespace(namespace: string, payload: IosPushNotificationPayload): Promise { - const devices = this.store.fcm.getDevicesByNamespace(namespace, ['ios']) + const devices = this.store.fcm + .getDevicesByNamespace(namespace, ['ios']) + .filter((device) => isNativePushEventEnabled(device.preferences, payload.type)) if (devices.length === 0) { return { sent: 0, failed: 0, invalidTokens: [] } } diff --git a/hub/src/socket/handlers/cli/index.test.ts b/hub/src/socket/handlers/cli/index.test.ts index 866ffccfaeb..a9b11261ee6 100644 --- a/hub/src/socket/handlers/cli/index.test.ts +++ b/hub/src/socket/handlers/cli/index.test.ts @@ -343,3 +343,24 @@ describe('cli handler session-access memo', () => { store.close() }) }) + +describe('the app-level ping', () => { + it('is answered when an acknowledgement was sent, and left alone without one, instead of throwing', () => { + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store: new Store(':memory:'), + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry + }) + + // The ping carries no data: socket.io hands the handler its acknowledgement alone, when there is one. + let answered = 0 + socket.handlers.get('ping')?.(() => { answered += 1 }) + expect(answered).toBe(1) + + // The call to the missing acknowledgement used to throw inside the socket handler. + expect(() => socket.handlers.get('ping')?.(undefined)).not.toThrow() + }) +}) diff --git a/hub/src/socket/handlers/cli/index.ts b/hub/src/socket/handlers/cli/index.ts index 0dfe2411d39..a3563d667cd 100644 --- a/hub/src/socket/handlers/cli/index.ts +++ b/hub/src/socket/handlers/cli/index.ts @@ -54,6 +54,8 @@ export type CliHandlersDeps = { onAgentProgress?: (sessionId: string, at: number) => void onSweepImmediateQueued?: (sessionId: string, now: number) => void onMessagesConsumed?: (sessionId: string) => void + onPromptDelivered?: (sessionId: string, deliveredAt: number) => void + onMaintenanceTurn?: (sessionId: string) => void } // resolveSessionAccess runs on EVERY cli socket event (message stream deltas, @@ -85,7 +87,7 @@ const SESSION_ACCESS_CACHE_TTL_MS = 1_000 const SESSION_ACCESS_CACHE_MAX_SESSIONS = 64 export function registerCliHandlers(socket: CliSocketWithData, deps: CliHandlersDeps): void { - const { io, store, rpcRegistry, terminalRegistry, onSessionAlive, onSessionReady, onSessionEnd, onMachineAlive, onSessionChildExited, onWebappEvent, onBackgroundTasks, onSessionActivity, onAgentProgress, onSweepImmediateQueued, onMessagesConsumed } = deps + const { io, store, rpcRegistry, terminalRegistry, onSessionAlive, onSessionReady, onSessionEnd, onMachineAlive, onSessionChildExited, onWebappEvent, onBackgroundTasks, onSessionActivity, onAgentProgress, onSweepImmediateQueued, onMessagesConsumed, onPromptDelivered, onMaintenanceTurn } = deps const terminalNamespace = io.of('/terminal') const namespace = typeof socket.data.namespace === 'string' ? socket.data.namespace : null @@ -183,7 +185,9 @@ export function registerCliHandlers(socket: CliSocketWithData, deps: CliHandlers onSessionActivity, onAgentProgress, onSweepImmediateQueued, - onMessagesConsumed + onMessagesConsumed, + onPromptDelivered, + onMaintenanceTurn }) registerMachineHandlers(socket, { store, @@ -213,8 +217,9 @@ export function registerCliHandlers(socket: CliSocketWithData, deps: CliHandlers emitAccessError }) - socket.on('ping', (callback: () => void) => { - callback() + socket.on('ping', (callback?: () => void) => { + // A ping sent with nothing to answer it must not end the hub. + callback?.() }) socket.on('disconnect', () => { diff --git a/hub/src/socket/handlers/cli/machineHandlers.ack.test.ts b/hub/src/socket/handlers/cli/machineHandlers.ack.test.ts new file mode 100644 index 00000000000..c7f0b0d9660 --- /dev/null +++ b/hub/src/socket/handlers/cli/machineHandlers.ack.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'bun:test' +import { EventEmitter } from 'node:events' +import { Store, type StoredMachine } from '../../../store' +import type { CliSocketWithData } from '../../socketTypes' +import { registerMachineHandlers } from './machineHandlers' + +describe('machine updates sent without an acknowledgement', () => { + function registered() { + const store = new Store(':memory:') + const machine = store.machines.getOrCreateMachine('machine-1', { host: 'studio.local' }, null, 'default') + // A plain socket: the handler is handed no acknowledgement at all, which is what a client that leaves it out sends. + const socket = Object.assign(new EventEmitter(), { to: () => ({ emit: () => {} }) }) as unknown as EventEmitter + registerMachineHandlers(socket as unknown as CliSocketWithData, { + store, + resolveMachineAccess: () => ({ ok: true, value: { namespace: 'default' } as StoredMachine }), + emitAccessError: () => { + throw new Error('unexpected access error') + } + }) + return { store, machine, socket } + } + + // A client that leaves out the acknowledgement is wrong; each of these used to throw inside the + // socket handler, which ends the hub process. + it('are applied all the same: machine-update-state and machine-update-metadata', () => { + const { store, machine, socket } = registered() + + expect(() => socket.emit('machine-update-state', { + machineId: machine.id, + expectedVersion: machine.runnerStateVersion, + runnerState: { status: 'running' } + })).not.toThrow() + expect(() => socket.emit('machine-update-metadata', { + machineId: machine.id, + expectedVersion: machine.metadataVersion, + metadata: { host: 'elsewhere.local' } + })).not.toThrow() + + const after = store.machines.getMachine(machine.id) + expect(after?.runnerState).toMatchObject({ status: 'running' }) + expect(after?.metadata).toMatchObject({ host: 'elsewhere.local' }) + }) + + it('are refused without throwing when the payload is malformed', () => { + const { machine, socket } = registered() + + expect(() => socket.emit('machine-update-state', {})).not.toThrow() + expect(() => socket.emit('machine-update-metadata', { machineId: machine.id })).not.toThrow() + }) +}) diff --git a/hub/src/socket/handlers/cli/machineHandlers.ts b/hub/src/socket/handlers/cli/machineHandlers.ts index 1f07f52ac79..e47f8b61193 100644 --- a/hub/src/socket/handlers/cli/machineHandlers.ts +++ b/hub/src/socket/handlers/cli/machineHandlers.ts @@ -73,26 +73,28 @@ export function registerMachineHandlers(socket: CliSocketWithData, deps: Machine }) const handleMachineMetadataUpdate: MachineUpdateMetadataHandler = (data, cb) => { + // The acknowledgement is the client's to send; one that leaves it out must not take the hub down. + const reply = typeof cb === 'function' ? cb : () => {} const parsed = machineUpdateMetadataSchema.safeParse(data) if (!parsed.success) { - cb({ result: 'error' }) + reply({ result: 'error' }) return } const { machineId: id, metadata, expectedVersion } = parsed.data const machineAccess = resolveMachineAccess(id) if (!machineAccess.ok) { - cb({ result: 'error', reason: machineAccess.reason }) + reply({ result: 'error', reason: machineAccess.reason }) return } const result = store.machines.updateMachineMetadata(id, metadata, expectedVersion, machineAccess.value.namespace) if (result.result === 'success') { - cb({ result: 'success', version: result.version, metadata: result.value }) + reply({ result: 'success', version: result.version, metadata: result.value }) } else if (result.result === 'version-mismatch') { - cb({ result: 'version-mismatch', version: result.version, metadata: result.value }) + reply({ result: 'version-mismatch', version: result.version, metadata: result.value }) } else { - cb({ result: 'error' }) + reply({ result: 'error' }) } if (result.result === 'success') { @@ -113,16 +115,18 @@ export function registerMachineHandlers(socket: CliSocketWithData, deps: Machine } const handleMachineStateUpdate: MachineUpdateStateHandler = (data, cb) => { + // The acknowledgement is the client's to send; one that leaves it out must not take the hub down. + const reply = typeof cb === 'function' ? cb : () => {} const parsed = machineUpdateStateSchema.safeParse(data) if (!parsed.success) { - cb({ result: 'error' }) + reply({ result: 'error' }) return } const { machineId: id, runnerState, expectedVersion } = parsed.data const machineAccess = resolveMachineAccess(id) if (!machineAccess.ok) { - cb({ result: 'error', reason: machineAccess.reason }) + reply({ result: 'error', reason: machineAccess.reason }) return } @@ -133,11 +137,11 @@ export function registerMachineHandlers(socket: CliSocketWithData, deps: Machine machineAccess.value.namespace ) if (result.result === 'success') { - cb({ result: 'success', version: result.version, runnerState: result.value }) + reply({ result: 'success', version: result.version, runnerState: result.value }) } else if (result.result === 'version-mismatch') { - cb({ result: 'version-mismatch', version: result.version, runnerState: result.value }) + reply({ result: 'version-mismatch', version: result.version, runnerState: result.value }) } else { - cb({ result: 'error' }) + reply({ result: 'error' }) } if (result.result === 'success') { diff --git a/hub/src/socket/handlers/cli/sessionHandlers.test.ts b/hub/src/socket/handlers/cli/sessionHandlers.test.ts index febd4d15e2e..a3a6627f4e0 100644 --- a/hub/src/socket/handlers/cli/sessionHandlers.test.ts +++ b/hub/src/socket/handlers/cli/sessionHandlers.test.ts @@ -49,6 +49,231 @@ it('does not rebroadcast stored messages and retains repeated consumption acknow store.close() }) +describe('a locally handled command does not answer the agent (#1717)', () => { + function harness() { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('local-command', {}, null, 'default') + const socket = new FakeSocket() + const delivered = mock((_sid: string, _at: number) => {}) + registerSessionHandlers(socket as unknown as CliSocketWithData, { + store, resolveSessionAccess: () => ({ ok: true, value: session }), emitAccessError() {}, + onWebappEvent() {}, onPromptDelivered: delivered + }) + return { store, session, socket, delivered } + } + + function sendPrompt(socket: FakeSocket, sid: string, localId: string): void { + socket.trigger('message', { + sid, localId, message: { role: 'user', content: { type: 'text', text: '/status' } } + }) + } + + it('clears the blocker when the prompt actually reaches the agent', () => { + // Positive control: the same shape WITHOUT the local-handler flag must + // still clear, or the assertion below would pass on a handler that + // never fires at all. + const { socket, session, delivered, store } = harness() + sendPrompt(socket, session.id, 'answer-1') + socket.trigger('messages-consumed', { sid: session.id, localIds: ['answer-1'] }) + + expect(delivered).toHaveBeenCalledTimes(1) + store.close() + }) + + it('reports the maintenance turn UP to the hub, not just hub-side', () => { + // My previous test for this called `markMaintenanceTurn` on the cache + // directly, so it could not see that the callback was declared in both + // option types and supplied by `startHub` but never forwarded to this + // handler — the fix was dead on arrival in production. Asserting the + // callback actually fires is what pins the wiring. + const { socket, session, store } = harness() + const maintenance: string[] = [] + const socket2 = new FakeSocket() + registerSessionHandlers(socket2 as unknown as CliSocketWithData, { + store, + resolveSessionAccess: () => ({ ok: true, value: session }), + emitAccessError() {}, + onWebappEvent() {}, + onMaintenanceTurn: (sid) => { maintenance.push(sid) } + }) + socket2.trigger('message', { + sid: session.id, + localId: 'compact-wire', + message: { role: 'user', content: { type: 'text', text: '/compact' } } + }) + socket2.trigger('messages-consumed', { + sid: session.id, localIds: ['compact-wire'], maintenance: true + }) + + expect(maintenance).toEqual([session.id]) + void socket + store.close() + }) + + it('leaves the blocker alone for a maintenance command, which keeps its grace', () => { + // OpenCode acknowledges /compact when it DEQUEUES the command, before + // compaction starts, and that consumed a command rather than + // delivering a prompt. It cannot reuse `clearQueuedThinkingGrace`, + // because /compact must KEEP that grace for the prompts queued behind + // it — so without a separate flag the hub cleared an unanswered + // blocker, and a cancellation during setup consumed no rows, leaving + // the blocker gone for good. + const { socket, session, delivered, store } = harness() + sendPrompt(socket, session.id, 'compact-1') + socket.trigger('messages-consumed', { + sid: session.id, localIds: ['compact-1'], maintenance: true + }) + + expect(delivered).not.toHaveBeenCalled() + store.close() + }) + + it('leaves the blocker alone for a command the CLI handled itself', () => { + // Copilot `/model`, Pi `/stats`, a rejected or aborted message, a + // failed steer: the CLI consumes the row and returns without ever + // prompting the agent. The operator typed something, so the row is + // genuinely consumed — but the question the agent asked is still + // unanswered, and clearing here dropped it out of the Blocked section + // with nobody having answered it. + const { socket, session, delivered, store } = harness() + sendPrompt(socket, session.id, 'slash-1') + socket.trigger('messages-consumed', { + sid: session.id, localIds: ['slash-1'], clearQueuedThinkingGrace: true + }) + + expect(delivered).not.toHaveBeenCalled() + store.close() + }) +}) + +describe('hub arrival survives the socket hop into ingestion (#1717)', () => { + function footerText(status: string): string { + return `Prose.\n\nAGENT_NOTIFY_SUMMARY ${JSON.stringify({ + version: 1, status, summary: `s-${status}` + })}` + } + + it('carries receivedAt on the emitted event, so ingestion does not fall back to the runner clock', () => { + // The handler builds the event by hand, and dropping `receivedAt` there + // silently defeated the whole boundary: ingestion fell back to + // `createdAt`, which is the agent runner's clock. A slow-clock runner's + // genuine blocked footer then looked older than the hub's delivery + // stamp and was rejected — the session never appeared in Blocked. + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('arrival-hop', {}, null, 'default') + const socket = new FakeSocket() + const events: SyncEvent[] = [] + registerSessionHandlers(socket as unknown as CliSocketWithData, { + store, resolveSessionAccess: () => ({ ok: true, value: session }), emitAccessError() {}, + onWebappEvent: event => events.push(event) + }) + + // Runner clock an hour behind the hub. + const runnerStamp = Date.now() - 3_600_000 + socket.trigger('message', { + sid: session.id, + message: { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText('blocked') }] } } + } + }, + createdAt: runnerStamp + }) + + const received = events.find(event => event.type === 'message-received') as + { message: { createdAt: number; receivedAt?: number | null } } | undefined + expect(received).toBeTruthy() + expect(received!.message.createdAt).toBe(runnerStamp) + // The arrival is the hub's own, not the runner's — that is the whole + // point, so assert they actually differ. + expect(received!.message.receivedAt).toBeGreaterThan(runnerStamp) + store.close() + }) +}) + +describe('blocked chrome through the real socket-to-ingestion path (#1717)', () => { + function footerText(status: string): string { + return `Prose.\n\nAGENT_NOTIFY_SUMMARY ${JSON.stringify({ + version: 1, status, summary: `s-${status}` + })}` + } + + async function wire(tag: string) { + const { SyncEngine } = await import('../../../sync/syncEngine') + const { RpcRegistry } = await import('../../rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession(tag, { path: '/tmp', host: 'h', flavor: 'claude' }, null, 'default') + const stored = store.sessions.getSessionByNamespace(session.id, 'default')! + const socket = new FakeSocket() + registerSessionHandlers(socket as unknown as CliSocketWithData, { + store, + resolveSessionAccess: () => ({ ok: true, value: stored }), + emitAccessError() {}, + onWebappEvent: (event) => engine.handleRealtimeEvent(event as SyncEvent), + onPromptDelivered: (sid, at) => engine.clearSessionLastNotifyOnDelivery(sid, at) + }) + return { store, engine, session, socket } + } + + function sendFooter(socket: FakeSocket, sid: string, status: string, createdAt: number): void { + socket.trigger('message', { + sid, + message: { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText(status) }] } } + } + }, + createdAt + }) + } + + function deliverPrompt(socket: FakeSocket, sid: string, localId: string): void { + socket.trigger('message', { + sid, localId, message: { role: 'user', content: { type: 'text', text: 'carry on' } } + }) + socket.trigger('messages-consumed', { sid, localIds: [localId] }) + } + + it('shows a slow-clock runner blocked after the prompt that provoked it', async () => { + // The runner is an hour behind, so its footer's author time predates + // the hub's delivery stamp for the prompt that caused it. Only the + // footer's hub ARRIVAL can tell the truth here, and it has to survive + // the socket hop to be available at all. + const { engine, session, socket } = await wire('socket-slow-clock') + deliverPrompt(socket, session.id, 'prompt-1') + + sendFooter(socket, session.id, 'blocked', Date.now() - 3_600_000) + + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + }) + + it('does not readmit a delayed footer from the turn the prompt answered', async () => { + // The other direction, and the reason arrival alone is not enough: this + // footer was authored BEFORE the reply but reaches the hub after it, so + // its arrival is genuinely later. The author time of the footer the + // delivery superseded is what rejects it. + const { engine, session, socket } = await wire('socket-delayed-sibling') + const runnerNow = Date.now() + + sendFooter(socket, session.id, 'blocked', runnerNow - 10_000) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + + deliverPrompt(socket, session.id, 'prompt-1') + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + + // Late output from that same, already-answered turn. + sendFooter(socket, session.id, 'blocked', runnerNow - 20_000) + + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + }) +}) + function redundantGoalStatusContent(message: string): unknown { return { role: 'agent', @@ -878,3 +1103,54 @@ it.each([ store.close() }) }) + +describe('updates sent without an acknowledgement', () => { + function registered() { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('ackless-update', { path: '/tmp', host: 'h' }, null, 'default') + const socket = new FakeSocket() + registerSessionHandlers(socket as unknown as CliSocketWithData, { + store, + resolveSessionAccess: () => ({ ok: true, value: session as StoredSession }), + emitAccessError: () => { + throw new Error('unexpected access error') + } + }) + return { store, session, socket } + } + + // A client that leaves out the acknowledgement is wrong; each of these used to throw inside the + // socket handler, which ends the hub process. + it('are applied all the same: update-state and update-metadata', () => { + const { store, session, socket } = registered() + + expect(() => socket.trigger('update-state', { + sid: session.id, + expectedVersion: session.agentStateVersion, + agentState: { controlledByUser: true } + })).not.toThrow() + expect(() => socket.trigger('update-metadata', { + sid: session.id, + expectedVersion: session.metadataVersion, + metadata: { path: '/elsewhere', host: 'h' } + })).not.toThrow() + + const after = store.sessions.getSession(session.id) + expect(after?.agentState).toMatchObject({ controlledByUser: true }) + expect(after?.metadata).toMatchObject({ path: '/elsewhere' }) + }) + + it('are refused without throwing when the payload is malformed or the version is stale', () => { + const { store, session, socket } = registered() + + expect(() => socket.trigger('update-state', {})).not.toThrow() + expect(() => socket.trigger('update-metadata', {})).not.toThrow() + expect(() => socket.trigger('update-state', { + sid: session.id, + expectedVersion: 99, + agentState: { controlledByUser: true } + })).not.toThrow() + + expect(store.sessions.getSession(session.id)?.agentState).toBeNull() + }) +}) diff --git a/hub/src/socket/handlers/cli/sessionHandlers.ts b/hub/src/socket/handlers/cli/sessionHandlers.ts index fb856382e5a..88337791f9e 100644 --- a/hub/src/socket/handlers/cli/sessionHandlers.ts +++ b/hub/src/socket/handlers/cli/sessionHandlers.ts @@ -135,10 +135,14 @@ export type SessionHandlersDeps = { /** Drops the queued-thinking grace so synchronous CLI handlers (e.g. slash * commands) don't leave the spinner stuck for the full grace window. */ onMessagesConsumed?: (sessionId: string) => void + /** Fired on CONFIRMED prompt consumption (#1717). */ + onPromptDelivered?: (sessionId: string, deliveredAt: number) => void + /** #1717: the next turn is maintenance, so it must not clear the footer. */ + onMaintenanceTurn?: (sessionId: string) => void } export function registerSessionHandlers(socket: CliSocketWithData, deps: SessionHandlersDeps): void { - const { store, resolveSessionAccess, emitAccessError, onSessionAlive, onSessionReady, onSessionEnd, onWebappEvent, onBackgroundTasks, onSessionActivity, onAgentProgress, onSweepImmediateQueued, onMessagesConsumed } = deps + const { store, resolveSessionAccess, emitAccessError, onSessionAlive, onSessionReady, onSessionEnd, onWebappEvent, onBackgroundTasks, onSessionActivity, onAgentProgress, onSweepImmediateQueued, onMessagesConsumed, onPromptDelivered, onMaintenanceTurn } = deps socket.on('native-queue-message', data => { const parsed = z.object({ sid: z.string(), localId: z.string().min(1), text: z.string().nullable() }).safeParse(data) @@ -321,6 +325,10 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session localId: msg.localId, content: msg.content, createdAt: msg.createdAt, + // Hub arrival must survive the hop into ingestion: without it + // the footer falls back to the runner's clock and a slow-clock + // agent's genuine blocker is rejected (#1717). + receivedAt: msg.receivedAt, invokedAt: msg.invokedAt, ...(msg.contentRevision ? { contentRevision: msg.contentRevision } : {}) } @@ -328,9 +336,11 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session }) const handleUpdateMetadata: UpdateMetadataHandler = (data, cb) => { + // The acknowledgement is the client's to send; one that leaves it out must not take the hub down. + const reply = typeof cb === 'function' ? cb : () => {} const parsed = updateMetadataSchema.safeParse(data) if (!parsed.success) { - cb({ result: 'error' }) + reply({ result: 'error' }) return } @@ -341,17 +351,17 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session // resurrect a concurrently-cleared one in this very write. const sessionAccess = resolveSessionAccess(sid, { fresh: true }) if (!sessionAccess.ok) { - cb({ result: 'error', reason: sessionAccess.reason }) + reply({ result: 'error', reason: sessionAccess.reason }) return } const gatedMetadata = gateExternalRefs(metadata) if (!externalRefsInMetadataValid(gatedMetadata)) { - cb({ result: 'error' }) + reply({ result: 'error' }) return } if (!cliMetadataWaitingValid(gatedMetadata)) { - cb({ result: 'error' }) + reply({ result: 'error' }) return } @@ -362,11 +372,11 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session sessionAccess.value.namespace ) if (result.result === 'success') { - cb({ result: 'success', version: result.version, metadata: result.value }) + reply({ result: 'success', version: result.version, metadata: result.value }) } else if (result.result === 'version-mismatch') { - cb({ result: 'version-mismatch', version: result.version, metadata: result.value }) + reply({ result: 'version-mismatch', version: result.version, metadata: result.value }) } else { - cb({ result: 'error' }) + reply({ result: 'error' }) } if (result.result === 'success') { @@ -408,16 +418,18 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session socket.on('update-metadata', handleUpdateMetadata) const handleUpdateState: UpdateStateHandler = (data, cb) => { + // The acknowledgement is the client's to send; one that leaves it out must not take the hub down. + const reply = typeof cb === 'function' ? cb : () => {} const parsed = updateStateSchema.safeParse(data) if (!parsed.success) { - cb({ result: 'error' }) + reply({ result: 'error' }) return } const { sid, agentState, expectedVersion } = parsed.data const sessionAccess = resolveSessionAccess(sid) if (!sessionAccess.ok) { - cb({ result: 'error', reason: sessionAccess.reason }) + reply({ result: 'error', reason: sessionAccess.reason }) return } @@ -428,11 +440,11 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session sessionAccess.value.namespace ) if (result.result === 'success') { - cb({ result: 'success', version: result.version, agentState: result.value }) + reply({ result: 'success', version: result.version, agentState: result.value }) } else if (result.result === 'version-mismatch') { - cb({ result: 'version-mismatch', version: result.version, agentState: result.value }) + reply({ result: 'version-mismatch', version: result.version, agentState: result.value }) } else { - cb({ result: 'error' }) + reply({ result: 'error' }) } if (result.result === 'success') { @@ -486,7 +498,7 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session onSessionReady?.(data) }) - socket.on('messages-consumed', (data: { sid: string; localIds: string[]; clearQueuedThinkingGrace?: boolean; steered?: boolean }) => { + socket.on('messages-consumed', (data: { sid: string; localIds: string[]; clearQueuedThinkingGrace?: boolean; steered?: boolean; maintenance?: boolean }) => { if (!data || typeof data.sid !== 'string' || !Array.isArray(data.localIds)) { return } @@ -501,13 +513,26 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session } const invokedAt = Date.now() let sessionUpdatedAt: number + // Only rows that were still uninvoked count as newly delivered. A + // replayed acknowledgement after the turn already finished blocked, + // and one naming unknown local ids, consume nothing — clearing on + // those erased a blocker the agent genuinely reported (#1717). + let newlyDelivered = false try { - sessionUpdatedAt = store.recordMessagesConsumed( + const consumedResult = store.recordMessagesConsumed( data.sid, localIds, invokedAt, - sessionAccess.value.namespace + sessionAccess.value.namespace, + // Persist the disposition, not just the live decision below: + // the backfill, rewind and merge paths re-derive "was this + // answered?" from the transcript long afterwards, and + // `invoked_at` alone reads a locally handled command as an + // answer the agent never received (#1717). + { agentDelivered: data.clearQueuedThinkingGrace !== true && data.maintenance !== true } ) + sessionUpdatedAt = consumedResult.updatedAt + newlyDelivered = consumedResult.consumed > 0 } catch (err) { console.error('recordMessagesConsumed failed', err) return @@ -519,6 +544,48 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session console.error('onSessionActivity failed', err) } + // #1717: the blocker clears when the agent actually RECEIVES the + // prompt, not when the hub optimistically queues it. Clearing at + // queue time erased a footer on an idempotent retry of an + // already-consumed message (no new turn started), and on a prompt + // cancelled before it was ever delivered. + // + // `clearQueuedThinkingGrace` is the CLI saying it consumed the row + // synchronously and no agent turn will follow: a slash command it + // handled itself (Copilot `/model`, Pi `/stats`), a message it rejected + // or aborted, or a steer that failed. The operator typed something, so + // the row counts as consumed — but the agent never saw it, so whatever + // it was waiting on is still unanswered. A successful steer reaches the + // agent and reports `steered` instead, so it still clears. + // + // `maintenance` is the same statement on a separate axis: OpenCode + // acknowledges /compact when it DEQUEUES the command, before + // compaction starts, so that consumed a command rather than delivering + // a prompt. It cannot reuse `clearQueuedThinkingGrace`, because + // /compact must KEEP that grace for the prompts queued behind it — so + // without its own flag the hub cleared an unanswered blocker, and a + // cancellation during setup consumed no rows, leaving it gone. + if (data.maintenance === true) { + // The thinking start that follows must not delete the footer: + // OpenCode sends thinking=true before compaction begins, and that + // keepalive was erasing a blocker nothing had answered (#1717). + try { + onMaintenanceTurn?.(data.sid) + } catch (err) { + console.error('onMaintenanceTurn failed', err) + } + } + + if (newlyDelivered + && data.clearQueuedThinkingGrace !== true + && data.maintenance !== true) { + try { + onPromptDelivered?.(data.sid, invokedAt) + } catch (err) { + console.error('onPromptDelivered failed', err) + } + } + // Only drop the queued-thinking grace when the CLI explicitly opts in // (synchronous handlers like slash commands that will never send // their own `thinking=true` keepalive). Normal queue drains still diff --git a/hub/src/socket/handlers/terminal.ws-interop.test.ts b/hub/src/socket/handlers/terminal.ws-interop.test.ts new file mode 100644 index 00000000000..6a04e673f3f --- /dev/null +++ b/hub/src/socket/handlers/terminal.ws-interop.test.ts @@ -0,0 +1,274 @@ +import { afterAll, beforeAll, describe, expect, it } from 'bun:test' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { SignJWT } from 'jose' +import { createConfiguration, resetConfigurationForTests } from '../../configuration' +import { Store } from '../../store' +import { createSocketServer } from '../server' +import { clearAgentTerminalBuffer } from '../agentTerminalBuffer' +import { clearUserTerminalBuffer } from '../userTerminalBuffer' + +/** + * Raw WebSocket wrapper matching the exact Engine.IO v4 + Socket.IO v4 text + * framing implemented by iOS `TerminalSocketCodec` (direct WebSocket upgrade + * without HTTP long-polling). + */ +class RawSocketIOClient { + readonly ws: WebSocket + private readonly queue: string[] = [] + private readonly waiters: Array<{ + predicate: (frame: string) => boolean + resolve: (frame: string) => void + reject: (err: Error) => void + timer: ReturnType + }> = [] + + constructor(url: string) { + this.ws = new WebSocket(url) + this.ws.addEventListener('message', (event) => { + const text = typeof event.data === 'string' ? event.data : String(event.data) + // Automatically answer Engine.IO ping ('2') with pong ('3') just like TerminalSocketClient. + if (text === '2') { + this.ws.send('3') + return + } + const idx = this.waiters.findIndex((w) => w.predicate(text)) + if (idx >= 0) { + const [waiter] = this.waiters.splice(idx, 1) + clearTimeout(waiter.timer) + waiter.resolve(text) + } else { + this.queue.push(text) + } + }) + } + + async waitForOpen(): Promise { + if (this.ws.readyState === WebSocket.OPEN) return + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('WebSocket open timeout')), 5_000) + this.ws.addEventListener('open', () => { + clearTimeout(timer) + resolve() + }, { once: true }) + this.ws.addEventListener('error', () => { + clearTimeout(timer) + reject(new Error('WebSocket open error')) + }, { once: true }) + }) + } + + waitForFrame(predicate: (frame: string) => boolean, timeoutMs = 5_000): Promise { + const queuedIdx = this.queue.findIndex(predicate) + if (queuedIdx >= 0) { + const [frame] = this.queue.splice(queuedIdx, 1) + return Promise.resolve(frame) + } + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + const idx = this.waiters.findIndex((w) => w.resolve === resolve) + if (idx >= 0) this.waiters.splice(idx, 1) + reject(new Error(`Timed out waiting for matching frame (queued: ${JSON.stringify(this.queue)})`)) + }, timeoutMs) + this.waiters.push({ predicate, resolve, reject, timer }) + }) + } + + send(frame: string): void { + this.ws.send(frame) + } + + close(): void { + try { + this.ws.close() + } catch { + // ignore + } + } +} + +function parseEventFrame(frame: string, namespace: string): { event: string; payload: Record } | null { + const prefix = `42${namespace},` + if (!frame.startsWith(prefix)) return null + const parsed = JSON.parse(frame.slice(prefix.length)) as [string, Record] + return { event: parsed[0], payload: parsed[1] } +} + +describe('Socket.IO /terminal direct-WebSocket interop (native iOS framing)', () => { + const jwtSecret = new TextEncoder().encode('test-jwt-secret-for-ws-interop-32b!') + let homeDir = '' + let previousHapiHome: string | undefined + let store: Store + let server: ReturnType + let baseWsUrl = '' + let sessionId = '' + let validJwt = '' + + beforeAll(async () => { + previousHapiHome = process.env.HAPI_HOME + homeDir = mkdtempSync(join(tmpdir(), 'hapi-terminal-ws-interop-')) + process.env.HAPI_HOME = homeDir + resetConfigurationForTests() + const config = await createConfiguration() + config._setCliApiToken('cli-interop-token', 'env', false) + + store = new Store(':memory:') + const created = store.sessions.getOrCreateSession( + 'interop-tag', + { path: '/tmp/interop', host: 'dev-host', startingMode: 'pty' }, + null, + 'default' + ) + sessionId = created.id + + const { engine } = createSocketServer({ + store, + jwtSecret, + corsOrigins: ['*'], + getSession: (id) => (id === sessionId ? { active: true, namespace: 'default' } : null) + }) + const handler = engine.handler() + // eslint-disable-next-line @typescript-eslint/no-explicit-any + server = (Bun.serve as any)({ + hostname: '127.0.0.1', + port: 0, + fetch(req: Request, srv: unknown) { + return handler.fetch(req, srv as never) + }, + websocket: handler.websocket + }) + baseWsUrl = `ws://127.0.0.1:${server.port}/socket.io/?EIO=4&transport=websocket` + + validJwt = await new SignJWT({ uid: 1, ns: 'default' }) + .setProtectedHeader({ alg: 'HS256' }) + .setIssuedAt() + .setExpirationTime('1h') + .sign(jwtSecret) + }) + + afterAll(() => { + clearUserTerminalBuffer(sessionId, 'term-interop-1') + clearAgentTerminalBuffer(sessionId) + server?.stop(true) + store?.close() + if (previousHapiHome === undefined) delete process.env.HAPI_HOME + else process.env.HAPI_HOME = previousHapiHome + if (homeDir) { + resetConfigurationForTests(homeDir) + rmSync(homeDir, { recursive: true, force: true }) + } + }) + + it('rejects an invalid JWT on /terminal with Socket.IO connect_error (44/terminal,...)', async () => { + const client = new RawSocketIOClient(baseWsUrl) + try { + await client.waitForOpen() + const openFrame = await client.waitForFrame((f) => f.startsWith('0{')) + const openJson = JSON.parse(openFrame.slice(1)) as { sid: string; pingInterval: number; pingTimeout: number } + expect(typeof openJson.sid).toBe('string') + expect(openJson.pingInterval).toBeGreaterThan(0) + expect(openJson.pingTimeout).toBeGreaterThan(0) + + client.send('40/terminal,{"token":"not-a-valid-jwt"}') + const errFrame = await client.waitForFrame((f) => f.startsWith('44/terminal,')) + const errJson = JSON.parse(errFrame.slice('44/terminal,'.length)) as { message: string } + expect(errJson.message).toBe('Invalid token') + } finally { + client.close() + } + }) + + it('bridges shell create/ready/output/write/resize, retained-id replay, and agent PTY streams over direct WS frames', async () => { + const cli = new RawSocketIOClient(baseWsUrl) + const term1 = new RawSocketIOClient(baseWsUrl) + let term2: RawSocketIOClient | null = null + + try { + // 1. Connect mock CLI to /cli for this session + await cli.waitForOpen() + await cli.waitForFrame((f) => f.startsWith('0{')) + cli.send(`40/cli,${JSON.stringify({ token: 'cli-interop-token', sessionId })}`) + await cli.waitForFrame((f) => f.startsWith('40/cli,')) + + // 2. Connect native-style client to /terminal with valid JWT + await term1.waitForOpen() + await term1.waitForFrame((f) => f.startsWith('0{')) + term1.send(`40/terminal,${JSON.stringify({ token: validJwt })}`) + const connectFrame = await term1.waitForFrame((f) => f.startsWith('40/terminal,')) + expect(connectFrame.startsWith('40/terminal,{')).toBe(true) + + // 3. Interactive Shell flow: terminal:create -> CLI terminal:open -> ready/output -> write/resize + const terminalId = 'term-interop-1' + term1.send(`42/terminal,${JSON.stringify(['terminal:create', { sessionId, terminalId, cols: 80, rows: 24 }])}`) + + const openOnCli = await cli.waitForFrame((f) => parseEventFrame(f, '/cli')?.event === 'terminal:open') + expect(parseEventFrame(openOnCli, '/cli')?.payload).toEqual({ sessionId, terminalId, cols: 80, rows: 24 }) + + cli.send(`42/cli,${JSON.stringify(['terminal:ready', { sessionId, terminalId }])}`) + const readyFrame = await term1.waitForFrame((f) => parseEventFrame(f, '/terminal')?.event === 'terminal:ready') + expect(parseEventFrame(readyFrame, '/terminal')?.payload).toMatchObject({ terminalId }) + + cli.send(`42/cli,${JSON.stringify(['terminal:output', { sessionId, terminalId, data: 'hello \x1b[32mcoretext\x1b[0m\r\n' }])}`) + const outFrame = await term1.waitForFrame((f) => parseEventFrame(f, '/terminal')?.event === 'terminal:output') + expect(parseEventFrame(outFrame, '/terminal')?.payload).toMatchObject({ + terminalId, + data: 'hello \x1b[32mcoretext\x1b[0m\r\n' + }) + + term1.send(`42/terminal,${JSON.stringify(['terminal:write', { terminalId, data: 'ls -la\r' }])}`) + const writeOnCli = await cli.waitForFrame((f) => parseEventFrame(f, '/cli')?.event === 'terminal:write') + expect(parseEventFrame(writeOnCli, '/cli')?.payload).toEqual({ sessionId, terminalId, data: 'ls -la\r' }) + + term1.send(`42/terminal,${JSON.stringify(['terminal:resize', { terminalId, cols: 100, rows: 32 }])}`) + const resizeOnCli = await cli.waitForFrame((f) => parseEventFrame(f, '/cli')?.event === 'terminal:resize') + expect(parseEventFrame(resizeOnCli, '/cli')?.payload).toEqual({ sessionId, terminalId, cols: 100, rows: 32 }) + + // 4. Agent PTY flow: subscribe -> CLI refresh -> output -> input -> resize -> unsubscribe + term1.send(`42/terminal,${JSON.stringify(['agent-terminal:subscribe', { sessionId }])}`) + const refreshOnCli = await cli.waitForFrame((f) => parseEventFrame(f, '/cli')?.event === 'agent-terminal:refresh') + expect(parseEventFrame(refreshOnCli, '/cli')?.payload).toEqual({ sessionId }) + + cli.send(`42/cli,${JSON.stringify(['agent-terminal:output', { sessionId, terminalId: 'agent', data: '\x1b[?1049h\x1b[HAgent TUI' }])}`) + const agentOut = await term1.waitForFrame((f) => parseEventFrame(f, '/terminal')?.event === 'agent-terminal:output') + expect(parseEventFrame(agentOut, '/terminal')?.payload).toEqual({ + sessionId, + terminalId: 'agent', + data: '\x1b[?1049h\x1b[HAgent TUI' + }) + + term1.send(`42/terminal,${JSON.stringify(['agent-terminal:input', { sessionId, data: '\x1b[A' }])}`) + const agentInOnCli = await cli.waitForFrame((f) => parseEventFrame(f, '/cli')?.event === 'agent-terminal:input') + expect(parseEventFrame(agentInOnCli, '/cli')?.payload).toEqual({ sessionId, data: '\x1b[A' }) + + term1.send(`42/terminal,${JSON.stringify(['agent-terminal:resize', { sessionId, cols: 110, rows: 36 }])}`) + const agentResizeOnCli = await cli.waitForFrame((f) => parseEventFrame(f, '/cli')?.event === 'agent-terminal:resize') + expect(parseEventFrame(agentResizeOnCli, '/cli')?.payload).toEqual({ sessionId, cols: 110, rows: 36 }) + + term1.send(`42/terminal,${JSON.stringify(['agent-terminal:unsubscribe', { sessionId }])}`) + const idleOnCli = await cli.waitForFrame((f) => parseEventFrame(f, '/cli')?.event === 'agent-terminal:idle') + expect(parseEventFrame(idleOnCli, '/cli')?.payload).toEqual({ sessionId }) + + // 5. Disconnect first terminal client cleanly and reattach with same terminalId -> scrollback replay + term1.send('41/terminal,') + term1.close() + + term2 = new RawSocketIOClient(baseWsUrl) + await term2.waitForOpen() + await term2.waitForFrame((f) => f.startsWith('0{')) + term2.send(`40/terminal,${JSON.stringify({ token: validJwt })}`) + await term2.waitForFrame((f) => f.startsWith('40/terminal,')) + + term2.send(`42/terminal,${JSON.stringify(['terminal:create', { sessionId, terminalId, cols: 100, rows: 32 }])}`) + const replayed = await term2.waitForFrame((f) => parseEventFrame(f, '/terminal')?.event === 'terminal:output') + expect(parseEventFrame(replayed, '/terminal')?.payload).toEqual({ + terminalId, + data: 'hello \x1b[32mcoretext\x1b[0m\r\n' + }) + } finally { + term1.close() + term2?.close() + cli.close() + } + }) +}) diff --git a/hub/src/socket/server.ts b/hub/src/socket/server.ts index 81d4cfd5061..1dd280de5a5 100644 --- a/hub/src/socket/server.ts +++ b/hub/src/socket/server.ts @@ -49,6 +49,8 @@ export type SocketServerDeps = { onAgentProgress?: (sessionId: string, at: number) => void onSweepImmediateQueued?: (sessionId: string, now: number) => void onMessagesConsumed?: (sessionId: string) => void + onPromptDelivered?: (sessionId: string, deliveredAt: number) => void + onMaintenanceTurn?: (sessionId: string) => void } export function createSocketServer(deps: SocketServerDeps): { @@ -138,7 +140,9 @@ export function createSocketServer(deps: SocketServerDeps): { onSessionActivity: deps.onSessionActivity, onAgentProgress: deps.onAgentProgress, onSweepImmediateQueued: deps.onSweepImmediateQueued, - onMessagesConsumed: deps.onMessagesConsumed + onMessagesConsumed: deps.onMessagesConsumed, + onPromptDelivered: deps.onPromptDelivered, + onMaintenanceTurn: deps.onMaintenanceTurn })) terminalNs.use(async (socket, next) => { diff --git a/hub/src/startHub.ts b/hub/src/startHub.ts index 0faefa4f23d..811e742af94 100644 --- a/hub/src/startHub.ts +++ b/hub/src/startHub.ts @@ -5,6 +5,7 @@ import { NotificationHub } from './notifications/notificationHub' import type { NotificationChannel } from './notifications/notificationTypes' import { HappyBot } from './telegram/bot' import { startWebServer } from './web/server' +import { getOrCreateHubId } from './config/hubId' import { getOrCreateJwtSecret } from './config/jwtSecret' import { getOrCreateOwnerId } from './config/ownerId' import { createSocketServer } from './socket/server' @@ -178,6 +179,7 @@ export async function startHub(options: StartHubOptions = {}): Promise syncEngine?.recordSessionActivity(sessionId, updatedAt), onAgentProgress: (sessionId, at) => syncEngine?.recordAgentProgress(sessionId, at), onSweepImmediateQueued: (sessionId, now) => syncEngine?.sweepImmediateQueuedOnSessionEnd(sessionId, now), - onMessagesConsumed: (sessionId) => syncEngine?.clearQueuedThinkingGrace(sessionId) + onMessagesConsumed: (sessionId) => syncEngine?.clearQueuedThinkingGrace(sessionId), + onPromptDelivered: (sessionId, deliveredAt) => + syncEngine?.clearSessionLastNotifyOnDelivery(sessionId, deliveredAt), + onMaintenanceTurn: (sessionId) => syncEngine?.markMaintenanceTurn(sessionId) }) syncEngine = new SyncEngine(store, socketServer.io, socketServer.rpcRegistry, sseManager) // Accountable principal for A2A work-graph notify ingest (P3). syncEngine.setHubOwnerUserId(await getOrCreateOwnerId()) + // #1717: hubs upgraded mid-flight would otherwise show no blocked chrome + // until every agent speaks again. Deferred off the startup path — it is a + // bounded catch-up scan, not something the first request should wait on. + setTimeout(() => { + syncEngine?.backfillRecentNotifySignals().catch((error) => { + console.error('[notify-backfill] failed', error) + }) + }, 0) const androidPushConfig = resolveAndroidPushConfig(config) const notificationChannels: NotificationChannel[] = [] if (androidPushConfig.mode === 'fcm') { const { fcm } = androidPushConfig const sender = new FcmService(fcm.projectId, fcm.serviceAccount, store) - notificationChannels.push(new FcmNotificationChannel(sender, sseManager, visibilityTracker, store)) + notificationChannels.push(new FcmNotificationChannel(sender, sseManager, visibilityTracker, store, hubId)) console.log(`[Hub] Android push: fcm (project: ${fcm.projectId})`) } else if (androidPushConfig.mode === 'relay') { const sender = new AndroidRelayService(new RelayClient(androidPushConfig.relayUrl, 'android'), store) - notificationChannels.push(new FcmNotificationChannel(sender, sseManager, visibilityTracker, store)) + notificationChannels.push(new FcmNotificationChannel(sender, sseManager, visibilityTracker, store, hubId)) console.log(`[Hub] Android push: relay (url: ${androidPushConfig.relayUrl})`) } else { console.log(`[Hub] Android push: off (${androidPushConfig.reason})`) @@ -234,11 +247,11 @@ export async function startHub(options: StartHubOptions = {}): Promise { }) expect(store.fcm.getDevicesByNamespace('default')).toHaveLength(2) }) + + it('stores preferences, preserves them when omitted on update, and overwrites when supplied', () => { + const store = new Store(':memory:') + const key = Buffer.alloc(32, 8).toString('base64') + + store.fcm.upsertDevice('default', { + token: 'apns-1', + platform: 'ios', + deviceId: 'iphone-1', + pushKey: key, + preferences: { ready: false, inputRequest: false } + }) + expect(store.fcm.getDevicesByNamespace('default', ['ios'])[0].preferences).toEqual({ + ready: false, + permissionRequest: true, + inputRequest: false, + modelError: true + }) + + // Token rotation without preferences preserves the stored filter. + store.fcm.upsertDevice('default', { + token: 'apns-2', + platform: 'ios', + deviceId: 'iphone-1', + pushKey: key + }) + const afterRotation = store.fcm.getDevicesByNamespace('default', ['ios'])[0] + expect(afterRotation.token).toBe('apns-2') + expect(afterRotation.preferences).toEqual({ + ready: false, + permissionRequest: true, + inputRequest: false, + modelError: true + }) + + // Explicit preferences object overwrites the stored filter. + store.fcm.upsertDevice('default', { + token: 'apns-2', + platform: 'ios', + deviceId: 'iphone-1', + pushKey: key, + preferences: { ready: true, permissionRequest: true, inputRequest: true, modelError: false } + }) + expect(store.fcm.getDevicesByNamespace('default', ['ios'])[0].preferences).toEqual({ + ready: true, + permissionRequest: true, + inputRequest: true, + modelError: false + }) + }) }) diff --git a/hub/src/store/fcmDevices.ts b/hub/src/store/fcmDevices.ts index 740da420432..46adbd3b245 100644 --- a/hub/src/store/fcmDevices.ts +++ b/hub/src/store/fcmDevices.ts @@ -1,6 +1,11 @@ import type { Database } from 'bun:sqlite' -import type { NativeDevicePlatform, StoredFcmDevice } from './types' +import type { + NativeDevicePlatform, + NativePushPreferences, + NativePushPreferencesInput, + StoredFcmDevice +} from './types' type DbFcmDeviceRow = { id: number @@ -9,10 +14,62 @@ type DbFcmDeviceRow = { platform: string device_id: string push_key: string | null + preferences_json: string | null created_at: number updated_at: number } +export function normalizeNativePushPreferences( + input: NativePushPreferencesInput +): NativePushPreferences { + return { + ready: input.ready ?? true, + permissionRequest: input.permissionRequest ?? true, + inputRequest: input.inputRequest ?? true, + modelError: input.modelError ?? true + } +} + +export function parseNativePushPreferences(raw: string | null | undefined): NativePushPreferences | null { + if (!raw) return null + try { + const parsed = JSON.parse(raw) as unknown + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null + const obj = parsed as Record + return { + ready: typeof obj.ready === 'boolean' ? obj.ready : true, + permissionRequest: typeof obj.permissionRequest === 'boolean' ? obj.permissionRequest : true, + inputRequest: typeof obj.inputRequest === 'boolean' ? obj.inputRequest : true, + modelError: typeof obj.modelError === 'boolean' ? obj.modelError : true + } + } catch { + return null + } +} + +/** + * Returns whether a native device wants push delivery for `eventType`. + * Unset preferences (`null`/`undefined`) and unknown future event types fail open (`true`). + */ +export function isNativePushEventEnabled( + preferences: NativePushPreferences | null | undefined, + eventType: string +): boolean { + if (!preferences) return true + switch (eventType) { + case 'ready': + return preferences.ready + case 'permission-request': + return preferences.permissionRequest + case 'input-request': + return preferences.inputRequest + case 'model-error': + return preferences.modelError + default: + return true + } +} + function toStoredFcmDevice(row: DbFcmDeviceRow): StoredFcmDevice { return { id: row.id, @@ -21,6 +78,7 @@ function toStoredFcmDevice(row: DbFcmDeviceRow): StoredFcmDevice { platform: row.platform as StoredFcmDevice['platform'], deviceId: row.device_id, pushKey: row.push_key, + preferences: parseNativePushPreferences(row.preferences_json), createdAt: row.created_at, updatedAt: row.updated_at } @@ -29,15 +87,26 @@ function toStoredFcmDevice(row: DbFcmDeviceRow): StoredFcmDevice { export function upsertFcmDevice( db: Database, namespace: string, - device: { token: string; platform: NativeDevicePlatform; deviceId: string; pushKey?: string } + device: { + token: string + platform: NativeDevicePlatform + deviceId: string + pushKey?: string + preferences?: NativePushPreferencesInput + } ): void { const now = Date.now() + const hasPreferences = device.preferences !== undefined + const preferencesJson = hasPreferences + ? JSON.stringify(normalizeNativePushPreferences(device.preferences!)) + : null const params = { namespace, token: device.token, platform: device.platform, device_id: device.deviceId, push_key: device.pushKey ?? null, + preferences_json: preferencesJson, created_at: now, updated_at: now } @@ -52,18 +121,36 @@ export function upsertFcmDevice( AND (namespace != @namespace OR device_id != @device_id OR platform != @platform) `).run(params) - db.prepare(` - INSERT INTO fcm_devices ( - namespace, token, platform, device_id, push_key, created_at, updated_at - ) VALUES ( - @namespace, @token, @platform, @device_id, @push_key, @created_at, @updated_at - ) - ON CONFLICT(namespace, device_id, platform) - DO UPDATE SET - token = excluded.token, - push_key = excluded.push_key, - updated_at = excluded.updated_at - `).run(params) + if (hasPreferences) { + db.prepare(` + INSERT INTO fcm_devices ( + namespace, token, platform, device_id, push_key, preferences_json, created_at, updated_at + ) VALUES ( + @namespace, @token, @platform, @device_id, @push_key, @preferences_json, @created_at, @updated_at + ) + ON CONFLICT(namespace, device_id, platform) + DO UPDATE SET + token = excluded.token, + push_key = excluded.push_key, + preferences_json = excluded.preferences_json, + updated_at = excluded.updated_at + `).run(params) + } else { + // When preferences are omitted (e.g. legacy client or token-only + // refresh), preserve any previously saved per-device filter. + db.prepare(` + INSERT INTO fcm_devices ( + namespace, token, platform, device_id, push_key, preferences_json, created_at, updated_at + ) VALUES ( + @namespace, @token, @platform, @device_id, @push_key, NULL, @created_at, @updated_at + ) + ON CONFLICT(namespace, device_id, platform) + DO UPDATE SET + token = excluded.token, + push_key = excluded.push_key, + updated_at = excluded.updated_at + `).run(params) + } })() } diff --git a/hub/src/store/fcmStore.ts b/hub/src/store/fcmStore.ts index 1874a7ed745..6abb6e7d64e 100644 --- a/hub/src/store/fcmStore.ts +++ b/hub/src/store/fcmStore.ts @@ -1,6 +1,6 @@ import type { Database } from 'bun:sqlite' -import type { NativeDevicePlatform, StoredFcmDevice } from './types' +import type { NativeDevicePlatform, NativePushPreferencesInput, StoredFcmDevice } from './types' import { getFcmDevicesByNamespace, removeFcmDeviceByToken, upsertFcmDevice } from './fcmDevices' /** @@ -15,7 +15,13 @@ export class FcmStore { upsertDevice( namespace: string, - device: { token: string; platform: NativeDevicePlatform; deviceId: string; pushKey?: string } + device: { + token: string + platform: NativeDevicePlatform + deviceId: string + pushKey?: string + preferences?: NativePushPreferencesInput + } ): void { upsertFcmDevice(this.db, namespace, device) } diff --git a/hub/src/store/index.ts b/hub/src/store/index.ts index 8aa75f44968..7db0c8d37df 100644 --- a/hub/src/store/index.ts +++ b/hub/src/store/index.ts @@ -6,6 +6,8 @@ import { dirname } from 'node:path' import { MachineStore } from './machineStore' import { MessageStore } from './messageStore' import { addMessage } from './messages' +import { decodeMessageContent } from './contentCodec' +import { isUserInputMessage } from './sessionUserActivity' import { clearCachedStatements } from './statementCache' import { backfillLastUserMessageAt } from './sessionUserActivity' import type { StoredMessage } from './types' @@ -61,7 +63,7 @@ export { WorkGraphValidationError } from './workGraph' -const SCHEMA_VERSION: number = 37 +const SCHEMA_VERSION: number = 41 const REQUIRED_TABLES = [ 'sessions', 'machines', @@ -172,10 +174,26 @@ export class Store { sessionId: string, localIds: string[], invokedAt: number, - namespace: string - ): number { + namespace: string, + options?: { agentDelivered?: boolean } + ): { updatedAt: number; consumed: number } { return this.db.transaction(() => { - const changes = this.messages.markMessagesInvoked(sessionId, localIds, invokedAt) + // Which of these rows are actually the operator's prompts? Agent + // OUTPUT also carries local ids and emits `messages-consumed` + // (OpenCode compaction summaries via `sendAgentMessage`), and + // counting those as a delivered reply cleared a live blocker. + const placeholders = localIds.map(() => '?').join(', ') + const pending = localIds.length === 0 + ? [] + : this.db.prepare( + `SELECT content FROM messages + WHERE session_id = ? AND local_id IN (${placeholders}) + AND invoked_at IS NULL` + ).all(sessionId, ...localIds) as Array<{ content: string | Uint8Array }> + const operatorPrompts = pending.filter( + (row) => isUserInputMessage(decodeMessageContent(row.content)) + ).length + const changes = this.messages.markMessagesInvoked(sessionId, localIds, invokedAt, options) if (changes > 0) { this.sessions.touchSessionUpdatedAt(sessionId, invokedAt, namespace) } @@ -188,7 +206,15 @@ export class Store { throw new Error('session activity was not persisted after messages-consumed transition') } - return session.updatedAt + // `consumed` is 0 for a replayed acknowledgement or unknown local + // ids: nothing reached the agent, so callers must not treat it as + // a delivery (#1717). + // `consumed` counts only operator prompts: a replayed ack, unknown + // local ids, and agent output all deliver nothing (#1717). + return { + updatedAt: session.updatedAt, + consumed: operatorPrompts + } })() } @@ -406,7 +432,10 @@ export class Store { // upstream read-state at v29→v30; // #1404 session_jobs at v31→v32 (after upstream FTS v30→v31); run_id fence at v32→v33; // #1489 wake-on-terminal at v33→v34; session_redirects at v34→v35; - // passkey_credentials at v35→v36; null run_id backfill at v36→v37 + // passkey_credentials at v35→v36; null run_id backfill at v36→v37; + // #1717 blocker-footer identity hardening at v37→v38/v38→v39/v39→v40; + // per-device push preferences_json at v40→v41 (renumbered past + // #1717's chain — upstream's own v37→v38 collided with ours). // (jobs remapped again after upstream took 28/29/30). 21: () => this.migrateFromV21ToV22(), 22: () => this.migrateFromV22ToV23(), @@ -424,6 +453,13 @@ export class Store { 34: () => this.migrateFromV34ToV35(), 35: () => this.migrateFromV35ToV36(), 36: () => this.migrateFromV36ToV37(), + // #1717 blocker-footer identity hardening at v37→v38/v38→v39/v39→v40. + 37: () => this.migrateFromV37ToV38(), + 38: () => this.migrateFromV38ToV39(), + 39: () => this.migrateFromV39ToV40(), + // Upstream per-device push preferences_json, renumbered from its + // original v37→v38 to run after #1717's chain. + 40: () => this.migrateFromV40ToV41(), } if (currentVersion !== 0 && (currentVersion > SCHEMA_VERSION || !stepMigrations[currentVersion])) { @@ -447,14 +483,18 @@ export class Store { // Keep the individual steps below for databases that resume from an // intermediate schema version after an interrupted upgrade. this.migrateFromV26ToV30() - this.migrateFromV29ToV30() - this.migrateFromV30ToV31() - this.migrateFromV31ToV32() - this.migrateFromV32ToV33() - this.migrateFromV33ToV34() - this.migrateFromV34ToV35() - this.migrateFromV35ToV36() - this.migrateFromV36ToV37() + // ...then run the REMAINING ladder by index rather than by hand. + // This branch used to list each later step explicitly, so a + // migration added to `stepMigrations` but not copied here was + // silently skipped while the database was still stamped at + // SCHEMA_VERSION — the row then claimed a version whose columns it + // did not have, and the hub failed to start. Driving the ladder + // from the same source removes that whole class. + for (let v = 29; v < SCHEMA_VERSION; v++) { + const step = stepMigrations[v] + if (!step) throw this.buildSchemaMismatchError(currentVersion) + step() + } } else { for (let v = currentVersion; v < SCHEMA_VERSION; v++) { const step = stepMigrations[v] @@ -496,6 +536,16 @@ export class Store { team_state_updated_at INTEGER, pinned INTEGER NOT NULL DEFAULT 0, global_pinned INTEGER NOT NULL DEFAULT 0, + last_notify_status TEXT, + last_notify_at INTEGER, + last_notify_note TEXT, + last_notify_cleared_at INTEGER, + last_notify_received_at INTEGER, + last_notify_cleared_author_at INTEGER, + last_notify_updated_at INTEGER, + blocked_ack_at INTEGER, + blocked_ack_reason TEXT, + blocked_ack_key TEXT, active INTEGER DEFAULT 0, active_at INTEGER, seq INTEGER DEFAULT 0 @@ -527,6 +577,9 @@ export class Store { seq INTEGER NOT NULL, local_id TEXT, invoked_at INTEGER, + received_at INTEGER, + agent_delivered INTEGER, + swept_at INTEGER, scheduled_at INTEGER, delivery_state TEXT NOT NULL DEFAULT 'queued', FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE @@ -586,6 +639,7 @@ export class Store { platform TEXT NOT NULL, device_id TEXT NOT NULL, push_key TEXT, + preferences_json TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, UNIQUE(namespace, device_id, platform) @@ -1290,6 +1344,94 @@ export class Store { rebuildMessageContentSearch(this.db) } + /** Blocked-agent session-list chrome (#1717): persist the last + * AGENT_NOTIFY_SUMMARY footer so the list can flag stuck agents without + * re-reading messages. */ + private migrateFromV37ToV38(): void { + const columns = this.getSessionColumnNames() + if (columns.size === 0) return + if (!columns.has('last_notify_status')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN last_notify_status TEXT') + } + if (!columns.has('last_notify_at')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN last_notify_at INTEGER') + } + if (!columns.has('last_notify_note')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN last_notify_note TEXT') + } + } + + /** Operator manual-unblock watermark + rationale (#1717). */ + private migrateFromV38ToV39(): void { + const columns = this.getSessionColumnNames() + if (columns.size === 0) return + if (!columns.has('blocked_ack_at')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN blocked_ack_at INTEGER') + } + if (!columns.has('blocked_ack_reason')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN blocked_ack_reason TEXT') + } + } + + /** Persisted clear boundary (#1717): an incoming footer older than the + * turn that cleared the last one has already been answered. Survives the + * turn ending and a restart, which `activeTurnStartedAt` does not. */ + private migrateFromV39ToV40(): void { + const columns = this.getSessionColumnNames() + if (columns.size === 0) return + if (!columns.has('last_notify_cleared_at')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN last_notify_cleared_at INTEGER') + } + if (!columns.has('last_notify_updated_at')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN last_notify_updated_at INTEGER') + } + // The author time of the footer a delivery superseded, in the RUNNER's + // clock. Delivery nulls `last_notify_at`, so without this a footer from + // the already-answered turn arriving late for the first time has + // nothing to be measured against and walks back in. Two footers from + // one runner are a sound comparison; this is that, kept across the + // clear. + // The footer's HUB arrival, kept beside its runner-clock author time. + // Each guard then compares inside one clock domain. + if (!columns.has('last_notify_received_at')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN last_notify_received_at INTEGER') + } + if (!columns.has('last_notify_cleared_author_at')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN last_notify_cleared_author_at INTEGER') + } + if (!columns.has('blocked_ack_key')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN blocked_ack_key TEXT') + } + // The session-end sweep stamps `invoked_at` on immediate queued rows + // the runtime never received, so `invoked_at` alone cannot answer "did + // the agent see this reply?". A dedicated marker keeps that distinction + // out of `delivery_state`, whose values drive dispatch and replay. + const messageColumns = this.getMessageColumnNames() + if (messageColumns.size > 0 && !messageColumns.has('swept_at')) { + this.db.exec('ALTER TABLE messages ADD COLUMN swept_at INTEGER') + } + // When the HUB received this message, as opposed to `created_at`, which + // is the agent runner's own clock preserved through transcript replay. + // This is what makes "did the operator's reply reach the agent after + // this footer arrived?" answerable: `invoked_at` is a hub stamp, so it + // belongs beside another hub stamp. Insertion `seq` cannot serve — + // allocation is MAX(seq)+1, so cancelling a queued row frees its number + // for reuse — and merge renumbering makes cross-session positions + // synthetic rather than real. A timestamp is durable under both. + if (messageColumns.size > 0 && !messageColumns.has('received_at')) { + this.db.exec('ALTER TABLE messages ADD COLUMN received_at INTEGER') + } + // Whether the delivery actually reached the agent. A locally handled + // slash command, a rejected or aborted prompt and a failed steer all + // get `invoked_at` stamped while the agent never saw them, so + // `invoked_at` alone wrongly reads as "the operator answered this". + // NULL means "written before this column existed" and keeps the old + // permissive reading, so an upgrade does not un-answer historical work. + if (messageColumns.size > 0 && !messageColumns.has('agent_delivered')) { + this.db.exec('ALTER TABLE messages ADD COLUMN agent_delivered INTEGER') + } + } + private getSessionColumnNames(): Set { const rows = this.db.prepare('PRAGMA table_info(sessions)').all() as Array<{ name: string }> return new Set(rows.map((row) => row.name)) @@ -1412,6 +1554,19 @@ export class Store { } } + /** + * v40→v41: per-device push event filter JSON on `fcm_devices`. Renumbered + * from its original v37→v38 slot, which collided with #1717's own + * v37→v38 blocker-footer migration above. + */ + private migrateFromV40ToV41(): void { + const cols = this.db.prepare('PRAGMA table_info(fcm_devices)').all() as Array<{ name: string }> + if (cols.length === 0) return + if (!cols.some((c) => c.name === 'preferences_json')) { + this.db.exec('ALTER TABLE fcm_devices ADD COLUMN preferences_json TEXT') + } + } + private ensureUsageScanParserVersion(): void { const columns = this.db.prepare('PRAGMA table_info(usage_scan_state)').all() as Array<{ name: string }> if (columns.length === 0) return diff --git a/hub/src/store/messageStore.ts b/hub/src/store/messageStore.ts index 319a626ca31..b9f8241bb99 100644 --- a/hub/src/store/messageStore.ts +++ b/hub/src/store/messageStore.ts @@ -33,6 +33,7 @@ import { minFutureScheduledAtBySessionIds, countMessages, markMessagesInvoked, + markMessagesSwept, markMessagesIndeterminate, markDispatchingMessagesIndeterminate, setMessagesDeliveryState, @@ -40,12 +41,15 @@ import { mergeSessionMessages, moveUninvokedScheduledMessages, moveUninvokedMessages, + type CopyStoredMessageInput, copyMessageToSession as copyStoredMessageToSession, copyMessagesToSession as copyStoredMessagesToSession, addMessageSweepingLiveSnapshots, deleteLiveTextSnapshots, getAllMessages, + getInvokedMessages, getMessagesAfterSeq, + getMessagesPage, getMaxSeq, getMinSeq, getMessageSeqById, @@ -78,8 +82,8 @@ export class MessageStore { return truncateOpenCodeRewind(this.db, sessionId, cutoffSeq, boundaryId) } - addMessage(sessionId: string, content: unknown, localId?: string, scheduledAt?: number | null, createdAt?: number): StoredMessage { - return addMessage(this.db, sessionId, content, localId, scheduledAt, createdAt) + addMessage(sessionId: string, content: unknown, localId?: string, scheduledAt?: number | null, createdAt?: number, receivedAt?: number): StoredMessage { + return addMessage(this.db, sessionId, content, localId, scheduledAt, createdAt, receivedAt) } addMessageSweepingLiveSnapshots( sessionId: string, @@ -119,7 +123,7 @@ export class MessageStore { copyMessageToSession( sessionId: string, - message: Pick + message: CopyStoredMessageInput ): StoredMessage { // 中文注释:重复会话合并时需要保留源消息的时间戳和排队信息,因此走专门的复制入口而不是普通 addMessage。 return copyStoredMessageToSession(this.db, sessionId, message) @@ -127,7 +131,7 @@ export class MessageStore { copyMessagesToSession( sessionId: string, - messages: Array> + messages: CopyStoredMessageInput[] ): number { return copyStoredMessagesToSession(this.db, sessionId, messages) } @@ -136,10 +140,18 @@ export class MessageStore { return getAllMessages(this.db, sessionId) } + getInvokedMessages(sessionId: string): StoredMessage[] { + return getInvokedMessages(this.db, sessionId) + } + getMessagesAfterSeq(sessionId: string, afterSeq: number): StoredMessage[] { return getMessagesAfterSeq(this.db, sessionId, afterSeq) } + getMessagesPage(sessionId: string, afterSeq: number, limit: number): StoredMessage[] { + return getMessagesPage(this.db, sessionId, afterSeq, limit) + } + getMaxSeq(sessionId: string): number { return getMaxSeq(this.db, sessionId) } @@ -291,8 +303,17 @@ export class MessageStore { return claimIndeterminateMessage(this.db, sessionId, messageId) } - markMessagesInvoked(sessionId: string, localIds: string[], invokedAt: number): number { - return markMessagesInvoked(this.db, sessionId, localIds, invokedAt) + markMessagesSwept(sessionId: string, localIds: string[], sweptAt: number): number { + return markMessagesSwept(this.db, sessionId, localIds, sweptAt) + } + + markMessagesInvoked( + sessionId: string, + localIds: string[], + invokedAt: number, + options?: { agentDelivered?: boolean } + ): number { + return markMessagesInvoked(this.db, sessionId, localIds, invokedAt, options) } markDispatchingMessagesIndeterminate(sessionId: string): string[] { diff --git a/hub/src/store/messages.copyBatch.test.ts b/hub/src/store/messages.copyBatch.test.ts index d2dddbd252d..10dec8e4ed1 100644 --- a/hub/src/store/messages.copyBatch.test.ts +++ b/hub/src/store/messages.copyBatch.test.ts @@ -30,4 +30,33 @@ describe('copyMessagesToSession', () => { expect(store.messages.getAllMessages(child.id)).toHaveLength(2) expect(store.messages.getMessageEpoch(child.id)).toBe(beforeEpoch + 1) }) + + it('carries receivedAt and agentDelivered through, not just createdAt (#1717 cold-review round 34)', () => { + // A batch copy (fork hydration) moves EXISTING history, so a + // footer's real hub arrival and delivery disposition belong to + // the original event, not to the moment it was copied — same + // reasoning `copyMessageToSession` (the single-row path) already + // applies. Dropping `receivedAt` here let a footer's position be + // judged on `createdAt` (the runner's own, possibly slow clock) + // instead, which could place a late-arriving footer "before" the + // prompt that actually preceded its real arrival. + const store = new Store(':memory:') + const child = store.sessions.getOrCreateSession('child-received-at', { path: '/tmp' }, null, 'default') + const base = Date.now() - 600_000 + + store.messages.copyMessagesToSession(child.id, [{ + content: { role: 'agent', content: { type: 'text', text: 'slow footer' } }, + createdAt: base, + localId: null, + invokedAt: null, + scheduledAt: null, + deliveryState: undefined, + receivedAt: base + 11_000, + agentDelivered: 1 + }]) + + const [copiedFooter] = store.messages.getAllMessages(child.id) + expect(copiedFooter?.receivedAt).toBe(base + 11_000) + expect(copiedFooter?.agentDelivered).toBe(1) + }) }) diff --git a/hub/src/store/messages.test.ts b/hub/src/store/messages.test.ts index 5473de17f78..0a443380729 100644 --- a/hub/src/store/messages.test.ts +++ b/hub/src/store/messages.test.ts @@ -308,6 +308,61 @@ describe('position pagination and structural epochs', () => { expect(store.messages.getMessageEpoch(target.id)).toBe(1) }) + it('marks a previously-queued collision row as not agent-delivered, but preserves an already-invoked one (#1717 cold-review round 36)', () => { + // Force-invoking a local_id collision's older copy is purely to + // unstick the floating bar — nothing was ever actually handed to + // the agent for a row that was still queued. Without + // agent_delivered = 0, the synthesized invoked_at still passes + // isDeliveredOperatorReply and can stand in for a reply nothing + // ever actually sent. An already-invoked row's real delivery + // state is genuine evidence and must survive untouched. + const store = makeStore() + const queuedSource = makeSession(store, 'collision-queued-source') + const queuedTarget = makeSession(store, 'collision-queued-target') + store.messages.addMessage(queuedSource.id, { text: 'queued' }, 'dup-queued') + store.messages.addMessage(queuedTarget.id, { text: 'queued' }, 'dup-queued') + + store.messages.mergeSessionMessages(queuedSource.id, queuedTarget.id) + const queuedRow = store.messages.getAllMessages(queuedTarget.id) + .find((message) => message.localId === null) + expect(queuedRow?.invokedAt).not.toBeNull() + expect(queuedRow?.agentDelivered).toBe(0) + + const invokedSource = makeSession(store, 'collision-invoked-source') + const invokedTarget = makeSession(store, 'collision-invoked-target') + store.messages.addMessage(invokedSource.id, { text: 'already invoked' }, 'dup-invoked') + store.messages.markMessagesInvoked(invokedSource.id, ['dup-invoked'], Date.now()) + store.messages.addMessage(invokedTarget.id, { text: 'already invoked' }, 'dup-invoked') + + store.messages.mergeSessionMessages(invokedSource.id, invokedTarget.id) + const invokedRow = store.messages.getAllMessages(invokedTarget.id) + .find((message) => message.localId === null) + expect(invokedRow?.agentDelivered).toBe(1) + }) + + it('getMessagesPage reads a bounded, ordered slice that chains to cover the whole transcript (#1717 cold-review round 36)', () => { + const store = makeStore() + const session = makeSession(store, 'paged-transcript') + for (let i = 0; i < 25; i++) { + store.messages.addMessage(session.id, { text: `m${i}` }, `paged-${i}`) + } + + const firstPage = store.messages.getMessagesPage(session.id, 0, 10) + expect(firstPage.map((m) => m.localId)).toEqual( + Array.from({ length: 10 }, (_, i) => `paged-${i}`) + ) + + const lastSeqInFirstPage = firstPage.at(-1)!.seq + const secondPage = store.messages.getMessagesPage(session.id, lastSeqInFirstPage, 10) + expect(secondPage.map((m) => m.localId)).toEqual( + Array.from({ length: 10 }, (_, i) => `paged-${i + 10}`) + ) + + const lastSeqInSecondPage = secondPage.at(-1)!.seq + const thirdPage = store.messages.getMessagesPage(session.id, lastSeqInSecondPage, 10) + expect(thirdPage.map((m) => m.localId)).toEqual(['paged-20', 'paged-21', 'paged-22', 'paged-23', 'paged-24']) + }) + it('clamps future client timestamps to hub receive time', () => { const store = makeStore() const session = makeSession(store, 'future-client-clock') diff --git a/hub/src/store/messages.ts b/hub/src/store/messages.ts index decdf7a227c..abe76102ce2 100644 --- a/hub/src/store/messages.ts +++ b/hub/src/store/messages.ts @@ -27,6 +27,9 @@ type DbMessageRow = { seq: number local_id: string | null invoked_at: number | null + swept_at?: number | null + received_at?: number | null + agent_delivered?: number | null scheduled_at: number | null delivery_state: string | null } @@ -80,15 +83,25 @@ export function addImportedMessage( const canonicalContent = truncateOversizedMessageContent(content) prepareCached(db, ` INSERT INTO messages ( - id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at + id, session_id, content, created_at, received_at, seq, local_id, invoked_at, scheduled_at ) VALUES ( - @id, @session_id, @content, @created_at, @seq, @local_id, @invoked_at, NULL + @id, @session_id, @content, @created_at, @received_at, @seq, @local_id, @invoked_at, NULL ) `).run({ id, session_id: sessionId, content: encodeMessageContent(canonicalContent), created_at: stampedAt, + // An IMPORTED row is stamped with the TRANSCRIPT's own time, not + // import time (#1717). Its `invoked_at` just below is historical + // too, so stamping arrival at `now` put the two halves of one row + // in different regimes: an imported footer then looked newer than + // the imported reply that answered it, and a rewind retaining that + // prefix reopened a blocker the transcript had already closed. + // Within one transcript everything shares a clock; against live + // rows both are real-world times and the historical gap dwarfs any + // skew between them. + received_at: stampedAt, seq: msgSeqRow.nextSeq, local_id: localId, invoked_at: stampedAt @@ -119,6 +132,9 @@ function toStoredMessage(row: DbMessageRow): StoredMessage { seq: row.seq, localId: row.local_id, invokedAt: row.invoked_at ?? null, + sweptAt: row.swept_at ?? null, + receivedAt: row.received_at ?? null, + agentDelivered: row.agent_delivered ?? null, scheduledAt: row.scheduled_at ?? null, ...(row.delivery_state && row.delivery_state !== 'queued' ? { deliveryState: 'indeterminate' as const } : {}), ...(row.delivery_state === 'dispatching' ? { deliveryPending: true as const } : {}) @@ -128,7 +144,7 @@ function toStoredMessage(row: DbMessageRow): StoredMessage { export type CopyStoredMessageInput = Pick< StoredMessage, 'content' | 'createdAt' | 'localId' | 'invokedAt' | 'scheduledAt' | 'deliveryState' -> +> & Partial> export function addMessage( db: Database, @@ -136,7 +152,8 @@ export function addMessage( content: unknown, localId?: string, scheduledAt?: number | null, - createdAt?: number + createdAt?: number, + receivedAt?: number ): StoredMessage { const now = Date.now() // Client-provided origin timestamp (e.g. a Claude transcript entry's own @@ -185,15 +202,20 @@ export function addMessage( const previousHead = getNewestMessagePosition(db, sessionId) prepareCached(db, ` INSERT INTO messages ( - id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at + id, session_id, content, created_at, received_at, seq, local_id, invoked_at, scheduled_at ) VALUES ( - @id, @session_id, @content, @created_at, @seq, @local_id, @invoked_at, @scheduled_at + @id, @session_id, @content, @created_at, @received_at, @seq, @local_id, @invoked_at, @scheduled_at ) `).run({ id, session_id: sessionId, content: encoded, created_at: stampedAt, + // Hub arrival, not the runner's clock: the key the delivery + // boundary is measured against (#1717). Defaults to now because + // this runs when the hub receives the message — including for a + // replayed transcript, whose `created_at` is deliberately older. + received_at: receivedAt ?? Date.now(), seq: msgSeq, local_id: localId ?? null, invoked_at: invokedAt, @@ -738,9 +760,11 @@ export function copyMessageToSession( const id = randomUUID() prepareCached(db, ` INSERT INTO messages ( - id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at, delivery_state + id, session_id, content, created_at, received_at, agent_delivered, + seq, local_id, invoked_at, scheduled_at, delivery_state ) VALUES ( - @id, @session_id, @content, @created_at, @seq, @local_id, @invoked_at, @scheduled_at, @delivery_state + @id, @session_id, @content, @created_at, @received_at, @agent_delivered, + @seq, @local_id, @invoked_at, @scheduled_at, @delivery_state ) `).run({ id, @@ -749,6 +773,14 @@ export function copyMessageToSession( // sessions, so no truncation here even for pre-codec oversized rows. content: encodeMessageContent(message.content), created_at: createdAt, + // Carried, not re-stamped (#1717). A copy moves existing history + // between sessions, so its hub arrival and its delivery + // disposition belong to the original event — re-stamping arrival + // at copy time made every copied row look like it reached the hub + // now, which put a copied footer after the copied reply that + // answered it. Falls back to `created_at` for pre-column history. + received_at: message.receivedAt ?? createdAt, + agent_delivered: message.agentDelivered ?? null, seq: nextSeq, local_id: localId ?? null, invoked_at: invokedAt ?? null, @@ -777,6 +809,7 @@ export function copyMessageToSession( return toStoredMessage(row) }) } + /** * Batch-hydrate a fork child: one transaction, contiguous seq allocation, * single epoch bump. Avoids O(n) max-seq lookups and epoch writes. @@ -792,9 +825,11 @@ export function copyMessagesToSession( let nextSeq = getMaxSeq(db, sessionId) + 1 const insert = prepareCached(db, ` INSERT INTO messages ( - id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at, delivery_state + id, session_id, content, created_at, received_at, agent_delivered, + seq, local_id, invoked_at, scheduled_at, delivery_state ) VALUES ( - @id, @session_id, @content, @created_at, @seq, @local_id, @invoked_at, @scheduled_at, @delivery_state + @id, @session_id, @content, @created_at, @received_at, @agent_delivered, + @seq, @local_id, @invoked_at, @scheduled_at, @delivery_state ) `) const collisionCheck = prepareCached(db, @@ -820,6 +855,13 @@ export function copyMessagesToSession( session_id: sessionId, content: encodeMessageContent(message.content), created_at: createdAt, + // Carried, not re-stamped — same reasoning as the single-row + // copy above: a batch copy (fork hydration) also moves + // EXISTING history, so its hub arrival and delivery + // disposition belong to the original event, not to the + // moment it was copied (#1717 cold-review round 34). + received_at: message.receivedAt ?? createdAt, + agent_delivered: message.agentDelivered ?? null, seq: nextSeq, local_id: localId ?? null, invoked_at: invokedAt ?? null, @@ -868,6 +910,28 @@ export function getAllMessages( return rows.map(toStoredMessage) } +/** + * Every message the agent was actually handed, oldest first (#1717). + * + * For "has anything answered this blocker?". A recency-bounded scan cannot + * answer that across a merge: `mergeSessionMessages` shifts the destination's + * seqs above every source row, so the newest-by-seq window can hold nothing but + * destination messages while the reply that answered the blocker sits below it. + * `invoked_at IS NOT NULL` is a necessary condition for a delivered reply, and + * delivered operator prompts are a small fraction of a transcript, so this is + * selective enough to take unbounded and exact rather than bounded and wrong. + */ +export function getInvokedMessages( + db: Database, + sessionId: string +): StoredMessage[] { + const rows = prepareCached(db, + 'SELECT * FROM messages WHERE session_id = ? AND invoked_at IS NOT NULL ORDER BY seq ASC' + ).all(sessionId) as DbMessageRow[] + + return rows.map(toStoredMessage) +} + export function getMessagesAfterSeq( db: Database, sessionId: string, @@ -880,6 +944,27 @@ export function getMessagesAfterSeq( return rows.map(toStoredMessage) } +/** + * One bounded page of a transcript, oldest-of-the-page first (#1717). + * + * For a caller reading an entire long transcript who wants to yield the + * event loop between chunks rather than decode everything in one + * synchronous pass — see `getMessagesAfterSeq` for the unbounded + * equivalent used where exactness within one call is required instead. + */ +export function getMessagesPage( + db: Database, + sessionId: string, + afterSeq: number, + limit: number +): StoredMessage[] { + const rows = prepareCached(db, + 'SELECT * FROM messages WHERE session_id = ? AND seq > ? ORDER BY seq ASC LIMIT ?' + ).all(sessionId, afterSeq, limit) as DbMessageRow[] + + return rows.map(toStoredMessage) +} + /** Current seq for a message that still lives on this session (merge-stable id). */ export function getMessageSeqById( db: Database, @@ -1594,22 +1679,45 @@ export function deleteQueuedMessageById( * First-write-wins: rows with a non-NULL invoked_at are not updated. A duplicate * ack (e.g. a CLI re-emit) would otherwise re-stamp the timestamp and shuffle * the message's position in the byPosition-ordered thread. */ +/** Mark rows invoked by the session-end sweep, not by a runtime ACK (#1717). */ +export function markMessagesSwept( + db: Database, + sessionId: string, + localIds: string[], + sweptAt: number +): number { + if (localIds.length === 0) return 0 + const placeholders = localIds.map(() => '?').join(', ') + return prepareCached(db, + `UPDATE messages SET swept_at = ? + WHERE session_id = ? AND local_id IN (${placeholders})` + ).run(sweptAt, sessionId, ...localIds).changes +} + export function markMessagesInvoked( db: Database, sessionId: string, localIds: string[], - invokedAt: number + invokedAt: number, + options?: { agentDelivered?: boolean } ): number { if (localIds.length === 0) return 0 return runInTransaction(db, () => { const placeholders = localIds.map(() => '?').join(', ') const changes = prepareCached(db, `UPDATE messages - SET invoked_at = ?, delivery_state = 'queued' + SET invoked_at = ?, + agent_delivered = ?, + delivery_state = 'queued' WHERE session_id = ? AND local_id IN (${placeholders}) AND invoked_at IS NULL` - ).run(invokedAt, sessionId, ...localIds).changes + ).run( + invokedAt, + options?.agentDelivered === false ? 0 : 1, + sessionId, + ...localIds + ).changes if (changes > 0) { const rows = prepareCached(db, ` SELECT id, session_id, content, created_at, seq, invoked_at @@ -1824,6 +1932,9 @@ export function mergeSessionMessages( db.exec('BEGIN') if (newMaxSeq > 0 && oldMaxSeq > 0) { + // Only `seq` moves. Nothing the notify ordering depends on is a + // position any more, precisely because this renumbering makes + // cross-session positions synthetic rather than real (#1717). prepareCached(db, 'UPDATE messages SET seq = seq + ? WHERE session_id = ?' ).run(oldMaxSeq, toSessionId) @@ -1844,9 +1955,19 @@ export function mergeSessionMessages( // (markMessagesInvoked matches by local_id), so leaving invoked_at // NULL would strand the row in the queued floating bar forever. // Use COALESCE so an already-invoked row keeps its server timestamp. + // + // A row synthesized this way was never actually handed to the + // agent — it is settled purely to unstick the floating bar, not + // because anything happened. Without agent_delivered = 0, it + // still passes isDeliveredOperatorReply and can stand in as the + // reply that answered a footer nothing ever actually answered + // (#1717 cold-review round 36). Only for rows that were still + // queued: an already-invoked row's recorded delivery state is + // real evidence and must not be overwritten. prepareCached(db, `UPDATE messages SET local_id = NULL, + agent_delivered = CASE WHEN invoked_at IS NULL THEN 0 ELSE agent_delivered END, invoked_at = COALESCE(invoked_at, created_at) WHERE session_id = ? AND local_id IN (${placeholders})` ).run(fromSessionId, ...localIds) diff --git a/hub/src/store/migration-v13.test.ts b/hub/src/store/migration-v13.test.ts index 91a549a4b6d..9351629d877 100644 --- a/hub/src/store/migration-v13.test.ts +++ b/hub/src/store/migration-v13.test.ts @@ -10,7 +10,7 @@ describe('Store V12/V13→V14 schema reconciliation', () => { const store = new Store(':memory:') expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(37) + expect(getUserVersion(store)).toBe(41) store.close() }) @@ -34,7 +34,7 @@ describe('Store V12/V13→V14 schema reconciliation', () => { store = new Store(dbPath) expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(37) + expect(getUserVersion(store)).toBe(41) expect(store.messages.getMessageEpoch('session-1')).toBe(0) expect(store.messages.getMessages('session-1')).toHaveLength(1) } finally { @@ -72,7 +72,7 @@ describe('Store V12/V13→V14 schema reconciliation', () => { store = new Store(dbPath) expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(37) + expect(getUserVersion(store)).toBe(41) expect(store.messages.getMessages('session-1')).toHaveLength(1) } finally { store?.close() diff --git a/hub/src/store/migration-v15.test.ts b/hub/src/store/migration-v15.test.ts index ee47cc1d00e..8213093570f 100644 --- a/hub/src/store/migration-v15.test.ts +++ b/hub/src/store/migration-v15.test.ts @@ -19,7 +19,7 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { expect(cols).toContain('attachments') expect(getColumns(store, 'usage_events')).toContain('last_input_tokens') expect(getColumns(store, 'usage_scan_state')).toContain('last_seq') - expect(getUserVersion(store)).toBe(37) + expect(getUserVersion(store)).toBe(41) store.close() }) @@ -40,7 +40,7 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { expect(cols).toContain('attachments') expect(getColumns(store, 'usage_events')).toContain('last_input_tokens') expect(getColumns(store, 'usage_scan_state')).toContain('last_seq') - expect(getUserVersion(store)).toBe(37) + expect(getUserVersion(store)).toBe(41) } finally { store?.close() rmSync(dir, { recursive: true, force: true }) @@ -60,7 +60,7 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { store2 = new Store(dbPath) const cols2 = getColumns(store2, 'session_scratchlist') expect(cols2).toEqual(cols1) - expect(getUserVersion(store2)).toBe(37) + expect(getUserVersion(store2)).toBe(41) } finally { store2?.close() store1?.close() diff --git a/hub/src/store/migration-v18.test.ts b/hub/src/store/migration-v18.test.ts index 88db7143e2c..03989fcf112 100644 --- a/hub/src/store/migration-v18.test.ts +++ b/hub/src/store/migration-v18.test.ts @@ -38,7 +38,7 @@ describe('Store V18->V19 migration: usage scan state', () => { const usageRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_events').get() as { count: number } expect(table?.name).toBe('usage_scan_state') - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) expect(usageRows.count).toBe(0) } finally { store?.close() diff --git a/hub/src/store/migration-v19.test.ts b/hub/src/store/migration-v19.test.ts index aeecabd1eb5..8055697c4b1 100644 --- a/hub/src/store/migration-v19.test.ts +++ b/hub/src/store/migration-v19.test.ts @@ -37,7 +37,7 @@ describe('Store V19->current migration: usage re-index', () => { const scanRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_scan_state').get() as { count: number } const usageRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_events').get() as { count: number } - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) expect(scanRows.count).toBe(0) expect(usageRows.count).toBe(0) } finally { diff --git a/hub/src/store/migration-v20.test.ts b/hub/src/store/migration-v20.test.ts index 9fdbc9a8e3b..d0de164e806 100644 --- a/hub/src/store/migration-v20.test.ts +++ b/hub/src/store/migration-v20.test.ts @@ -43,7 +43,7 @@ describe('Store V20->V21 migration: usage semantics re-index', () => { store = new Store(dbPath) const internalDb = (store as unknown as { db: Database }).db const count = (table: string): number => (internalDb.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get() as { count: number }).count - expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(37) + expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(41) expect(count('usage_events')).toBe(0) expect(count('usage_scan_state')).toBe(0) expect(store.messages.getMessages(session.id)).toHaveLength(1) diff --git a/hub/src/store/migration-v23.test.ts b/hub/src/store/migration-v23.test.ts index 8079da9ae44..cd109d7c24a 100644 --- a/hub/src/store/migration-v23.test.ts +++ b/hub/src/store/migration-v23.test.ts @@ -15,7 +15,7 @@ afterEach(() => { } }) -describe('schema migrations through v33', () => { +describe('schema migrations through v40', () => { it('adds events and event_links tables to a V22 database', () => { const dir = mkdtempSync(join(tmpdir(), 'hapi-migration-v23-')) tempDirs.push(dir) @@ -45,7 +45,7 @@ describe('schema migrations through v33', () => { expect(links?.name).toBe('event_links') const columns = internalDb.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }> expect(columns.map((column) => column.name)).toContain('delivery_state') - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) } finally { migrated.close() } @@ -78,7 +78,7 @@ describe('schema migrations through v33', () => { expect(migrated.messages.searchContent('backfill this', 'default')[0]?.sessionId).toBe(session.id) const internalDb = (migrated as unknown as { db: Database }).db const version = internalDb.prepare('PRAGMA user_version').get() as { user_version: number } - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) } finally { migrated.close() } @@ -114,7 +114,7 @@ describe('schema migrations through v33', () => { ).get() as { name: string } | null const version = internalDb.prepare('PRAGMA user_version').get() as { user_version: number } expect(lookup?.name).toBe('message_content_search_lookup') - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) } finally { migrated.close() } @@ -177,7 +177,7 @@ describe('schema migrations through v33', () => { expect(target?.target_message_id).toBe(message.id) expect(indexed?.searchable_text.length).toBeLessThanOrEqual(MAX_INDEXED_MESSAGE_CHARACTERS) expect(indexed?.searchable_text).toContain('tail-migration-needle') - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) } finally { migrated.close() } @@ -239,7 +239,7 @@ describe('schema migrations through v33', () => { expect(indexed?.searchable_text).toContain('v30-middle-needle') expect(metadata?.is_truncated).toBe(1) expect(metadata?.short_index_truncated).toBe(1) - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) } finally { migrated.close() } diff --git a/hub/src/store/migration-v24.test.ts b/hub/src/store/migration-v24.test.ts index 909f06a5f0f..0a561fc3664 100644 --- a/hub/src/store/migration-v24.test.ts +++ b/hub/src/store/migration-v24.test.ts @@ -13,7 +13,7 @@ afterEach(() => { } }) -describe('schema migrations through v33', () => { +describe('schema migrations through v40', () => { it('adds fcm_devices.push_key to a V23 database and keeps existing rows', () => { const dir = mkdtempSync(join(tmpdir(), 'hapi-migration-v24-')) tempDirs.push(dir) @@ -41,7 +41,7 @@ describe('schema migrations through v33', () => { expect(columns.some((col) => col.name === 'push_key')).toBe(true) const messageColumns = messageColumnsStatement.all() as Array<{ name: string }> expect(messageColumns.some((col) => col.name === 'delivery_state')).toBe(true) - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) // Existing Android rows survive with a NULL push key. const devices = migrated.fcm.getDevicesByNamespace('default') @@ -91,7 +91,7 @@ describe('schema migrations through v33', () => { const version = versionStatement.get() as { user_version: number } const indexes = indexesStatement.all() as Array<{ name: string }> expect(columns.some((col) => col.name === 'delivery_state')).toBe(true) - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) expect(indexes.map((index) => index.name)).toEqual(expect.arrayContaining([ 'idx_messages_immediate_queued', 'idx_messages_future_scheduled_queued' diff --git a/hub/src/store/migration-v25.test.ts b/hub/src/store/migration-v25.test.ts index 02e9c908749..52ae417cfe3 100644 --- a/hub/src/store/migration-v25.test.ts +++ b/hub/src/store/migration-v25.test.ts @@ -41,7 +41,7 @@ describe('schema migration v25 to v26', () => { ORDER BY seq ASC `).all('session-id') as Array<{ detail: string }> - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) expect(plan.some((row) => row.detail.includes('idx_messages_immediate_queued'))).toBe(true) migrated.close() }) diff --git a/hub/src/store/migration-v26-ladder.test.ts b/hub/src/store/migration-v26-ladder.test.ts new file mode 100644 index 00000000000..dcea5e2592d --- /dev/null +++ b/hub/src/store/migration-v26-ladder.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'bun:test' +import { Database } from 'bun:sqlite' +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Store } from './index' + +describe('v26 fast-path upgrade (#1717)', () => { + it('lands every later column, not just the ones listed by hand', () => { + // The v26 branch used to enumerate each later migration explicitly, so + // a step added to the ladder but not copied here was skipped while the + // row was still stamped at SCHEMA_VERSION. The database then claimed a + // version whose columns it did not have and the hub failed to start. + const dir = mkdtempSync(join(tmpdir(), 'hapi-v26-')) + const path = join(dir, 'hub.db') + new Store(path).close() + + const legacy = new Database(path) + // Genuinely remove the post-v26 columns, otherwise `createSchema` has + // already added them and the test cannot see a skipped migration. + for (const column of [ + 'last_notify_status', 'last_notify_at', 'last_notify_note', + 'last_notify_cleared_at', 'last_notify_updated_at', + 'blocked_ack_at', 'blocked_ack_reason', 'blocked_ack_key' + ]) { + try { legacy.exec(`ALTER TABLE sessions DROP COLUMN ${column};`) } catch { /* absent */ } + } + legacy.exec('PRAGMA user_version = 26;') + legacy.close() + + const migrated = new Store(path) + try { + const db = (migrated as unknown as { db: Database }).db + const columns = new Set( + (db.prepare('PRAGMA table_info(sessions)').all() as Array<{ name: string }>) + .map((row) => row.name) + ) + for (const column of [ + 'last_notify_status', 'last_notify_at', 'last_notify_note', + 'last_notify_cleared_at', 'last_notify_updated_at', + 'blocked_ack_at', 'blocked_ack_reason', 'blocked_ack_key' + ]) { + expect(columns.has(column)).toBe(true) + } + // And a session actually loads, which is what the hub does at boot. + expect(() => migrated.sessions.getSessions()).not.toThrow() + } finally { + migrated.close() + } + }) +}) diff --git a/hub/src/store/migration-v26.test.ts b/hub/src/store/migration-v26.test.ts index ed60b8bd50d..1f1e1b640d7 100644 --- a/hub/src/store/migration-v26.test.ts +++ b/hub/src/store/migration-v26.test.ts @@ -59,7 +59,7 @@ describe('schema migration v26 to v27', () => { const minPlan = minPlanStatement.all('a', 'b', 123) as Array<{ detail: string }> minPlanStatement.finalize() - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) expect(countPlan.some((row) => row.detail.includes('idx_messages_future_scheduled_queued'))).toBe(true) expect(minPlan.some((row) => row.detail.includes('idx_messages_future_scheduled_queued'))).toBe(true) migrated.close() diff --git a/hub/src/store/migration-v28.test.ts b/hub/src/store/migration-v28.test.ts index 75241c4ba08..21343b52547 100644 --- a/hub/src/store/migration-v28.test.ts +++ b/hub/src/store/migration-v28.test.ts @@ -32,7 +32,7 @@ describe('schema migration v27 to v28', () => { const migrated = new Store(dbPath) const internalDb = (migrated as unknown as { db: Database }).db const version = internalDb.prepare('PRAGMA user_version').get() as { user_version: number } - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) expect(migrated.turns.open(session.id, 'default', 1_000, 'agent')).toBe(true) expect(migrated.turns.open(session.id, 'default', 2_000, 'agent')).toBe(false) diff --git a/hub/src/store/migration-v30.test.ts b/hub/src/store/migration-v30.test.ts index 2e35d9368f7..4226691268a 100644 --- a/hub/src/store/migration-v30.test.ts +++ b/hub/src/store/migration-v30.test.ts @@ -52,7 +52,7 @@ it('creates and backfills search tables when upgrading a base v30 database', () try { const internalDb = (migrated as unknown as { db: Database }).db const version = internalDb.prepare('PRAGMA user_version').get() as { user_version: number } - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) expect(migrated.messages.searchContent('searchable', 'default')[0]?.sessionId).toBe(session.id) } finally { migrated.close() } } finally { Bun.gc(true); rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }) } @@ -84,7 +84,7 @@ it('upgrades a genuine v26 schema without read-state or search table shortcuts', try { const internalDb = (migrated as unknown as { db: Database }).db const version = internalDb.prepare('PRAGMA user_version').get() as { user_version: number } - expect(version.user_version).toBe(37) + expect(version.user_version).toBe(41) expect(migrated.sessions.getSession(session.id)?.readState).toEqual({ readRevision: 0, manualUnread: false, version: 0 }) migrated.messages.addMessage(session.id, { role: 'user', content: { type: 'text', text: 'genuine v26 searchable text' } diff --git a/hub/src/store/migration-v36.test.ts b/hub/src/store/migration-v36.test.ts index 481ba894250..e9541aa7fb8 100644 --- a/hub/src/store/migration-v36.test.ts +++ b/hub/src/store/migration-v36.test.ts @@ -18,11 +18,11 @@ it('adds passkey_credentials when upgrading a v35 database', () => { const migrated = new Store(path) try { expect(log.mock.calls).toEqual([ - ['[Store] Migrating database schema from v35 to v37...'], - ['[Store] Database schema migration complete (v35 to v37).'] + ['[Store] Migrating database schema from v35 to v41...'], + ['[Store] Database schema migration complete (v35 to v41).'] ]) const internalDb = (migrated as unknown as { db: Database }).db - expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(37) + expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(41) migrated.passkeys.add({ id: 'cred', namespace: 'default', rpId: 'localhost', publicKey: new Uint8Array([1, 2, 3]), counter: 0, transports: ['internal'], tokenFingerprint: 'fp', name: null, createdAt: 1 diff --git a/hub/src/store/migration-v37.test.ts b/hub/src/store/migration-v37.test.ts index d998aab369a..27fc3c02230 100644 --- a/hub/src/store/migration-v37.test.ts +++ b/hub/src/store/migration-v37.test.ts @@ -31,11 +31,11 @@ it('backfills null session_job run_id when upgrading a v36 database', () => { const migrated = new Store(path) try { expect(log.mock.calls).toEqual([ - ['[Store] Migrating database schema from v36 to v37...'], - ['[Store] Database schema migration complete (v36 to v37).'] + ['[Store] Migrating database schema from v36 to v41...'], + ['[Store] Database schema migration complete (v36 to v41).'] ]) const internalDb = (migrated as unknown as { db: Database }).db - expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(37) + expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(41) const job = migrated.sessionJobs.get(id, 'stale') expect(job?.runId).toMatch( /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i diff --git a/hub/src/store/migration-v41.test.ts b/hub/src/store/migration-v41.test.ts new file mode 100644 index 00000000000..79fab647fb9 --- /dev/null +++ b/hub/src/store/migration-v41.test.ts @@ -0,0 +1,67 @@ +import { expect, it, spyOn } from 'bun:test' +import { Database } from 'bun:sqlite' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Store } from '.' + +it('adds preferences_json to fcm_devices when upgrading a v40 database', () => { + const dir = mkdtempSync(join(tmpdir(), 'hapi-push-prefs-v41-migration-')) + const log = spyOn(console, 'log').mockImplementation(() => {}) + try { + const path = join(dir, 'hub.db') + const seed = new Store(path) + const pushKey = Buffer.alloc(32, 7).toString('base64') + seed.fcm.upsertDevice('default', { + token: 'apns-existing', + platform: 'ios', + deviceId: 'iphone-existing', + pushKey + }) + seed.close() + expect(log).not.toHaveBeenCalled() + + const legacy = new Database(path) + legacy.exec('ALTER TABLE fcm_devices DROP COLUMN preferences_json; PRAGMA user_version = 40;') + legacy.close() + + const migrated = new Store(path) + try { + expect(log.mock.calls).toEqual([ + ['[Store] Migrating database schema from v40 to v41...'], + ['[Store] Database schema migration complete (v40 to v41).'] + ]) + const internalDb = (migrated as unknown as { db: Database }).db + expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(41) + + const devices = migrated.fcm.getDevicesByNamespace('default', ['ios']) + expect(devices).toHaveLength(1) + expect(devices[0]).toMatchObject({ + token: 'apns-existing', + deviceId: 'iphone-existing', + pushKey, + preferences: null + }) + + migrated.fcm.upsertDevice('default', { + token: 'apns-existing', + platform: 'ios', + deviceId: 'iphone-existing', + pushKey, + preferences: { ready: false, modelError: true } + }) + expect(migrated.fcm.getDevicesByNamespace('default', ['ios'])[0].preferences).toEqual({ + ready: false, + permissionRequest: true, + inputRequest: true, + modelError: true + }) + } finally { + migrated.close() + } + } finally { + log.mockRestore() + Bun.gc(true) + rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }) + } +}) diff --git a/hub/src/store/sessionStore.ts b/hub/src/store/sessionStore.ts index caf6233c0e4..2ee19cefd37 100644 --- a/hub/src/store/sessionStore.ts +++ b/hub/src/store/sessionStore.ts @@ -4,6 +4,8 @@ import { updateSessionReadState } from './sessionReadState' import type { StoredSession, VersionedUpdateResult } from './types' import { + clearSessionBlockedAck, + clearSessionLastNotify, deleteSession, getOrCreateSession, adoptPreallocatedSession, @@ -19,12 +21,15 @@ import { setSessionPinned, setSessionPinMode, type SessionPinMode, + setSessionBlockedAck, + setSessionLastNotify, setSessionTeamState, setSessionTodos, replaceSessionTodos, touchSessionUpdatedAt, updateSessionAgentState, - updateSessionMetadata + updateSessionMetadata, + replaceSessionNotifyAfterTruncate } from './sessions' export class SessionStore { @@ -104,6 +109,44 @@ export class SessionStore { return replaceSessionTodos(this.db, id, todos, namespace) } + setSessionLastNotify( + id: string, + signal: { status: string; at: number; note: string | null; receivedAt?: number | null }, + namespace: string + ): boolean { + return setSessionLastNotify(this.db, id, signal, namespace) + } + + setSessionBlockedAck( + id: string, + ack: { at: number; reason: string; keys?: string[] | null; livePendingKeys?: ReadonlySet }, + namespace: string + ): boolean { + return setSessionBlockedAck(this.db, id, ack, namespace) + } + + clearSessionBlockedAck(id: string, namespace: string, at?: number): boolean { + return clearSessionBlockedAck(this.db, id, namespace, at) + } + + clearSessionLastNotify( + id: string, + namespace: string, + clearedAt: number = Date.now() + ): boolean { + return clearSessionLastNotify(this.db, id, namespace, clearedAt) + } + + replaceNotifyAfterTruncate( + id: string, + namespace: string, + signal: { status: string; at: number; note: string | null; receivedAt?: number | null } | null, + clearedAt: number = Date.now(), + clearedAuthorAt: number | null = null + ): boolean { + return replaceSessionNotifyAfterTruncate(this.db, id, namespace, signal, clearedAt, clearedAuthorAt) + } + setSessionTeamState(id: string, teamState: unknown, updatedAt: number, namespace: string): boolean { return setSessionTeamState(this.db, id, teamState, updatedAt, namespace) } diff --git a/hub/src/store/sessions.test.ts b/hub/src/store/sessions.test.ts index 4790ebbeb57..473f8822cb7 100644 --- a/hub/src/store/sessions.test.ts +++ b/hub/src/store/sessions.test.ts @@ -1748,6 +1748,343 @@ describe('updateSessionAgentState: updated_at (#1855)', () => { }) }) +describe('setSessionLastNotify / clearSessionLastNotify (#1717)', () => { + function seed(store: Store) { + return store.sessions.getOrCreateSession( + `notify-${randomUUID()}`, + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + } + + it('persists the footer and reads it back', () => { + const store = makeStore() + const session = seed(store) + + expect(store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: 2000, note: 'needs creds' }, + 'default' + )).toBe(true) + + const row = store.sessions.getSession(session.id) + expect(row?.lastNotifyStatus).toBe('blocked') + expect(row?.lastNotifyAt).toBe(2000) + expect(row?.lastNotifyNote).toBe('needs creds') + }) + + it('does not let a replayed older message resurrect a superseded status', () => { + const store = makeStore() + const session = seed(store) + store.sessions.setSessionLastNotify(session.id, { status: 'done', at: 3000, note: null }, 'default') + + expect(store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: 1000, note: 'stale' }, + 'default' + )).toBe(false) + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBe('done') + }) + + it('leaves updated_at alone so stamping never re-sorts the session list', () => { + const store = makeStore() + const session = seed(store) + const before = store.sessions.getSession(session.id)?.updatedAt + + store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: Date.now() + 60_000, note: null }, + 'default' + ) + + expect(store.sessions.getSession(session.id)?.updatedAt).toBe(before!) + }) + + it('clears on a new turn, and still advances the boundary with nothing stored', () => { + const store = makeStore() + const session = seed(store) + + // Previously a no-op. It must not be: a turn can start BEFORE the + // previous footer reaches the hub, and if that start writes nothing + // the delayed footer slips past the boundary later and revives an + // answered blocker. The write moves the watermark even with no footer. + expect(store.sessions.clearSessionLastNotify(session.id, 'default', 1000)).toBe(true) + expect(store.sessions.getSession(session.id)?.lastNotifyClearedAt).toBe(1000) + + // Genuinely idempotent once the boundary is already at or past it. + expect(store.sessions.clearSessionLastNotify(session.id, 'default', 500)).toBe(false) + + store.sessions.setSessionLastNotify(session.id, { status: 'blocked', at: 2000, note: 'x' }, 'default') + expect(store.sessions.clearSessionLastNotify(session.id, 'default', 3000)).toBe(true) + + const row = store.sessions.getSession(session.id) + expect(row?.lastNotifyStatus).toBeNull() + expect(row?.lastNotifyAt).toBeNull() + expect(row?.lastNotifyNote).toBeNull() + expect(row?.lastNotifyClearedAt).toBe(3000) + }) + + it('rejects a footer stamped before the clear boundary', () => { + const store = makeStore() + const session = seed(store) + + store.sessions.clearSessionLastNotify(session.id, 'default', 5000) + // Delayed Claude replay carrying its original pre-reply timestamp. + store.sessions.setSessionLastNotify(session.id, { status: 'blocked', at: 4000, note: 'stale' }, 'default') + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBeNull() + + store.sessions.setSessionLastNotify(session.id, { status: 'blocked', at: 6000, note: 'fresh' }, 'default') + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBe('blocked') + }) + + it('measures the delivery boundary against hub ARRIVAL, not the runner clock', () => { + const store = makeStore() + const session = seed(store) + + // A footer's own timestamp comes off the agent runner (the transcript + // preserves it verbatim); the boundary is stamped when the hub delivers + // the reply. Comparing those two is never sound in either direction. + // The footer's hub ARRIVAL is, because it is the same clock. + const HUB_NOW = 1_700_000_000_000 + store.sessions.clearSessionLastNotify(session.id, 'default', HUB_NOW) + + // Runner clock an hour FAST, so a superseded footer from before the + // reply looks like the future. Its arrival is what decides, and it + // arrived before the delivery. + store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: HUB_NOW + 3_600_000, note: 'superseded', receivedAt: HUB_NOW - 5_000 }, + 'default' + ) + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBeNull() + + // Runner clock an hour SLOW, so a genuinely new blocker reported after + // the reply looks older than the boundary. It arrived after the + // delivery, so the operator still learns the agent is stuck. + store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: HUB_NOW - 3_600_000, note: 'live', receivedAt: HUB_NOW + 5_000 }, + 'default' + ) + const row = store.sessions.getSession(session.id) + expect(row?.lastNotifyStatus).toBe('blocked') + expect(row?.lastNotifyNote).toBe('live') + expect(row?.lastNotifyReceivedAt).toBe(HUB_NOW + 5_000) + }) + + it('rejects delayed output from the turn the delivery already answered', () => { + const store = makeStore() + const session = seed(store) + + // The agent reported blocked, and the operator answered. + store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: 5_000, note: 'needs a key', receivedAt: 100_000 }, + 'default' + ) + store.sessions.clearSessionLastNotify(session.id, 'default', 110_000) + // The clear captures what it superseded, so a late arrival from that + // same turn is still measurable once `last_notify_at` is null. + expect(store.sessions.getSession(session.id)?.lastNotifyClearedAuthorAt).toBe(5_000) + + // A second footer from BEFORE the reply, reaching the hub for the first + // time afterwards. Its arrival is genuinely later than the delivery, so + // only its author time can reveal that the reply already answered it. + expect(store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: 4_000, note: 'stale sibling', receivedAt: 120_000 }, + 'default' + )).toBe(false) + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBeNull() + + // A genuinely new report from after the answered turn still lands. + expect(store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: 6_000, note: 'stuck again', receivedAt: 130_000 }, + 'default' + )).toBe(true) + expect(store.sessions.getSession(session.id)?.lastNotifyNote).toBe('stuck again') + }) + + it('a rewind scopes both boundaries to the surviving transcript', () => { + const store = makeStore() + const session = seed(store) + + store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: 5_000, note: 'old', receivedAt: 100_000 }, + 'default' + ) + store.sessions.clearSessionLastNotify(session.id, 'default', 110_000) + expect(store.sessions.getSession(session.id)?.lastNotifyClearedAuthorAt).toBe(5_000) + + // The rewind deletes the history both boundaries describe. + expect(store.sessions.replaceNotifyAfterTruncate( + session.id, + 'default', + null, + 0 + )).toBe(true) + const cleared = store.sessions.getSession(session.id) + expect(cleared?.lastNotifyClearedAuthorAt).toBeNull() + expect(cleared?.lastNotifyClearedAt).toBe(0) + + // Carried forward, the author boundary of 5000 would have suppressed + // every footer the retained transcript is entitled to report — and the + // clear's MAX meant nothing could ever lower it again. + expect(store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: 4_500, note: 'stuck again', receivedAt: 200_000 }, + 'default' + )).toBe(true) + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBe('blocked') + }) + + it('is namespace scoped', () => { + const store = makeStore() + const session = seed(store) + expect(store.sessions.setSessionLastNotify( + session.id, + { status: 'blocked', at: 2000, note: null }, + 'other' + )).toBe(false) + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBeNull() + }) +}) + +describe('setSessionBlockedAck (#1717 manual unblock)', () => { + function seed(store: Store) { + return store.sessions.getOrCreateSession( + `ack-${randomUUID()}`, + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + } + + it('persists the watermark and the rationale', () => { + const store = makeStore() + const session = seed(store) + + expect(store.sessions.setSessionBlockedAck( + session.id, + { at: 5000, reason: 'handled outside HAPI' }, + 'default' + )).toBe(true) + + const row = store.sessions.getSession(session.id) + expect(row?.blockedAckAt).toBe(5000) + expect(row?.blockedAckReason).toBe('handled outside HAPI') + }) + + it('does not let a replayed older ack un-dismiss a newer one', () => { + const store = makeStore() + const session = seed(store) + store.sessions.setSessionBlockedAck( + session.id, { at: 9000, reason: 'newer', keys: ['notify:9000'] }, 'default' + ) + + // The write is now accepted — with identities, an older acknowledgement + // is legitimate (dismissing an older prompt after a newer one), and + // rejecting it turned that into a 500. What must NOT move backwards is + // the watermark and the reason that describes the newest dismissal. + store.sessions.setSessionBlockedAck( + session.id, { at: 1000, reason: 'older replay', keys: ['notify:9000'] }, 'default' + ) + const row = store.sessions.getSession(session.id) + expect(row?.blockedAckAt).toBe(9000) + expect(row?.blockedAckReason).toBe('newer') + }) + + it('retains dismissals for several prompts, in any order', () => { + const store = makeStore() + const session = seed(store) + + store.sessions.setSessionBlockedAck( + session.id, { at: 9000, reason: 'newer question', keys: ['request:q1'] }, 'default' + ) + // Dismissing the OLDER permission afterwards used to be rejected by the + // monotonic guard, which the route surfaced as a 500. + store.sessions.setSessionBlockedAck( + session.id, + { at: 5000, reason: 'older permission', keys: ['request:q1', 'request:p1'] }, + 'default' + ) + + expect(store.sessions.getSession(session.id)?.blockedAckKeys) + .toEqual(['request:q1', 'request:p1']) + }) + + it('leaves updated_at alone — dismissing chrome is not conversation', () => { + const store = makeStore() + const session = seed(store) + const before = store.sessions.getSession(session.id)?.updatedAt + + store.sessions.setSessionBlockedAck( + session.id, + { at: Date.now() + 60_000, reason: 'x' }, + 'default' + ) + + expect(store.sessions.getSession(session.id)?.updatedAt).toBe(before!) + }) + + it('is namespace scoped', () => { + const store = makeStore() + const session = seed(store) + expect(store.sessions.setSessionBlockedAck( + session.id, + { at: 5000, reason: 'x' }, + 'other' + )).toBe(false) + expect(store.sessions.getSession(session.id)?.blockedAckAt).toBeNull() + }) +}) + +describe('clearSessionBlockedAck (#1717 cold-review round 36)', () => { + function seed(store: Store) { + return store.sessions.getOrCreateSession( + `ack-clear-${randomUUID()}`, + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + } + + it('nulls the timestamp, reason, and keys entirely — not just the keys', () => { + // `serialiseAckKeys([]) === null`, same wire value as "never + // dismissed," but `blocked_ack_at` only ever grows via MAX — a + // caller that writes an empty key set through `setSessionBlockedAck` + // leaves a stale timestamp behind that the web's watermark fallback + // (for rows written before keys existed) would still read as an + // acknowledgement of whatever shares that author time. + const store = makeStore() + const session = seed(store) + store.sessions.setSessionBlockedAck( + session.id, { at: 9000, reason: 'handled', keys: ['notify:9000'] }, 'default' + ) + + expect(store.sessions.clearSessionBlockedAck(session.id, 'default')).toBe(true) + + const row = store.sessions.getSession(session.id) + expect(row?.blockedAckAt).toBeNull() + expect(row?.blockedAckReason).toBeNull() + expect(row?.blockedAckKeys).toBeNull() + }) + + it('is namespace-scoped like the sibling setter', () => { + const store = makeStore() + const session = seed(store) + store.sessions.setSessionBlockedAck( + session.id, { at: 9000, reason: 'handled', keys: ['notify:9000'] }, 'default' + ) + + expect(store.sessions.clearSessionBlockedAck(session.id, 'other')).toBe(false) + expect(store.sessions.getSession(session.id)?.blockedAckAt).toBe(9000) + }) +}) + describe('DSH metadata carry-forward', () => { it('keeps the resume token but drops the per-launch confirmation', () => { const prior = { diff --git a/hub/src/store/sessions.ts b/hub/src/store/sessions.ts index 0a4f08edee7..fbc7439bf25 100644 --- a/hub/src/store/sessions.ts +++ b/hub/src/store/sessions.ts @@ -8,6 +8,7 @@ import type { StoredSession, VersionedUpdateResult } from './types' import { safeJsonParse } from './json' import { updateVersionedField } from './versionedUpdates' import { removeMessageContentSearchForSession } from './messageContentSearch' +import { SUPPORTED_LIVE_DISMISSAL_CAP } from '@hapi/protocol' function runInTransaction(db: Database, operation: () => T): T { return db.inTransaction ? operation() : db.transaction(operation)() @@ -286,6 +287,16 @@ type DbSessionRow = { todos_updated_at: number | null team_state: string | null team_state_updated_at: number | null + last_notify_status: string | null + last_notify_at: number | null + last_notify_note: string | null + blocked_ack_at: number | null + blocked_ack_reason: string | null + blocked_ack_key: string | null + last_notify_cleared_at: number | null + last_notify_received_at: number | null + last_notify_cleared_author_at: number | null + last_notify_updated_at: number | null active: number active_at: number | null seq: number @@ -316,6 +327,16 @@ function toStoredSession(row: DbSessionRow): StoredSession { todosUpdatedAt: row.todos_updated_at, teamState: safeJsonParse(row.team_state), teamStateUpdatedAt: row.team_state_updated_at, + lastNotifyStatus: row.last_notify_status, + lastNotifyAt: row.last_notify_at, + lastNotifyNote: row.last_notify_note, + blockedAckAt: row.blocked_ack_at, + blockedAckReason: row.blocked_ack_reason, + blockedAckKeys: parseAckKeys(row.blocked_ack_key), + lastNotifyClearedAt: row.last_notify_cleared_at, + lastNotifyReceivedAt: row.last_notify_received_at, + lastNotifyClearedAuthorAt: row.last_notify_cleared_author_at, + lastNotifyUpdatedAt: row.last_notify_updated_at, active: row.active === 1, activeAt: row.active_at, seq: row.seq @@ -696,6 +717,201 @@ function hasNewAgentStateRequest(prior: unknown, next: unknown): boolean { return Object.keys(nextRequests).some((requestId) => !Object.hasOwn(priorRequests, requestId)) } +/** + * Persist the last `AGENT_NOTIFY_SUMMARY` footer for a session (#1717). + * + * Monotonic on `last_notify_at` so a replayed or out-of-order older message + * cannot resurrect a stale `blocked` over a newer `done`. + * + * Deliberately does NOT touch `updated_at`: the message that carried the + * footer already advanced the session clock, and moving it again here would + * re-sort the session list and re-trigger the unread watermark for a write + * that carries no new conversation. + */ +export function setSessionLastNotify( + db: Database, + id: string, + signal: { status: string; at: number; note: string | null; receivedAt?: number | null }, + namespace: string +): boolean { + try { + const result = db.prepare(` + UPDATE sessions + SET last_notify_status = @status, + last_notify_at = @at, + last_notify_note = @note, + last_notify_received_at = @receivedAt, + last_notify_updated_at = MAX(COALESCE(last_notify_updated_at, 0) + 1, @rev), + seq = seq + 1 + WHERE id = @id + AND namespace = @namespace + -- Footer vs footer: both were stamped by the same agent runner + -- inside one transcript, so authorship time IS the authoritative + -- order between them. Insertion seq is not: it is allocated as + -- MAX(seq)+1, so a replayed older footer arriving after a newer + -- one carries a HIGHER seq while being older in fact. + AND (last_notify_at IS NULL OR last_notify_at <= @at) + -- Footer arrival vs the operator's delivery: BOTH hub stamps, so + -- this is a single-clock comparison. The footer's own at cannot + -- be used here (runner clock), and a position cannot either — + -- cancelling a queued row frees its seq for reuse, and a merge + -- renumbers positions into something synthetic. + AND (@receivedAt IS NULL OR last_notify_cleared_at IS NULL + OR last_notify_cleared_at <= @receivedAt) + -- Callers with no arrival stamp (older paths, and the ack/merge + -- transfers) keep the original author-time comparison. It is a + -- cross-domain guess, which is why every live path now supplies + -- an arrival, but dropping it entirely would let those paths + -- bypass the boundary altogether. + AND (@receivedAt IS NOT NULL OR last_notify_cleared_at IS NULL + OR last_notify_cleared_at <= @at) + -- Delayed output from the turn the delivery already answered. + -- The clear nulls last_notify_at, so a footer authored BEFORE + -- the reply but arriving after it for the first time otherwise + -- has nothing to be measured against: its arrival is genuinely + -- later, and it would walk straight back in. This keeps the + -- superseded footer's author time, which is the same runner clock + -- the newcomer carries. + AND (last_notify_cleared_author_at IS NULL + OR @at > last_notify_cleared_author_at) + `).run({ + id, + status: signal.status, + at: signal.at, + note: signal.note, + receivedAt: signal.receivedAt ?? null, + namespace, rev: Date.now() }) + return result.changes === 1 + } catch { + return false + } +} + +/** + * Record the operator's manual "this is not blocked" acknowledgement (#1717). + * + * Monotonic on `blocked_ack_at`: a replayed older ack must not un-dismiss a + * newer one. Leaves `updated_at` alone for the same reason the notify writes + * do — dismissing chrome is not conversation and must not re-sort the list. + */ +export function setSessionBlockedAck( + db: Database, + id: string, + ack: { at: number; reason: string; keys?: string[] | null; livePendingKeys?: ReadonlySet }, + namespace: string +): boolean { + try { + const result = db.prepare(` + UPDATE sessions + SET blocked_ack_at = MAX(COALESCE(blocked_ack_at, 0), @at), + -- Reason follows the newest acknowledgement; a replayed older + -- one must not overwrite it. The KEYS still merge below, so + -- dismissing an older prompt is accepted on its own terms. + blocked_ack_reason = CASE + WHEN blocked_ack_at IS NULL OR @at >= blocked_ack_at THEN @reason + ELSE blocked_ack_reason + END, + blocked_ack_key = @keys, + last_notify_updated_at = MAX(COALESCE(last_notify_updated_at, 0) + 1, @at), + seq = seq + 1 + WHERE id = @id + AND namespace = @namespace + -- No monotonic guard on @at. With identities the acknowledgement + -- is a SET, so dismissing an OLDER prompt after a newer one is + -- legitimate — the guard rejected it and the route turned that + -- into a 500. Ordering is carried by the keys, not the clock. + `).run({ id, at: ack.at, reason: ack.reason, keys: serialiseAckKeys(ack.keys, ack.livePendingKeys), namespace }) + return result.changes === 1 + } catch { + return false + } +} + +/** + * Drop a dismissal entirely rather than writing an empty key set (#1717 + * cold-review round 36). + * + * `serialiseAckKeys([]) === null`, same wire value as "never dismissed" — + * so stripping a session's LAST live key through `setSessionBlockedAck` + * leaves `blocked_ack_key` null while `blocked_ack_at` survives untouched + * (it only ever grows via `MAX`). A row with keys but a surviving + * timestamp is exactly what `isAcknowledgedBlocker`'s own watermark + * fallback exists for — rows written before keys existed — so that + * stale timestamp still silently re-covers a DIFFERENT, genuinely + * unresolved footer sharing the same `at`. Clearing the timestamp too + * is what tells the fallback there is nothing here to fall back to. + */ +export function clearSessionBlockedAck( + db: Database, + id: string, + namespace: string, + at: number = Date.now() +): boolean { + try { + const result = db.prepare(` + UPDATE sessions + SET blocked_ack_at = NULL, + blocked_ack_reason = NULL, + blocked_ack_key = NULL, + last_notify_updated_at = MAX(COALESCE(last_notify_updated_at, 0) + 1, @at), + seq = seq + 1 + WHERE id = @id AND namespace = @namespace + `).run({ id, namespace, at }) + return result.changes === 1 + } catch { + return false + } +} + +/** + * Drop the stored notify footer — the agent started a new turn, so its last + * self-report no longer describes the present. No-op (returns false) when + * nothing was stored, so callers can guard cheap. + */ +export function clearSessionLastNotify( + db: Database, + id: string, + namespace: string, + clearedAt: number = Date.now() +): boolean { + try { + const result = db.prepare(` + UPDATE sessions + SET last_notify_status = NULL, + last_notify_at = NULL, + last_notify_note = NULL, + last_notify_cleared_at = MAX(COALESCE(last_notify_cleared_at, 0), @clearedAt), + -- Capture the author time of the footer being cleared, in the + -- same move that nulls it. Delayed output from that turn is + -- then still rejectable even though nothing is stored any more. + -- + -- Untouched when there is no footer to capture: a 0 sentinel + -- here would suppress every footer with a non-positive + -- timestamp, which is exactly the kind of silent suppression + -- this feature must not do. + last_notify_cleared_author_at = CASE + WHEN last_notify_at IS NULL THEN last_notify_cleared_author_at + WHEN last_notify_cleared_author_at IS NULL THEN last_notify_at + ELSE MAX(last_notify_cleared_author_at, last_notify_at) + END, + last_notify_updated_at = MAX(COALESCE(last_notify_updated_at, 0) + 1, @clearedAt), + seq = seq + 1 + WHERE id = @id + AND namespace = @namespace + -- No last_notify_status IS NOT NULL guard: the clear boundary + -- has to advance on a qualifying turn start even when no footer + -- is stored yet, or a footer still in flight at turn start slips + -- past it later. Still a no-op write when neither would move. + AND (last_notify_status IS NOT NULL + OR last_notify_cleared_at IS NULL + OR last_notify_cleared_at < @clearedAt) + `).run({ id, namespace, clearedAt }) + return result.changes === 1 + } catch { + return false + } +} + export function setSessionTodos( db: Database, id: string, @@ -1067,3 +1283,131 @@ export function deleteSession(db: Database, id: string, namespace: string): bool return result.changes > 0 }) } + +/** + * Replace the notify signal and its clear boundary in ONE write. + * + * Rewind needs this: clearing (which stamps the boundary at now) and then + * restoring the retained footer separately makes the restore fail its own + * boundary check, so a session whose retained history still ends blocked + * dropped out of the Blocked section. Bypasses the monotonic guards on + * purpose — the transcript, not arrival order, is the truth after a truncation. + */ +export function replaceSessionNotifyAfterTruncate( + db: Database, + id: string, + namespace: string, + signal: { status: string; at: number; note: string | null; receivedAt?: number | null } | null, + clearedAt: number, + clearedAuthorAt: number | null = null +): boolean { + try { + // Every boundary is assigned ABSOLUTELY here, never via MAX, and + // scoped to the surviving transcript (#1717). The rewind deleted the + // history the old values described, so carrying them forward rejected + // genuine new footers with no way to ever lower them again. + const result = db.prepare(` + UPDATE sessions + SET last_notify_status = @status, + last_notify_at = @at, + last_notify_note = @note, + last_notify_received_at = @receivedAt, + last_notify_cleared_at = @clearedAt, + -- Re-derived from the RETAINED history, not dropped. Nulling + -- it threw away the one thing that rejects a late footer from + -- a turn the retained reply already answered: after the + -- rewind such a footer arrives fresh, so arrival cannot catch + -- it and only its author time can. Carrying the OLD value + -- would be wrong too — it describes deleted history — which is + -- why this is the value the reconciliation just computed. + last_notify_cleared_author_at = @clearedAuthorAt, + last_notify_updated_at = MAX(COALESCE(last_notify_updated_at, 0) + 1, @rev), + seq = seq + 1 + WHERE id = @id AND namespace = @namespace + `).run({ + id, + namespace, + status: signal?.status ?? null, + at: signal?.at ?? null, + note: signal?.note ?? null, + receivedAt: signal?.receivedAt ?? null, + clearedAuthorAt, + // The derived delivery boundary, already a hub stamp. No clamping + // against the retained footer is needed any more: the boundary is + // compared against a footer's hub ARRIVAL, and the retained footer + // is written here rather than re-validated through that guard. + clearedAt, + rev: Date.now() + }) + return result.changes === 1 + } catch { + return false + } +} + +/** Dismissed-blocker identities are stored as a JSON array in one column. */ +export function parseAckKeys(raw: string | null | undefined): string[] | null { + // `undefined` reaches here when the column is absent on a database that + // claims a version it never migrated to. Treat it like "no dismissals" + // rather than letting `raw.length` throw on every session load. + if (raw === null || raw === undefined) return null + try { + const parsed: unknown = JSON.parse(raw) + if (!Array.isArray(parsed)) return null + return parsed.filter((item): item is string => typeof item === 'string') + } catch { + // Pre-set rows stored a single bare key; keep honouring them. + return raw.length > 0 ? [raw] : null + } +} + +/** + * Exported so tests can exercise the retention boundary without a magic + * number. Pinned to `SUPPORTED_LIVE_DISMISSAL_CAP` (#1717 cold-review rounds + * 22-24) — `SessionBlockedAckSchema.keys` is bounded by the SAME constant, + * so retention and the wire schema can never disagree about how many keys + * are allowed through, which is the actual invariant; the constant itself is + * a generous practical ceiling, not derived from any true limit (there is + * none — `AgentState.requests` has no enforced cap). + */ +export const ACK_KEYS_RETENTION_LIMIT = SUPPORTED_LIVE_DISMISSAL_CAP + +function serialiseAckKeys(keys: string[] | null | undefined, livePendingKeys?: ReadonlySet): string | null { + if (!keys || keys.length === 0) return null + if (keys.length <= ACK_KEYS_RETENTION_LIMIT) return JSON.stringify(keys) + // Bounded so a long-lived session cannot grow this without limit. Plain + // "keep the newest N" evicted an OLD dismissal whose request was still + // pending once the limit's worth of later ones piled up, and the web + // re-flagged it as blocked (cold-review round 21) — the key was gone, not + // the request. A still-live key (the caller's current footer or an open + // request) is preserved regardless of position; only resolved/superseded + // keys are evicted, oldest first, to make room. + if (!livePendingKeys || livePendingKeys.size === 0) { + return JSON.stringify(keys.slice(-ACK_KEYS_RETENTION_LIMIT)) + } + const live: string[] = [] + const resolved: string[] = [] + for (const key of keys) { + (livePendingKeys.has(key) ? live : resolved).push(key) + } + const resolvedBudget = ACK_KEYS_RETENTION_LIMIT - live.length + const keptResolved = resolvedBudget > 0 ? resolved.slice(-resolvedBudget) : [] + // Resolved keys alone cannot always make room: `AgentState.requests` has + // no enforced count, so `live` itself can exceed the bound (#1717 + // cold-review round 25) — picking ever-larger numbers for + // `ACK_KEYS_RETENTION_LIMIT` (64 → 201 → 2000) just moved the N+1 failure + // rather than removing it, because no number derived from an unbounded + // source was ever going to hold. Oldest-first eviction among LIVE keys + // only starts once every resolved key is ALREADY gone — a dismissal + // whose request is still open can still be evicted here, but only when + // there is truly nothing else left to make room with. That is a + // documented, bounded trade (this hub tracks at most + // `ACK_KEYS_RETENTION_LIMIT` live dismissals at once) rather than an + // unbounded wire payload the schema keeps rejecting at whatever the + // current guess happens to be. + const keptLive = resolvedBudget >= 0 ? live : live.slice(-ACK_KEYS_RETENTION_LIMIT) + const kept = new Set([...keptResolved, ...keptLive]) + // Original relative order, not live-then-resolved — nothing downstream + // should have to know this function reordered anything. + return JSON.stringify(keys.filter((key) => kept.has(key))) +} diff --git a/hub/src/store/types.ts b/hub/src/store/types.ts index d6ae23fd36a..b4e93bad15f 100644 --- a/hub/src/store/types.ts +++ b/hub/src/store/types.ts @@ -24,6 +24,16 @@ export type StoredSession = { todosUpdatedAt: number | null teamState: unknown | null teamStateUpdatedAt: number | null + lastNotifyStatus: string | null + lastNotifyAt: number | null + lastNotifyNote: string | null + blockedAckAt: number | null + blockedAckReason: string | null + blockedAckKeys: string[] | null + lastNotifyClearedAt: number | null + lastNotifyReceivedAt: number | null + lastNotifyClearedAuthorAt: number | null + lastNotifyUpdatedAt: number | null active: boolean activeAt: number | null seq: number @@ -55,6 +65,13 @@ export type StoredMessage = { seq: number localId: string | null invokedAt: number | null + /** Set when the session-end sweep stamped `invokedAt` without a runtime + * ACK, so a reply can be told apart from one the agent actually got. */ + sweptAt?: number | null + /** When the HUB received this message, vs `createdAt`'s runner clock (#1717). */ + receivedAt?: number | null + /** 1 if the delivery reached the agent, 0 if handled locally, NULL if unknown (#1717). */ + agentDelivered?: number | null scheduledAt: number | null /** Omitted for ordinary queued/delivered rows; set when steer outcome is unknown. */ deliveryState?: MessageDeliveryState @@ -79,6 +96,15 @@ export type StoredPushSubscription = { export type NativeDevicePlatform = 'phone' | 'wear' | 'ios' +export type NativePushPreferences = { + ready: boolean + permissionRequest: boolean + inputRequest: boolean + modelError: boolean +} + +export type NativePushPreferencesInput = Partial + export type StoredFcmDevice = { id: number namespace: string @@ -92,6 +118,10 @@ export type StoredFcmDevice = { * null for legacy phone/Wear registrations. */ pushKey: string | null + /** + * Per-device push event filter. Null means unset (all event types enabled). + */ + preferences: NativePushPreferences | null createdAt: number updatedAt: number } diff --git a/hub/src/sync/aliveEvents.test.ts b/hub/src/sync/aliveEvents.test.ts index 4201f3cb57d..1d9fae31391 100644 --- a/hub/src/sync/aliveEvents.test.ts +++ b/hub/src/sync/aliveEvents.test.ts @@ -72,6 +72,66 @@ describe('alive incremental events', () => { expect(update.data).toEqual(expect.objectContaining({ active: true })) }) + it('carries thinkingAt on every emitted patch that includes thinking (cold-review round 27)', () => { + // The web list and detail caches gate `thinking`/`thinkingConfirmed` + // against `thinkingAt` to survive a stale patch arriving after a + // fresher one on the OTHER SSE stream — a gate that can only work + // if every emit site that sends `thinking` also sends the ordering + // value it is supposed to be judged against. + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + + const session = cache.getOrCreateSession( + 'session-alive-thinking-at', + { path: '/tmp/project', host: 'localhost' }, + { requests: {}, completedRequests: {} }, + 'default' + ) + + events.length = 0 + cache.handleSessionAlive({ sid: session.id, time: Date.now(), thinking: true }) + + const update = events.find((event) => event.type === 'session-updated') + expect(update).toBeDefined() + if (!update || update.type !== 'session-updated') { + return + } + expect(update.data).toHaveProperty('thinkingAt') + expect(typeof (update.data as { thinkingAt?: unknown }).thinkingAt).toBe('number') + expect(update.data).toHaveProperty('thinkingRevision') + expect(typeof (update.data as { thinkingRevision?: unknown }).thinkingRevision).toBe('number') + }) + + it('advances thinkingRevision on every thinking transition, even within the same clamped millisecond (cold-review round 27)', () => { + // `thinkingAt` is the CLI's own clamped alive-report time: two + // transitions processed within the same clamped-to-"now" millisecond + // (bun test executes synchronous calls fast enough for this to + // happen routinely) carry the IDENTICAL `thinkingAt`, which the web + // caches' ordering gate cannot tell apart with a strict `>` check. + // `thinkingRevision` is a counter, not a clock, so it must still + // advance even when `thinkingAt` does not. + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + + const session = cache.getOrCreateSession( + 'session-thinking-revision-advance', + { path: '/tmp/project', host: 'localhost' }, + { requests: {}, completedRequests: {} }, + 'default' + ) + + cache.handleSessionAlive({ sid: session.id, time: Date.now(), thinking: true }) + const firstRevision = cache.getSession(session.id)?.thinkingRevision + cache.handleSessionAlive({ sid: session.id, time: Date.now(), thinking: false }) + const secondRevision = cache.getSession(session.id)?.thinkingRevision + + expect(typeof firstRevision).toBe('number') + expect(typeof secondRevision).toBe('number') + expect(secondRevision).toBeGreaterThan(firstRevision!) + }) + it('emits full active machine object on machine alive', () => { const store = new Store(':memory:') const events: SyncEvent[] = [] diff --git a/hub/src/sync/messageService.ts b/hub/src/sync/messageService.ts index c7a58b543af..b1182f5e34f 100644 --- a/hub/src/sync/messageService.ts +++ b/hub/src/sync/messageService.ts @@ -1133,6 +1133,7 @@ export class MessageService { localId: msg.localId, content: msg.content, createdAt: msg.createdAt, + receivedAt: msg.receivedAt, invokedAt: msg.invokedAt, scheduledAt: msg.scheduledAt, ...(msg.deliveryState ? { deliveryState: msg.deliveryState } : {}), @@ -1179,7 +1180,15 @@ export class MessageService { && !id.startsWith(JOB_WAKE_MESSAGE_LOCAL_ID_PREFIX) ) if (localIds.length === 0) return null - this.store.messages.markMessagesInvoked(sessionId, localIds, invokedAt) + // `agentDelivered: false` because that is simply what happened: the + // sweep stamps `invoked_at` to unpin the floating bar on rows the + // runtime never received (#1717). The `sweptAt === invokedAt` check + // below already excludes them from answering a blocker, so this is + // defence in depth — but it puts the truth in the row rather than + // leaving it inferable from one guard. + this.store.messages.markMessagesInvoked(sessionId, localIds, invokedAt, { agentDelivered: false }) + // Record that THIS invokedAt came from the sweep, not a runtime ACK. + this.store.messages.markMessagesSwept(sessionId, localIds, invokedAt) this.forgetScheduledMatureNotified(localIds) this.publisher.emit({ type: 'messages-consumed', sessionId, localIds, invokedAt }) return { localIds, invokedAt } diff --git a/hub/src/sync/opencodeRewind.test.ts b/hub/src/sync/opencodeRewind.test.ts index 6f8e5a54fd7..af4f5ea0e6d 100644 --- a/hub/src/sync/opencodeRewind.test.ts +++ b/hub/src/sync/opencodeRewind.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it, spyOn } from 'bun:test' +import { createHash } from 'node:crypto' import type { Database } from 'bun:sqlite' import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Store } from '../store' import { RpcRegistry } from '../socket/rpcRegistry' -import { SyncEngine } from './syncEngine' +import { SyncEngine, hashOpenCodeRewindTranscript } from './syncEngine' import { registerSessionHandlers } from '../socket/handlers/cli/sessionHandlers' import type { CliSocketWithData } from '../socket/socketTypes' import type { OpenCodeRewindOperation } from '@hapi/protocol/schemas' @@ -577,3 +578,107 @@ describe('OpenCode durable Hub rewind commit', () => { } finally { f.engine.stop() } }) }) + +describe('OpenCode rewind transcript hash survives a hub upgrade (#1717 cold-review round 21)', () => { + // A reservation hashes `getAllMessages` output at reservation time, then + // the hub re-hashes it to verify nothing changed before applying a native + // report. `sweptAt` / `receivedAt` / `agentDelivered` are new in this PR: + // migrated-but-unchanged rows emit them as `null`, which a hub running + // the pre-upgrade code never did. Hashing the raw `StoredMessage` object + // therefore changes the hash for a transcript that is, in every way that + // matters, identical — stranding any reservation written before the + // upgrade. + const baseMessage = { + id: 'm1', + sessionId: 's1', + content: { type: 'text', text: 'hello' }, + createdAt: 1_700_000_000_000, + seq: 1, + localId: 'local-1', + invokedAt: 1_700_000_000_500, + scheduledAt: null + } + + it('is unaffected by fields a pre-upgrade hub never wrote', () => { + const preUpgrade = [{ ...baseMessage }] + const postUpgradeUnchangedRow = [{ ...baseMessage, sweptAt: null, receivedAt: null, agentDelivered: null }] + + expect(hashOpenCodeRewindTranscript(postUpgradeUnchangedRow)) + .toBe(hashOpenCodeRewindTranscript(preUpgrade)) + }) + + it('still changes when a field the old hash already covered changes', () => { + // Proves the projection is not accidentally hashing nothing: a real + // content edit must still be caught. + const original = [{ ...baseMessage }] + const edited = [{ ...baseMessage, content: { type: 'text', text: 'edited' } }] + + expect(hashOpenCodeRewindTranscript(edited)) + .not.toBe(hashOpenCodeRewindTranscript(original)) + }) + + // Cold-review round 22: the test above hashes BOTH sides through + // `hashOpenCodeRewindTranscript`, so it cannot see a drift between the + // helper and what the PRE-#1717 hub actually hashed — a key-order or + // null-vs-omitted difference changes the string either way and the test + // still passes, because the base serializer never appears in the + // experiment. A migration-boundary compatibility claim needs an artifact + // produced independently of the code under test: this hardcodes the + // exact bytes `toStoredMessage`'s pre-#1717 shape would have produced + // (`id, sessionId, content, createdAt, seq, localId, invokedAt, + // scheduledAt` — no `contentRevision` for a plain row, no trailing + // `deliveryState`/`deliveryPending` for an ordinary queued message) and + // hashes THAT directly, the way the old hub's own `JSON.stringify` did. + it('matches the hash a pre-upgrade hub would have written for this reservation', () => { + const preUpgradeSerializedShape = { + id: baseMessage.id, + sessionId: baseMessage.sessionId, + content: baseMessage.content, + createdAt: baseMessage.createdAt, + seq: baseMessage.seq, + localId: baseMessage.localId, + invokedAt: baseMessage.invokedAt, + scheduledAt: baseMessage.scheduledAt + } + const preUpgradeHash = createHash('sha256') + .update(JSON.stringify([preUpgradeSerializedShape])) + .digest('hex') + + const migratedRow = [{ ...baseMessage, sweptAt: null, receivedAt: null, agentDelivered: null }] + + expect(hashOpenCodeRewindTranscript(migratedRow)).toBe(preUpgradeHash) + }) + + it('matches the pre-upgrade hash for the conditionally-present fields too', () => { + // Same independent-artifact discipline, exercising the three fields + // `toStoredMessage` only includes when they apply: `contentRevision` + // must be OMITTED, not nulled, when it is the default (0); same for + // `deliveryState` / `deliveryPending` on an ordinary queued message. + const preUpgradeSerializedShape = { + id: baseMessage.id, + sessionId: baseMessage.sessionId, + content: baseMessage.content, + createdAt: baseMessage.createdAt, + seq: baseMessage.seq, + localId: baseMessage.localId, + invokedAt: baseMessage.invokedAt, + scheduledAt: baseMessage.scheduledAt + // No contentRevision / deliveryState / deliveryPending keys at all. + } + const preUpgradeHash = createHash('sha256') + .update(JSON.stringify([preUpgradeSerializedShape])) + .digest('hex') + + const migratedRowWithDefaults = [{ + ...baseMessage, + sweptAt: null, + receivedAt: null, + agentDelivered: null, + contentRevision: undefined, + deliveryState: undefined, + deliveryPending: undefined + }] + + expect(hashOpenCodeRewindTranscript(migratedRowWithDefaults)).toBe(preUpgradeHash) + }) +}) diff --git a/hub/src/sync/sessionCache.hubGeneration.test.ts b/hub/src/sync/sessionCache.hubGeneration.test.ts new file mode 100644 index 00000000000..1b83e308357 --- /dev/null +++ b/hub/src/sync/sessionCache.hubGeneration.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'bun:test' +import type { SyncEvent } from '@hapi/protocol/types' +import { Store } from '../store' +import type { EventPublisher } from './eventPublisher' +import { SessionCache } from './sessionCache' + +// `thinkingRevision`'s zero-exception (#1717 bot review) only covers the +// instant nothing has ticked yet after a restart; `hubGeneration` is what +// lets a client detect a restart happened at all, regardless of what any +// one session's counter reads at that moment — see the field's own doc +// comment on `SessionCache` for the full race it closes. +describe('SessionCache.hubGeneration (#1717 cold-review round 29)', () => { + const publisher = { emit: (_event: SyncEvent) => {} } as unknown as EventPublisher + + it('is stable across reads of the same instance', () => { + const cache = new SessionCache(new Store(':memory:'), publisher) + expect(cache.hubGeneration).toBe(cache.hubGeneration) + }) + + it('differs between two instances, simulating two hub processes', () => { + const first = new SessionCache(new Store(':memory:'), publisher) + const second = new SessionCache(new Store(':memory:'), publisher) + expect(first.hubGeneration).not.toBe(second.hubGeneration) + }) +}) diff --git a/hub/src/sync/sessionCache.ts b/hub/src/sync/sessionCache.ts index e0ac067ae61..0470def3701 100644 --- a/hub/src/sync/sessionCache.ts +++ b/hub/src/sync/sessionCache.ts @@ -1,17 +1,35 @@ -import { mergeClaudeSessionIdHistory, mergeReadState } from '@hapi/protocol' +import { randomUUID } from 'node:crypto' +import { mergeClaudeSessionIdHistory, mergeReadState, notifyBlockerKey, requestBlockerKey } from '@hapi/protocol' import { SESSION_LIFECYCLE_IDLE, SESSION_LIFECYCLE_RUNNING } from '@hapi/protocol' import { AgentStateSchema, ExternalRefsSchema, MetadataSchema, SessionPatchSchema, TeamStateSchema } from '@hapi/protocol/schemas' import type { BackgroundTask, CodexCollaborationMode, CopilotAgentMode, ExternalRef, PermissionMode, Session, SessionPatch } from '@hapi/protocol/types' -import type { SessionTurnEndReason, SessionTurnTrigger, Store } from '../store' +import type { SessionTurnEndReason, SessionTurnTrigger, Store, StoredMessage, StoredSession } from '../store' import type { TransferSessionJobsResult } from '../store/sessionJobs' import { clampAliveTime } from './aliveTime' import { EventPublisher } from './eventPublisher' import { extractTodoWriteTodosFromMessageContent, TodosSchema } from './todos' import { InvalidExternalRefsError } from './externalRefErrors' import { resolveSessionIdleTimeoutMs, shouldClearKeepaliveIdle, shouldMarkKeepaliveIdle } from './sessionIdle' +import { isDeliveredOperatorReply, messageReceivedAt, operatorReplyDeliveredAt } from './workGraphNotifyIngest' + +/** Transcript window scanned for a newer operator reply when merging a + * notify signal (#1717). Matches the startup backfill's scan depth. */ export { InvalidExternalRefsError } from './externalRefErrors' +/** A blocked-ack request with no observed key, once the session already has + * a keyed dismissal on record (#1717 cold-review round 37). There is no + * honest way to infer what a keyless request means at that point: reusing + * the stale key set keeps the ack scoped to blockers that no longer exist, + * silently leaving a genuinely new one undismissed while the endpoint + * reports success. Thrown instead of guessed; the route maps this to 400. */ +export class BlockedAckMissingKeyError extends Error { + constructor(sessionId: string) { + super(`Blocked-ack request for session ${sessionId} is missing a key, and this session already has a keyed dismissal — a key is required to dismiss a specific blocker rather than guessing at one.`) + this.name = 'BlockedAckMissingKeyError' + } +} + const QUEUED_MESSAGE_THINKING_GRACE_MS = 15_000 // A turn the hub closed when it restarted is picked up again if the agent // carries on with it this soon after the restart, instead of starting a new one. @@ -228,8 +246,35 @@ export class SessionCache { * the agent reports thinking before the hub sees it idle or a new prompt * arrives; see `recordTurn`. */ + private readonly maintenanceTurnSessionIds = new Set() + /** + * Sessions currently inside a maintenance turn's full duration, not just + * its rising edge (#1717 cold-review round 23). `maintenanceTurnSessionIds` + * is consumed once, on the first `thinking` tick, so it cannot by itself + * keep a LATER tick of the same turn (e.g. OpenCode's /compact reporting + * `thinking: true` more than once while it runs) from confirming the + * turn and hiding the stored footer the maintenance exemption already + * protects from being cleared. + */ + private readonly activeMaintenanceTurnSessionIds = new Set() private readonly interruptedTurnSessionIds: Set = new Set() private readonly sessionIdleTimeoutMs: number = resolveSessionIdleTimeoutMs() + /** + * One value per hub process, identifying the generation `thinkingRevision` + * resets within (#1717 cold-review round 29). + * + * `thinkingRevision` lives only in this cache's memory — a restart resets + * every session's counter to 0, closing the common case (an idle tab's + * cached revision is always higher than a fresh 0). But if ANY session's + * counter advances past 0 before a reconnecting tab's first post-restart + * list GET lands, that GET reports a small positive number which can + * still lose to the tab's stale, much higher pre-restart value — the + * zero-exception only ever covers the exact instant nothing has ticked + * yet. `hubGeneration` lets a client detect "this response came from a + * DIFFERENT process than the one my cached revision describes" and + * discard that cached revision outright, regardless of its number. + */ + readonly hubGeneration: string = randomUUID() constructor( private readonly store: Store, @@ -411,6 +456,7 @@ export class SessionCache { const namespace = cached?.namespace const existed = this.sessions.delete(sessionId) this.pendingThinkingUntilBySessionId.delete(sessionId) + this.activeMaintenanceTurnSessionIds.delete(sessionId) this.runtimeConfigUpdatedAtBySessionId.delete(sessionId) this.agentProgressAtBySessionId.delete(sessionId) if (existed) { @@ -461,6 +507,12 @@ export class SessionCache { const session: Session = { hasConversationContent: this.store.messages.hasConversationContent(sessionId), + // Always THIS process's generation, never inherited from + // `existing` — unlike `thinkingRevision`, there is nothing to + // carry forward across a refresh within one process's lifetime, + // and the whole point is that it must change across a restart + // (#1717 cold-review round 30). + hubGeneration: this.hubGeneration, id: stored.id, namespace: stored.namespace, seq: stored.seq, @@ -485,6 +537,8 @@ export class SessionCache { agentStateVersion: stored.agentStateVersion, thinking: existing?.thinking ?? false, thinkingAt: existing?.thinkingAt ?? 0, + thinkingRevision: existing?.thinkingRevision ?? 0, + thinkingConfirmed: existing?.thinkingConfirmed, activeTurnStartedAt: existing?.activeTurnStartedAt ?? null, backgroundTaskCount: existing?.backgroundTaskCount ?? 0, backgroundTasks: existing?.backgroundTasks ?? [], @@ -494,6 +548,24 @@ export class SessionCache { teamState, todosUpdatedAt: stored.todosUpdatedAt ?? 0, teamStateUpdatedAt: stored.teamStateUpdatedAt ?? 0, + blockedAck: stored.blockedAckAt !== null + ? { + at: stored.blockedAckAt, + reason: stored.blockedAckReason ?? '', + // Dropping this made a restart or merge fall back to + // timestamp-cutoff semantics, which is exactly what the + // identity exists to replace. + keys: stored.blockedAckKeys + } + : null, + notifyUpdatedAt: stored.lastNotifyUpdatedAt ?? 0, + lastNotify: stored.lastNotifyStatus !== null && stored.lastNotifyAt !== null + ? { + status: stored.lastNotifyStatus, + at: stored.lastNotifyAt, + note: stored.lastNotifyNote + } + : null, model: stored.model, modelReasoningEffort: stored.modelReasoningEffort, effort: stored.effort, @@ -535,6 +607,386 @@ export class SessionCache { this.refreshSession(sessionId) } + /** + * Record the agent's latest `AGENT_NOTIFY_SUMMARY` footer (#1717). + * Refreshes so SSE carries the new `lastNotify` to session lists. + */ + setSessionLastNotify( + sessionId: string, + signal: { status: string; at: number; note: string | null; receivedAt?: number | null } + ): void { + const session = this.sessions.get(sessionId) ?? this.refreshSession(sessionId) + if (!session) return + // `clearSessionLastNotify` nulls `last_notify_at`, so the store's + // timestamp-monotonic check has nothing left to compare against — and + // Claude replays keep their original transcript timestamps. Without a + // boundary, a delayed footer from before the operator's reply walks + // straight back in and the row reappears as blocked. + // + // The boundary is persisted (`last_notify_cleared_at`) rather than read + // from `activeTurnStartedAt`: that field resets when the agent goes + // idle, so a footer arriving after the reply turn *ended* found both it + // and `last_notify_at` null and was accepted. The persisted watermark + // also survives a restart. The store enforces the same rules in SQL; + // this is the in-memory fast path, and the two must agree. + // + // Each comparison stays inside ONE clock: the footer's hub arrival + // against the delivery boundary (both hub), and the footer's author + // time against the author time of the footer that delivery superseded + // (both this runner). + const stored = this.store.sessions.getSessionByNamespace(sessionId, session.namespace) + const clearedAt = stored?.lastNotifyClearedAt ?? null + if (signal.receivedAt != null && clearedAt !== null && signal.receivedAt < clearedAt) { + return + } + if (signal.receivedAt == null && clearedAt !== null && signal.at < clearedAt) { + return + } + const clearedAuthorAt = stored?.lastNotifyClearedAuthorAt ?? null + if (clearedAuthorAt !== null && signal.at <= clearedAuthorAt) { + return + } + // Unchanged status for the same turn: skip the write + SSE fan-out. + // The list only renders status/note, so a repeated footer is a no-op. + if (session.lastNotify + && session.lastNotify.status === signal.status + && session.lastNotify.note === signal.note + && session.lastNotify.at >= signal.at + ) { + return + } + if (this.store.sessions.setSessionLastNotify(sessionId, signal, session.namespace)) { + this.applyLastNotifyToCache(session, signal) + } + } + + /** + * Record the operator's manual unblock (#1717). Returns the stored ack so + * the caller can put the same values in the ledger event. + * + * @throws {BlockedAckMissingKeyError} when no key is supplied and the + * session already has an existing keyed dismissal — see that class for + * why this must reject rather than guess at the caller's intent. + */ + setSessionBlockedAck( + sessionId: string, + reason: string, + at: number = Date.now(), + key?: string + ): { + at: number + reason: string + keys?: string[] | null + } | null { + const session = this.sessions.get(sessionId) ?? this.refreshSession(sessionId) + if (!session) return null + // Merge, never replace: dismissing a second prompt must not un-dismiss + // the first. Deduped and bounded by the store. + const existingKeys = this.store.sessions.getSessionByNamespace(sessionId, session.namespace) + ?.blockedAckKeys ?? [] + // A reason-only call with no existing keys legitimately means the + // old watermark semantics (dismiss everything up to `at`) — that + // path is untouched below. But a reason-only call once keyed + // dismissals already exist cannot be resolved by guessing: reusing + // the stale key set silently keeps the ack in SCOPED mode, so a + // genuinely new blocker (whose key is not in that set) stays + // undismissed while the endpoint reports success (#1717 cold-review + // round 37). Reject rather than silently reinterpret. + if (!key && existingKeys.length > 0) { + throw new BlockedAckMissingKeyError(sessionId) + } + const keys = key + ? Array.from(new Set([...existingKeys, key])) + : null + // Keys the store's retention bound must never evict even if 64 newer + // dismissals pile up: the current footer and every request the agent + // is still parked on. Anything else is resolved or superseded and is + // safe to drop first (cold-review round 21). + const livePendingKeys = new Set() + if (session.lastNotify) { + livePendingKeys.add(notifyBlockerKey(session.lastNotify.at)) + } + for (const requestId of Object.keys(session.agentState?.requests ?? {})) { + livePendingKeys.add(requestBlockerKey(requestId)) + } + if (!this.store.sessions.setSessionBlockedAck( + sessionId, + { at, reason, keys, livePendingKeys }, + session.namespace + )) { + return null + } + // Read the WHOLE acknowledgement back from the row, not just its + // revision. SQLite bounds the key set; a long-lived session keeps + // dismissal keys after their prompts resolve, so the 65th distinct + // dismissal was trimmed to 64 in storage while the broadcast carried + // all 65 — and the web rejected that session wholesale against the + // 64-key schema limit, so other tabs silently missed the dismissal. + // Publishing what was persisted keeps the wire inside its own schema + // and keeps every tab agreeing with the row. + const stored = this.store.sessions.getSessionByNamespace(sessionId, session.namespace) + const ack = stored?.blockedAckAt !== null && stored?.blockedAckAt !== undefined + ? { + at: stored.blockedAckAt, + reason: stored.blockedAckReason ?? reason, + keys: stored.blockedAckKeys ?? null + } + : { at, reason, keys } + // In place + full-session emit, for the same reason as the notify + // writes: refreshSession would discard in-memory runtime state. + session.blockedAck = ack + // Read the revision BACK from the row rather than inventing one from + // hub-now. SQLite versions the write using the blocker's observed + // timestamp; broadcasting a now-based revision made a later refresh + // look older than the SSE patch, and the browser rejected a dismissal + // a merge had legitimately transferred. + session.notifyUpdatedAt = this.readNotifyRevision(session) + this.publisher.emit({ type: 'session-updated', sessionId: session.id, data: session }) + return ack + } + + /** + * Forget the stored footer — a new turn started, so the agent's last + * self-report no longer describes the present. + */ + /** + * Replace the notify signal and its clear boundary in one write. + * + * Only for post-truncation reconciliation: after a rewind the retained + * transcript is the truth, so this bypasses the monotonic and boundary + * guards that protect the live path from out-of-order arrivals. + */ + /** + * True when the destination holds a blocker older than `ackAt` that its own + * acknowledgement does not already cover — i.e. one a transferred watermark + * would silence without the operator ever having seen it. + */ + private hasUnacknowledgedBlockerBefore( + stored: StoredSession, + ackAt: number, + namespace: string + ): boolean { + const ownAckAt = stored.blockedAckAt ?? null + const covered = (at: number): boolean => ownAckAt !== null && at <= ownAckAt + const notifyAt = stored.lastNotifyAt + if (stored.lastNotifyStatus !== null && notifyAt !== null + && notifyAt < ackAt && !covered(notifyAt)) { + return true + } + const session = this.sessions.get(stored.id) + const requests = session?.agentState?.requests + if (!requests) return false + for (const request of Object.values(requests)) { + const since = typeof request.createdAt === 'number' ? request.createdAt : null + if (since !== null && since < ackAt && !covered(since)) return true + } + return false + } + + replaceNotifyAfterTruncate( + sessionId: string, + signal: { status: string; at: number; note: string | null; receivedAt?: number | null } | null, + boundaryAt: number = Date.now(), + boundaryAuthorAt: number | null = null + ): void { + const session = this.sessions.get(sessionId) ?? this.refreshSession(sessionId) + if (!session) return + if (this.store.sessions.replaceNotifyAfterTruncate( + sessionId, + session.namespace, + signal, + boundaryAt, + boundaryAuthorAt + )) { + this.applyLastNotifyToCache(session, signal) + } + } + + clearSessionLastNotify(sessionId: string, boundaryAt: number = Date.now()): void { + const session = this.sessions.get(sessionId) + if (!session) return + // The boundary advances even when no footer is cached. A turn that + // starts BEFORE the previous footer reaches the hub would otherwise + // skip the write entirely, and that delayed pre-reply footer could + // then arrive after the reply turn ended and be accepted — reviving a + // blocker the operator had already answered. + const cleared = this.store.sessions.clearSessionLastNotify( + sessionId, + session.namespace, + boundaryAt + ) + if (session.lastNotify && cleared) { + this.applyLastNotifyToCache(session, null) + } else if (cleared) { + session.notifyUpdatedAt = this.readNotifyRevision(session) + } + } + + /** + * Update `lastNotify` in place and broadcast the whole Session. + * + * Deliberately NOT `refreshSession`: that rebuilds from SQLite and would + * discard in-memory runtime state, most damagingly the `updatedAt` bump + * `markMessageQueued` / `applySessionPatch` just made in memory — the clear + * runs on exactly those paths, so refreshing there broadcast a stale clock + * and moved the session back down the list. + * + * A full Session rather than a SessionPatch because `SessionPatch` has no + * `lastNotify` field; the web's full-session branch rebuilds the summary + * via `toSessionSummary`, which does carry it. + */ + private applyLastNotifyToCache( + session: Session, + signal: { status: string; at: number; note: string | null } | null + ): void { + session.lastNotify = signal + // Bumped on every write INCLUDING a clear: without an ordering key a + // delayed snapshot on the other SSE stream re-applies the pre-clear + // state and the row flips back to blocked. + // + // Read BACK from the row, for the same reason the acknowledgement path + // does. SQLite versions a clear off the *boundary* timestamp — which is + // the answering message's clock, usually well in the past — so a + // now-based revision invented here outruns the row. A merge clears the + // footer, then transfers the dismissal, then re-emits from a refresh: + // with a now-based revision that final, correct payload looked OLDER + // than this patch and the browser rejected it, keeping the pre-merge + // acknowledgement and re-blocking a row the operator had dismissed. + session.notifyUpdatedAt = this.readNotifyRevision(session) + this.publisher.emit({ type: 'session-updated', sessionId: session.id, data: session }) + } + + /** + * Carry a dismissal from one session onto another (#1717). + * + * Public because more than one path merges sessions: the resume-id rotation + * in `mergeSessionData`, and the Codex Desktop duplicate reconciliation, + * which copies messages across and then deletes the source. That one did + * not transfer the acknowledgement, so a dismissed footer copied into the + * canonical session became its latest signal and showed up in Blocked + * again — a dismissal the operator had already made, undone by a merge + * they did not ask for. One implementation rather than two, because an + * ack-merge rule duplicated is an ack-merge rule that drifts. + */ + transferBlockedAck( + fromSessionId: string, + toSessionId: string, + namespace: string, + notifyKeyRemap?: ReadonlyMap, + // A caller committing this AFTER `fromSessionId` has already been + // deleted (#1717 cold-review round 36) has nothing left to read + // live — it must snapshot the source's ack before deletion and + // pass it through here instead. + sourceSnapshot?: { blockedAckAt: number | null; blockedAckKeys: string[] | null; blockedAckReason: string | null } + ): void { + const source = sourceSnapshot ?? this.store.sessions.getSessionByNamespace(fromSessionId, namespace) + const sourceAckAt = source?.blockedAckAt ?? null + if (!source || sourceAckAt === null) return + const target = this.store.sessions.getSessionByNamespace(toSessionId, namespace) + if (!target) return + const targetAckAt = target.blockedAckAt ?? null + // UNION the dismissal sets. Skipping the source entirely whenever the + // destination had its own keyed acknowledgement meant each row having + // dismissed a DIFFERENT request made the source's request block again + // on the merged row — the merge unions the requests, so it has to + // union what dismissed them. + // + // A source footer key is remapped to the SURVIVING occurrence's own + // key first (#1717 cold-review round 25): an untimestamped Codex + // footer can carry a different `createdAt` in two projections of the + // same thread, so when the merge deduplicates it against an existing + // canonical row, the raw source key no longer matches anything live + // and the dismissal silently stops applying — the message-matching + // caller (this function has no visibility into which row matched + // which) is the only place that knows the remap. + const remappedSourceKeys = (source.blockedAckKeys ?? []) + .map((key) => notifyKeyRemap?.get(key) ?? key) + const mergedKeys = Array.from(new Set([ + ...(target.blockedAckKeys ?? []), + ...remappedSourceKeys + ])) + // Keyless acknowledgements (written before identities existed) still + // carry across on the old watermark rule, so an upgrade does not + // resurrect work the operator already dismissed. + const transferKeyless = mergedKeys.length === 0 + && (targetAckAt === null || sourceAckAt > targetAckAt) + if (mergedKeys.length === 0 && !transferKeyless) return + const targetSession = this.sessions.get(toSessionId) + const livePendingKeys = new Set() + if (targetSession?.lastNotify) { + livePendingKeys.add(notifyBlockerKey(targetSession.lastNotify.at)) + } + for (const requestId of Object.keys(targetSession?.agentState?.requests ?? {})) { + livePendingKeys.add(requestBlockerKey(requestId)) + } + this.store.sessions.setSessionBlockedAck( + toSessionId, + { + at: Math.max(sourceAckAt, targetAckAt ?? 0), + reason: (targetAckAt !== null && targetAckAt >= sourceAckAt) + ? (target.blockedAckReason ?? '') + : (source.blockedAckReason ?? ''), + keys: mergedKeys.length > 0 ? mergedKeys : null, + livePendingKeys + }, + namespace + ) + } + + /** + * Did this delivered reply arrive after the footer it might answer (#1717)? + * + * Both sides are hub stamps: the reply's delivery time against the footer's + * hub ARRIVAL. The footer's own timestamp is the runner's clock, and mixing + * the two meant a runner running 30 seconds behind could have a merge or + * rewind treat a turn's own initiating prompt as the answer to the footer + * that turn ended on, removing a blocker still plainly visible in the + * transcript. A position cannot serve either — see `messageReceivedAt`. + */ + private replyAnswersFooter(reply: StoredMessage, footerReceivedAt: number): boolean { + return operatorReplyDeliveredAt(reply) > footerReceivedAt + } + + /** + * The most recently delivered operator reply on a session, or null (#1717). + * + * Ordered by delivery time, which is the same key `replyAnswersFooter` + * then compares against. Selecting on anything else let the two disagree: + * a merge renumbers the destination's positions, so the highest `seq` is + * not the latest reply, and the one picked as "latest" could be the one + * that answers least. Scans every delivered row rather than a recency + * window, because after a merge a bounded window can hold only destination + * rows and miss the source reply that answered the blocker. + */ + private latestDeliveredOperatorReply(sessionId: string): StoredMessage | null { + let newest: StoredMessage | null = null + for (const message of this.store.messages.getInvokedMessages(sessionId)) { + if (!isDeliveredOperatorReply(message)) continue + // Selected by the same key `replyAnswersFooter` then compares, and + // by the same rule the transcript derivation uses — the two having + // their own copies is how the merge path kept comparing a LOCAL + // reply's runner clock against a footer's hub arrival (#1717). + if (newest === null + || operatorReplyDeliveredAt(message) > operatorReplyDeliveredAt(newest)) { + newest = message + } + } + return newest + } + + /** + * The notify revision as SQLite computed it — the single source of truth. + * + * Every in-memory broadcast must carry the row's value, or two independent + * counters drift and the browser's ordering guard starts rejecting good + * payloads. Falls back to a local bump only if the row vanished mid-merge. + */ + private readNotifyRevision(session: Session): number { + return this.store.sessions + .getSessionByNamespace(session.id, session.namespace)?.lastNotifyUpdatedAt + ?? ((session.notifyUpdatedAt ?? 0) + 1) + } + markSessionActive(sessionId: string, time: number = Date.now()): void { const t = clampAliveTime(time) ?? Date.now() const session = this.sessions.get(sessionId) ?? this.refreshSession(sessionId) @@ -552,7 +1004,10 @@ export class SessionCache { data: { active: true, activeAt: session.activeAt, - thinking: session.thinking + thinking: session.thinking, + thinkingAt: session.thinkingAt, + thinkingRevision: session.thinkingRevision, + hubGeneration: this.hubGeneration } satisfies SessionPatch }) @@ -609,7 +1064,26 @@ export class SessionCache { const wasThinking = session.thinking if (patch.active !== undefined) session.active = patch.active + if (patch.thinking !== undefined || patch.thinkingConfirmed !== undefined) { + this.bumpThinkingRevision(session) + } if (patch.thinking !== undefined) session.thinking = patch.thinking + if (patch.thinkingConfirmed !== undefined) { + session.thinkingConfirmed = patch.thinkingConfirmed + } else if (patch.thinking) { + // No existing caller of this generic patch path sends + // `thinkingConfirmed` explicitly, so without this a session + // queued via `markMessageQueued` (thinkingConfirmed: false) and + // then genuinely confirmed ONLY through this path — never through + // `handleSessionAlive` — would stay unconfirmed forever. Same + // maintenance exemption as the clear below (#1717 cold-review + // round 23): a caller that never learned about this field must + // not confirm a maintenance turn either. + if (!wasThinking && this.maintenanceTurnSessionIds.has(session.id)) { + this.activeMaintenanceTurnSessionIds.add(session.id) + } + session.thinkingConfirmed = !this.activeMaintenanceTurnSessionIds.has(session.id) + } if (patch.activeAt !== undefined) session.activeAt = patch.activeAt if (patch.contentRevision !== undefined) session.contentRevision = Math.max(session.contentRevision ?? 0, patch.contentRevision) if (patch.readState) session.readState = mergeReadState(session.readState, patch.readState) @@ -645,12 +1119,43 @@ export class SessionCache { session.agentState = patch.agentState.value session.agentStateVersion = patch.agentState.version } - if (patch.thinking === false) this.forgetInterruptedTurn(session.id) + if (patch.thinking === false) { + this.forgetInterruptedTurn(session.id) + this.activeMaintenanceTurnSessionIds.delete(session.id) + } this.recordTurn(session, wasThinking, Date.now(), 'patch', 'idle') + // #1717: last, because clearing re-seats the cached Session object and + // would strand the in-place mutations above. + if (!wasThinking && session.thinking) { + // …unless this turn is maintenance. OpenCode can reach an idle + // session with a scheduled /compact and then send thinking=true + // before compaction starts: the maintenance acknowledgement + // correctly preserved the footer, and this keepalive deleted it + // anyway — so when compaction ended without a new status summary + // the session stayed out of Blocked with nothing having answered + // it. A turn the operator did not prompt does not invalidate the + // agent's last self-report. Consumed once, so the NEXT genuine + // prompt turn clears normally (#1717). + if (!this.maintenanceTurnSessionIds.delete(session.id)) { + this.clearSessionLastNotify(session.id) + } + } + return true } + // Monotonic, not wall-clock (#1717 cold-review round 27): `thinkingAt` is + // the CLI's own clamped alive-report time, so two transitions processed + // within the same clamped-to-"now" millisecond — a reconnect replaying + // buffered ticks, clock skew, plain bad luck — can carry the identical + // value, defeating a strict `>` ordering check on it. This counter + // cannot collide: every call increments it regardless of what wall-clock + // time reads. + private bumpThinkingRevision(session: Session): void { + session.thinkingRevision = (session.thinkingRevision ?? 0) + 1 + } + handleSessionAlive(payload: { sid: string time: number @@ -673,6 +1178,7 @@ export class SessionCache { const wasActive = session.active const wasThinking = session.thinking const previousActiveTurnStartedAt = session.activeTurnStartedAt + const previousThinkingConfirmed = session.thinkingConfirmed const previousPermissionMode = session.permissionMode const previousModel = session.model const previousModelReasoningEffort = session.modelReasoningEffort @@ -691,17 +1197,36 @@ export class SessionCache { session.activeAt = Math.max(session.activeAt, hubNow) session.thinking = requestedThinking || preserveQueuedThinking session.thinkingAt = t + this.bumpThinkingRevision(session) + // A rising edge within a maintenance turn's one-shot exemption window + // stays marked for the turn's whole duration, not just this tick — + // OpenCode's /compact can report `thinking: true` more than once + // while it runs, and `maintenanceTurnSessionIds` itself is consumed + // (deleted) on the first tick below (#1717 cold-review round 23). + if (!wasThinking && session.thinking && this.maintenanceTurnSessionIds.has(session.id)) { + this.activeMaintenanceTurnSessionIds.add(session.id) + } + // The CLI's OWN report, not the hub's queue-grace override, is what + // confirms a turn actually started (#1717 cold-review round 22) — + // UNLESS this is a maintenance turn: the clear-exemption below already + // keeps the stored footer from being cleared for one, so confirming + // it here hid the footer anyway, and ending compaction made the SAME + // unanswered blocker look newly arrived (#1717 cold-review round 23). + if (requestedThinking) { + session.thinkingConfirmed = !this.activeMaintenanceTurnSessionIds.has(session.id) + } if (!requestedThinking && preserveQueuedThinking && hasUnconsumedPrompt) { session.activeTurnStartedAt = hubNow } else if (wasThinking && !session.thinking) { session.activeTurnStartedAt = null + this.activeMaintenanceTurnSessionIds.delete(session.id) } if (requestedThinking || pendingThinkingUntil <= hubNow) { this.pendingThinkingUntilBySessionId.delete(session.id) } // The agent says it's idle: whatever it does next is a new turn. if (!requestedThinking) this.forgetInterruptedTurn(session.id) - this.recordTurn(session, wasThinking, hubNow, 'agent', 'idle') + const resumedInterruptedTurn = this.recordTurn(session, wasThinking, hubNow, 'agent', 'idle') if (payload.permissionMode !== undefined && !this.isStaleRuntimeKeepAlive(session.id, 'permissionMode', t)) { session.permissionMode = payload.permissionMode this.persistPreferredPermissionMode(session, payload.permissionMode) @@ -756,9 +1281,11 @@ export class SessionCache { || previousCollaborationMode !== session.collaborationMode || previousCopilotAgentMode !== session.copilotAgentMode const turnBoundaryChanged = previousActiveTurnStartedAt !== session.activeTurnStartedAt + const thinkingConfirmedChanged = previousThinkingConfirmed !== session.thinkingConfirmed const shouldBroadcast = (!wasActive && session.active) || (wasThinking !== session.thinking) || turnBoundaryChanged + || thinkingConfirmedChanged || modeChanged || (now - lastBroadcastAt > 60_000) @@ -771,6 +1298,10 @@ export class SessionCache { active: true, activeAt: session.activeAt, thinking: session.thinking, + thinkingAt: session.thinkingAt, + thinkingRevision: session.thinkingRevision, + hubGeneration: this.hubGeneration, + thinkingConfirmed: session.thinkingConfirmed, activeTurnStartedAt: session.activeTurnStartedAt, permissionMode: session.permissionMode, model: session.model, @@ -782,6 +1313,54 @@ export class SessionCache { } satisfies SessionPatch }) } + + // #1717: a new turn invalidates the agent's last self-report — whatever + // it said it was blocked on, it is now working. Done last because + // `clearSessionLastNotify` re-seats the cached Session object, which + // would strand the in-place mutations above. + if ( + !wasThinking && session.thinking + // The agent resuming a turn a hub restart left open is not a + // NEW turn (#1717 cold-review round 32) — `recordTurn` just + // above already recognized this exact rising edge as that + // resume, not a fresh prompt, so nothing it reports should + // invalidate whatever the session reported before the restart. + && !resumedInterruptedTurn + ) { + // Same maintenance exemption as `applySessionPatch`: whichever + // rising edge arrives first consumes the mark, so one maintenance + // turn is protected and the next genuine prompt clears (#1717). + if (!this.maintenanceTurnSessionIds.delete(session.id)) { + this.clearSessionLastNotify(session.id) + } + } + } + + /** + * The next turn on this session is maintenance, not an answer (#1717). + * + * Set when the CLI acknowledges consuming a command rather than + * delivering a prompt — OpenCode's /compact does this at dequeue time. + * Consumed by the next thinking rising edge, so it protects exactly that + * one turn and a genuine prompt afterwards still clears the footer. + */ + markMaintenanceTurn(sessionId: string): void { + const session = this.sessions.get(sessionId) + // Sending a command like /compact through the ordinary queue path + // (`markMessageQueued`) already flips `thinking` true, with no + // rising edge left for the usual one-shot-mark consumption to catch + // once this CLI acknowledgement arrives after it. Mark the turn as + // maintenance immediately in that case and retroactively + // un-confirm, or the next keepalive confirms the turn and hides the + // footer the maintenance exemption exists to protect (#1717 + // cold-review round 24). + if (session?.thinking) { + this.activeMaintenanceTurnSessionIds.add(sessionId) + session.thinkingConfirmed = false + this.bumpThinkingRevision(session) + return + } + this.maintenanceTurnSessionIds.add(sessionId) } /** @@ -815,7 +1394,16 @@ export class SessionCache { session.thinking = true session.thinkingAt = nextTime - if (!wasThinking) session.activeTurnStartedAt = activeTurnStartedAt + this.bumpThinkingRevision(session) + if (!wasThinking) { + session.activeTurnStartedAt = activeTurnStartedAt + // This turn has only been QUEUED, not confirmed by the CLI — a + // cancel before delivery never reaches a running agent at all + // (#1717 cold-review round 22). Only stamped on the transition + // into thinking: a reply queued mid-turn must not demote an + // already-confirmed turn back to unconfirmed. + session.thinkingConfirmed = false + } this.recordTurn(session, wasThinking, session.activeTurnStartedAt ?? nextTime, 'hub_prompt', 'idle') session.updatedAt = Math.max(session.updatedAt, nextTime) this.pendingThinkingUntilBySessionId.set(session.id, nextTime + QUEUED_MESSAGE_THINKING_GRACE_MS) @@ -828,17 +1416,40 @@ export class SessionCache { sessionId: session.id, data: { thinking: true, + thinkingAt: session.thinkingAt, + thinkingRevision: session.thinkingRevision, + hubGeneration: this.hubGeneration, + thinkingConfirmed: session.thinkingConfirmed, activeTurnStartedAt: session.activeTurnStartedAt, updatedAt: session.updatedAt } satisfies SessionPatch }) } + + // #1717: the clear lives on CONFIRMED delivery + // (`clearSessionLastNotifyOnDelivery`), not here. Queueing is + // optimistic: an idempotent retry of an already-consumed message + // reuses its row and starts no turn, and a prompt can be cancelled + // before the agent ever sees it — both erased a live blocker from + // here. The boundary still advances so a delayed footer cannot slip + // in behind the reply. + // The boundary is NOT advanced here any more. Queueing is optimistic: + // a reply cancelled before delivery would otherwise leave a boundary + // that rejects a footer the agent generated before the send, and the + // unanswered blocker never reappears. Both the clear and the boundary + // now move together on confirmed delivery. } /** * Persists a change of `thinking` as the start or end of a turn, so how * long agents worked survives a hub restart. Never throws: losing a turn * row must not break the keepalive path. + * + * Returns whether THIS transition was recognized as the agent resuming + * a turn a hub restart left open, rather than starting a new one + * (#1717 cold-review round 32) — callers that clear the session's + * self-report on a rising edge need this: a turn resuming is not a + * new turn, so nothing it already reported is invalidated by it. */ private recordTurn( session: Session, @@ -846,8 +1457,8 @@ export class SessionCache { at: number, trigger: SessionTurnTrigger, reason: SessionTurnEndReason - ): void { - if (wasThinking === session.thinking) return + ): boolean { + if (wasThinking === session.thinking) return false try { if (session.thinking) { // Only the agent itself carrying on continues an interrupted @@ -859,12 +1470,13 @@ export class SessionCache { if (!resumed) { this.store.turns.open(session.id, session.namespace, at, trigger) } - } else { - this.store.turns.close(session.id, at, reason) + return resumed } + this.store.turns.close(session.id, at, reason) } catch (error) { console.warn('[SessionCache] Failed to record turn', { sessionId: session.id, error }) } + return false } /** The turn a restart interrupted can no longer continue. */ @@ -1173,12 +1785,14 @@ export class SessionCache { this.store.sessions.setSessionActive(session.id, false, session.activeAt, session.namespace) session.thinking = false session.thinkingAt = t + this.bumpThinkingRevision(session) session.activeTurnStartedAt = null this.recordTurn(session, wasThinking, t, 'agent', 'session_end') session.backgroundTaskCount = 0 session.backgroundTasks = [] session.derivedToolWork = false this.pendingThinkingUntilBySessionId.delete(session.id) + this.activeMaintenanceTurnSessionIds.delete(session.id) this.publisher.emit({ type: 'session-updated', @@ -1187,6 +1801,9 @@ export class SessionCache { active: false, activeAt: session.activeAt, thinking: false, + thinkingAt: session.thinkingAt, + thinkingRevision: session.thinkingRevision, + hubGeneration: this.hubGeneration, activeTurnStartedAt: null, backgroundTaskCount: 0, backgroundTasks: [], @@ -1216,6 +1833,7 @@ export class SessionCache { // same stop time, or stopped rows reorder after a hub restart. this.store.sessions.setSessionActive(session.id, false, session.activeAt, session.namespace) session.thinking = false + this.bumpThinkingRevision(session) session.activeTurnStartedAt = null // The keepalive died, not the tasks: reset the transient work // state like handleSessionEnd does, or a session that expired @@ -1228,6 +1846,7 @@ export class SessionCache { // The last keepalive is the last time the agent was known to be working. this.recordTurn(session, wasThinking, session.activeAt, 'agent', 'expired') this.pendingThinkingUntilBySessionId.delete(session.id) + this.activeMaintenanceTurnSessionIds.delete(session.id) expired.push(session.id) this.publisher.emit({ type: 'session-updated', @@ -1235,6 +1854,8 @@ export class SessionCache { data: { active: false, thinking: false, + thinkingRevision: session.thinkingRevision, + hubGeneration: this.hubGeneration, activeTurnStartedAt: null, // The last keepalive: when the session stopped, for clients // that only saw an older activeAt. @@ -2081,6 +2702,7 @@ export class SessionCache { this.lastBroadcastAtBySessionId.delete(sessionId) this.todoBackfillAttemptedSessionIds.delete(sessionId) this.pendingThinkingUntilBySessionId.delete(sessionId) + this.activeMaintenanceTurnSessionIds.delete(sessionId) this.agentProgressAtBySessionId.delete(sessionId) this.attachedJobEmitVersion.delete(sessionId) @@ -2433,6 +3055,76 @@ export class SessionCache { } } + // #1717: the acknowledgement has to follow the requests it silences. + // The merge above moves the source's pending requests onto the target + // with their original `createdAt`, so without the watermark a prompt + // the operator already dismissed reads as newer-than-nothing and goes + // straight back to blocking. Keep the later of the two acks, so a + // genuinely newer request on either side still blocks. + // The acknowledgement now carries the identity of the blocker it + // covered, so a merge can transfer it without it swallowing anything + // else: a destination ack cannot hide an incoming source footer, and a + // source ack cannot hide an unanswered destination prompt. That is what + // the previous timestamp-only watermark could not express, and why a + // one-directional guard here was never going to be enough. + // + // Keyless acks (written before the identity existed) keep the old + // watermark semantics, so the later of the two still wins for them. + this.transferBlockedAck(oldSessionId, newSessionId, namespace) + + // The footer has to follow its transcript. `mergeSessionMessages` moves + // the blocked turn onto the destination but replays no `message-added`, + // so nothing re-derives the signal there — the conversation would keep + // the unanswered footer in its history while dropping out of the + // Blocked section entirely. Newest wins, matching the monotonic rule + // the live writes use. + // A source with NO footer is not "nothing to say": it may hold a + // delivered reply that answered its own footer and, once merged, also + // answers the destination's older one. Skipping reconciliation there + // left the destination showing a blocker the combined transcript + // answers. + if (oldStored.lastNotifyStatus === null || oldStored.lastNotifyAt === null) { + const target = this.store.sessions.getSessionByNamespace(newSessionId, namespace) + const targetAt = target?.lastNotifyAt ?? null + if (target && target.lastNotifyStatus !== null && targetAt !== null) { + const newest = this.latestDeliveredOperatorReply(newSessionId) + // Measured against the footer's HUB ARRIVAL, not its runner + // timestamp and not a position: after the merge renumbering, + // an EARLIER destination reply sits above every source row and + // read as proof it had answered a later source footer. + const targetReceivedAt = target.lastNotifyReceivedAt ?? targetAt + if (newest !== null && this.replyAnswersFooter(newest, targetReceivedAt)) { + this.clearSessionLastNotify(newSessionId, operatorReplyDeliveredAt(newest)) + } + } + } + + const oldNotifyAt = oldStored.lastNotifyAt + if (oldStored.lastNotifyStatus !== null && oldNotifyAt !== null) { + const latest = this.store.sessions.getSessionByNamespace(newSessionId, namespace) + const targetNotifyAt = latest?.lastNotifyAt ?? null + // A null on the destination is ambiguous: it can mean "never had a + // footer", or "the operator already answered and markMessageQueued + // cleared it". Copying in that second case resurrects a blocker + // that was dealt with, so check the (already merged) transcript for + // a delivered reply newer than the footer before carrying it over. + // Mirrors the operator-reply boundary the startup backfill applies. + const newestReply = this.latestDeliveredOperatorReply(newSessionId) + const oldReceivedAt = oldStored.lastNotifyReceivedAt ?? oldNotifyAt + const answeredSince = newestReply !== null + && this.replyAnswersFooter(newestReply, oldReceivedAt) + // Footer vs footer is a same-runner-clock comparison, so `at` is + // the right key here even though the reply comparison above is not. + if (latest && !answeredSince && (targetNotifyAt === null || oldNotifyAt > targetNotifyAt)) { + this.setSessionLastNotify(newSessionId, { + status: oldStored.lastNotifyStatus, + at: oldNotifyAt, + note: oldStored.lastNotifyNote, + receivedAt: oldStored.lastNotifyReceivedAt + }) + } + } + if (oldStored.teamState !== null && oldStored.teamStateUpdatedAt !== null) { this.store.sessions.setSessionTeamState( newSessionId, diff --git a/hub/src/sync/sessionCache.turns.test.ts b/hub/src/sync/sessionCache.turns.test.ts index 80dbfce54c8..eca84d9aa82 100644 --- a/hub/src/sync/sessionCache.turns.test.ts +++ b/hub/src/sync/sessionCache.turns.test.ts @@ -119,6 +119,35 @@ describe('SessionCache turn recording', () => { } }) + it('preserves a stored footer when the agent resumes a turn a hub restart cut short (#1717 cold-review round 32)', () => { + // The old process set a footer before it died mid-turn. On restart, + // the fresh in-memory cache's `thinking` defaults to false, so the + // runner's first keepalive (still `thinking: true`, genuinely + // continuing the SAME interrupted turn) looks like an ordinary + // false-to-true rising edge — which `markSessionActive`'s own + // "a new turn invalidates the agent's last self-report" rule would + // otherwise clear. `recordTurn` already distinguishes a genuine + // resume from a new turn for its OWN bookkeeping; the clear must + // respect that same distinction instead of re-deriving it (and + // getting it wrong) from the bare `thinking` transition alone. + const { store, session } = setup() + try { + store.sessions.setSessionLastNotify(session.id, { + status: 'blocked', at: Date.now() - 60_000, note: 'needs creds' + }, 'default') + store.turns.open(session.id, 'default', Date.now() - 60_000, 'agent') + + const restarted = restart(store) + restarted.handleSessionAlive({ sid: session.id, time: Date.now(), thinking: true }) + + expect(turns(store)).toHaveLength(1) + expect(turns(store)[0]).toMatchObject({ endedAt: null }) + expect(restarted.getSession(session.id)?.lastNotify?.status).toBe('blocked') + } finally { + store.close() + } + }) + it('starts a new turn once the agent was seen idle after a restart', () => { const { store, session } = setup() try { diff --git a/hub/src/sync/sessionCacheNotify.test.ts b/hub/src/sync/sessionCacheNotify.test.ts new file mode 100644 index 00000000000..ea13073f512 --- /dev/null +++ b/hub/src/sync/sessionCacheNotify.test.ts @@ -0,0 +1,2311 @@ +import { describe, expect, it } from 'bun:test' +import type { SyncEvent } from '@hapi/protocol/types' +import { SessionBlockedAckSchema } from '@hapi/protocol/schemas' +import { Store } from '../store' +import { ACK_KEYS_RETENTION_LIMIT } from '../store/sessions' +import type { EventPublisher } from './eventPublisher' +import { BlockedAckMissingKeyError, SessionCache } from './sessionCache' + +function makeCache(): { cache: SessionCache; store: Store } { + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_event: SyncEvent) => {} } as EventPublisher) + return { cache, store } +} + +function seedBlocked(cache: SessionCache, tag: string): string { + const session = cache.getOrCreateSession( + tag, + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + cache.markSessionActive(session.id) + cache.setSessionLastNotify(session.id, { status: 'blocked', at: Date.now(), note: 'needs creds' }) + expect(cache.getSession(session.id)?.lastNotify?.status).toBe('blocked') + return session.id +} + +describe('lastNotify clearing on turn start (#1717)', () => { + it('keeps the footer while the prompt is only QUEUED, clears on delivery', () => { + // Queueing is optimistic: an idempotent retry of an already-consumed + // message reuses its row and starts no turn, and a prompt can be + // cancelled before the agent ever sees it. Clearing here erased live + // blockers in both cases, so the clear lives on confirmed delivery. + const { cache } = makeCache() + const id = seedBlocked(cache, 'notify-clear-queued') + + cache.markMessageQueued(id) + expect(cache.getSession(id)?.lastNotify?.status).toBe('blocked') + + cache.clearSessionLastNotify(id) + expect(cache.getSession(id)?.lastNotify).toBeNull() + }) + + it('clears when the CLI reports the agent started thinking', () => { + const { cache } = makeCache() + const id = seedBlocked(cache, 'notify-clear-alive') + + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: true }) + + expect(cache.getSession(id)?.lastNotify).toBeNull() + }) + + it('keeps the footer while the session stays idle', () => { + const { cache } = makeCache() + const id = seedBlocked(cache, 'notify-keep-idle') + + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: false }) + + expect(cache.getSession(id)?.lastNotify?.status).toBe('blocked') + }) + + it('does not re-clear on every keep-alive of an already-thinking session', () => { + const { cache } = makeCache() + const id = seedBlocked(cache, 'notify-keep-thinking') + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: true }) + + // A footer arriving mid-turn must survive later keep-alives that carry + // no rising edge, or a blocked report would be erased the moment the + // next keep-alive tick lands. + cache.setSessionLastNotify(id, { status: 'blocked', at: Date.now() + 1_000, note: 'still stuck' }) + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: true }) + + expect(cache.getSession(id)?.lastNotify?.status).toBe('blocked') + }) +}) + +describe('footer timestamp boundary on the live path (#1717)', () => { + it('rejects a delayed footer stamped before the operator reply', () => { + // `clearSessionLastNotify` nulls `last_notify_at`, so the store's + // monotonic check has nothing to compare against, and Claude replays + // keep their original timestamps. The turn that cleared it is the + // boundary — anything older was answered by the prompt that started it. + const { cache } = makeCache() + const id = seedBlocked(cache, 'notify-boundary') + const beforeReply = Date.now() - 60_000 + + cache.markMessageQueued(id) + cache.clearSessionLastNotify(id) + expect(cache.getSession(id)?.lastNotify).toBeNull() + + cache.setSessionLastNotify(id, { status: 'blocked', at: beforeReply, note: 'stale replay' }) + + expect(cache.getSession(id)?.lastNotify ?? null).toBeNull() + }) + + it('rejects a delayed footer that arrives after the reply turn ended', () => { + // The gap the earlier `activeTurnStartedAt` version missed: that field + // resets when the agent goes idle, so once the turn ends both it and + // `last_notify_at` are null and the stale footer was accepted. The + // persisted clear watermark has to outlive the turn. + const { cache } = makeCache() + const id = seedBlocked(cache, 'notify-boundary-after-turn') + const beforeReply = Date.now() - 60_000 + + cache.markMessageQueued(id) + cache.clearSessionLastNotify(id) + // Turn ends; agent goes idle without emitting another footer. + cache.handleSessionEnd({ sid: id, time: Date.now() }) + + cache.setSessionLastNotify(id, { status: 'blocked', at: beforeReply, note: 'stale replay' }) + + expect(cache.getSession(id)?.lastNotify ?? null).toBeNull() + }) + + it('still accepts a footer from the current turn', () => { + const { cache } = makeCache() + const id = seedBlocked(cache, 'notify-boundary-live') + + cache.markMessageQueued(id) + cache.clearSessionLastNotify(id) + cache.setSessionLastNotify(id, { status: 'blocked', at: Date.now() + 1_000, note: 'stuck again' }) + + expect(cache.getSession(id)?.lastNotify?.note).toBe('stuck again') + }) +}) + +describe('importing a transcript does not reopen an answered blocker (#1717)', () => { + it('derives the blocker from the imported conversation, not from import-time arrival', async () => { + // An import replays historical rows through live ingestion, which is + // the wrong shape twice over: the imported reply never passes through + // the CLI delivery callback, so nothing clears the footer it answered; + // and every imported row is stamped with the SAME hub arrival (import + // time) while imported replies keep their historical invocation times, + // so arrival cannot order them either. The conversation entered Blocked + // on a footer its own transcript answers. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'import-answered', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const historical = Date.now() - 86_400_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needed a key' }) + + // The transcript: blocked footer, the operator's reply, then an + // assistant turn carrying no footer at all. + // Written exactly as the importer writes them — `addImportedMessage`, + // not `addMessage`. Using the live insert here modelled an import that + // does not exist: it stamps arrival at `now` while the importer stamps + // the transcript's own time, which is the whole distinction the + // reconciliation turns on. + const rows = [ + store.messages.addImportedMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, 'imported-footer', historical).message, + store.messages.addImportedMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here is the key' }, + meta: { sentFrom: 'webapp' } + }, 'imported-reply', historical + 1_000).message, + store.messages.addImportedMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: 'All done.' }] } } + } + }, 'imported-tail', historical + 2_000).message + ] + + // Replayed through live ingestion exactly as the importer does. + for (const message of rows) { + engine.handleRealtimeEvent({ + type: 'message-received', + sessionId: session.id, + message: { + id: message.id, + seq: message.seq, + localId: message.localId, + content: message.content, + createdAt: message.createdAt, + receivedAt: message.receivedAt, + invokedAt: message.invokedAt + } + }) + } + // Live ingestion alone leaves the answered footer standing. + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + }) + + it('does not reopen an answered imported blocker when a rewind retains it', async () => { + // The reviewer's sequence: import (footer, reply, footerless reply), + // resume, send another prompt, then rewind to that prompt so the + // imported prefix survives. Rewind reconciliation re-derives from the + // retained transcript — and an imported row used to carry the + // transcript's time in `invoked_at` but IMPORT time in `received_at`, + // so the imported footer looked newer than the imported reply that + // answered it and the replacement write reopened the blocker. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'import-then-rewind', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const historical = Date.now() - 86_400_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needed a key' }) + + // Imported prefix, written the way the importer writes it. + store.messages.addImportedMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, 'imported-footer', historical) + store.messages.addImportedMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here is the key' }, + meta: { sentFrom: 'webapp' } + }, 'imported-reply', historical + 1_000) + store.messages.addImportedMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: 'All done.' }] } } + } + }, 'imported-tail', historical + 2_000) + + // What the rewind reconciliation does with the retained prefix. + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + }) + + it('keeps an unanswered footer when the import has no timestamps at all', async () => { + // A Codex Desktop transcript carries no per-message timestamps, so the + // importer stamps every row with the same import time. Comparing + // arrival alone then made the transcript's FINAL message — an + // unanswered blocked footer — compare equal to the prompt that started + // it and read as already answered, so the conversation went missing + // from Blocked entirely. Native transcript order breaks the tie. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'import-no-timestamps', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const importedAt = Date.now() + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a decision' }) + + // Prompt first, then the footer — same timestamp, order carried by seq. + store.messages.addImportedMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'off you go' }, + meta: { sentFrom: 'webapp' } + }, 'codex-prompt', importedAt) + store.messages.addImportedMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, 'codex-footer', importedAt) + + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + expect(engine.getSession(session.id)?.lastNotify?.note).toBe('needs a decision') + }) + + it('keeps the final blocker of a MULTI-TURN untimestamped import', async () => { + // Two turns, no timestamps anywhere: the importer stamps every row + // identically. The first turn's footer then sets an author cutoff + // EQUAL to the final footer's author time, and an at-or-older + // comparison discarded a blocker that is both unanswered and the last + // thing in the transcript. Where the author clock cannot discriminate, + // position already has. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'import-two-turns', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const importedAt = Date.now() + const footerText = (status: string, summary: string) => 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status, summary }) + const agent = (text: string) => ({ + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text }] } } + } + }) + + // Turn one: blocked, then answered. + store.messages.addImportedMessage(session.id, agent(footerText('blocked', 'turn one')), 'f1', importedAt) + store.messages.addImportedMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'webapp' } + }, 'p1', importedAt) + // Turn two: the operator prompts again, and it ends blocked. + store.messages.addImportedMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'now this' }, + meta: { sentFrom: 'webapp' } + }, 'p2', importedAt) + store.messages.addImportedMessage(session.id, agent(footerText('blocked', 'turn two')), 'f2', importedAt) + + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + expect(engine.getSession(session.id)?.lastNotify?.note).toBe('turn two') + }) + + it('keeps the final blocker when both turns report the SAME footer text', async () => { + // The round-14 identity check keyed on the footer's text, and an + // untimestamped import gives every row one timestamp — so two distinct + // turns reporting the same status and note collapsed to one identity + // and the second was discarded as a replay. My own multi-turn test + // used different notes, so it could not see this. An imported row + // carries the transcript's message id, which says they are two + // different messages however identical their text. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'import-identical-footers', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const importedAt = Date.now() + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + const agent = () => ({ + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }) + + store.messages.addImportedMessage(session.id, agent(), 'f1', importedAt) + store.messages.addImportedMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'webapp' } + }, 'p1', importedAt) + // Identical text to the first footer, but a different turn. + store.messages.addImportedMessage(session.id, agent(), 'f2', importedAt) + + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + }) + + it('rejects an EXACT replay of an answered footer on rewind', async () => { + // Claude transcript rows keep their author timestamp and arrive with + // no outer local id, so the same footer can be stored a second time + // after the reply that answered it. Live ingestion refuses it on the + // equal author timestamp — but making the reconciliation comparison + // strict (so untimestamped imports could work at all) meant an equal + // author time now PASSED there. Identity is what separates the two: a + // replay is the same status, note and timestamp as something already + // superseded; a new footer in an untimestamped import is not. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'rewind-exact-replay', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const base = Date.now() - 600_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + const agentFooter = () => ({ + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }) + + store.messages.addMessage(session.id, agentFooter(), undefined, null, base, base) + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'webapp' } + }, 'reply-1', null, base + 1_000, base + 1_000) + store.messages.markMessagesInvoked(session.id, ['reply-1'], base + 2_000) + // The SAME footer stored again, after the reply. + store.messages.addMessage(session.id, agentFooter(), undefined, null, base, base + 3_000) + + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + }) + + it('uses hub arrival for a LOCAL reply, whose invokedAt is the runner clock', async () => { + // A prompt typed straight into a local Claude terminal never went + // through the hub queue, so it has no local id and `invoked_at` is the + // transcript's own clock. Measuring that against a footer's hub + // arrival is the cross-clock comparison this area exists to avoid: on + // a slow-enough runner a LATER local reply sorted before an EARLIER + // footer's arrival, and a rewind retaining both restored a blocker the + // operator had already answered. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'rewind-local-reply', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const hubNow = Date.now() + const RUNNER_BEHIND = 3_600_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + + // Footer: arrived at the hub an hour ago by the hub's clock. + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, hubNow - RUNNER_BEHIND, hubNow - 60_000) + // Local reply, answering it: no localId, so its invokedAt is the + // runner's clock and reads as an hour BEFORE the footer's arrival. + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'cli' } + }, undefined, null, hubNow - RUNNER_BEHIND + 1_000, hubNow) + + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + }) + + it('persists the replay cutoff across a rewind, so a late footer still cannot return', async () => { + // Reconciliation computes an author cutoff from the retained history, + // and the replacement write used to reset it to null. A footer from + // the retained, already-answered turn that reaches the hub for the + // FIRST time after the rewind then arrives fresh, so arrival cannot + // reject it and only the cutoff can. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'rewind-cutoff', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const base = Date.now() - 600_000 + const footerText = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'original' }) + + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } + } + }, undefined, null, base, base) + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'webapp' } + }, 'reply-1', null, base + 1_000, base + 1_000) + store.messages.markMessagesInvoked(session.id, ['reply-1'], base + 2_000) + + // The rewind retains the footer and the reply that answered it. + engine.reconcileNotifySignalAfterImport(session.id) + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + const row = store.sessions.getSessionByNamespace(session.id, 'default') + expect(row?.lastNotifyClearedAuthorAt).toBe(base) + + // A footer from that answered turn, arriving only now. + engine.getSession(session.id) + engine.handleRealtimeEvent({ + type: 'message-received', + sessionId: session.id, + message: { + id: 'late-1', + seq: 99, + localId: null, + createdAt: base - 5_000, + receivedAt: Date.now(), + content: { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } + } + } + } + }) + + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + }) + + it('does not restore, on rewind, a replay that live ingestion rejected', async () => { + // Live ingestion rejects an older footer replay using the author time + // of the footer the reply superseded — but that cutoff is SESSION + // state, so a derivation reading only the transcript cannot see it. + // Rewind retaining both the reply and the replay therefore handed the + // replay back as the blocker, reopening an answered turn. The + // transcript carries the equivalent: a footer that arrived before the + // reply belongs to a turn the reply superseded, so nothing authored at + // or before it can be current. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'rewind-replay', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const base = Date.now() - 600_000 + const footerAt = (at: number, summary: string) => 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary }) + + // The agent blocked, and the operator answered. + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerAt(base, 'original') }] } } + } + }, undefined, null, base, base) + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'webapp' } + }, 'reply-1', null, base + 1_000, base + 1_000) + store.messages.markMessagesInvoked(session.id, ['reply-1'], base + 2_000) + // A delayed replay of that same, already-answered turn: authored + // BEFORE the original footer, but reaching the hub after the reply. + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerAt(base, 'stale replay') }] } } + } + }, undefined, null, base - 5_000, base + 3_000) + + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + }) + + it('keeps a genuinely unanswered footer from an imported transcript', async () => { + // Positive control: reconciliation must not simply wipe the signal. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'import-unanswered', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const historical = Date.now() - 86_400_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'still needs a key' }) + + // Reply FIRST, then the agent blocks and nobody answers. + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'off you go' }, + meta: { sentFrom: 'webapp' } + }, 'early-reply', null, historical) + store.messages.markMessagesInvoked(session.id, ['early-reply'], historical) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, historical + 1_000) + + engine.reconcileNotifySignalAfterImport(session.id) + + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + expect(engine.getSession(session.id)?.lastNotify?.note).toBe('still needs a key') + }) +}) + +describe('cancelling a queued prompt cannot suppress the next blocker (#1717)', () => { + it('ingests a genuine footer after a higher-numbered scheduled prompt is cancelled', () => { + // Insertion `seq` is allocated as MAX(seq)+1, so deleting the + // highest-numbered row frees its number for the next message to reuse. + // Any boundary expressed as a POSITION therefore covers rows that do + // not exist yet: acknowledge prompt A while a future-scheduled prompt B + // holds the top number, cancel B, and the next footer is born beneath + // the boundary and silently rejected — the session never enters + // Blocked. The boundary is a hub timestamp, which deletion cannot + // rewind, so there is nothing here to reuse. + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_event: SyncEvent) => {} } as EventPublisher) + const session = cache.getOrCreateSession( + 'cancel-reuse', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + cache.markSessionActive(session.id) + const now = Date.now() + + // Prompt A, delivered. + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'answer' }, + meta: { sentFrom: 'webapp' } + }, 'prompt-a', null, now - 10_000, now - 10_000) + // Prompt B, scheduled for later, taking the top seq. + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'later' }, + meta: { sentFrom: 'webapp' } + }, 'prompt-b', now + 3_600_000, now - 9_000, now - 9_000) + store.messages.markMessagesInvoked(session.id, ['prompt-a'], now - 8_000) + cache.clearSessionLastNotify(session.id, now - 8_000) + + // B is cancelled, freeing its number. + store.messages.cancelQueuedMessage(session.id, 'prompt-b') + + // The agent then genuinely blocks, and the new row reuses B's number. + cache.setSessionLastNotify(session.id, { + status: 'blocked', at: now - 1_000, note: 'needs a key', receivedAt: now - 1_000 + }) + + expect(cache.getSession(session.id)?.lastNotify?.status).toBe('blocked') + expect(cache.getSession(session.id)?.lastNotify?.note).toBe('needs a key') + }) +}) + +describe('transferBlockedAck across a merge that copies its own messages (#1717)', () => { + it('carries the dismissal onto the canonical session', () => { + // The Codex Desktop duplicate reconciliation copies a duplicate's + // messages into the canonical session and then deletes the source. It + // never transferred the acknowledgement, so a footer the operator had + // already dismissed became the canonical session's latest signal and + // reappeared in Blocked — their decision undone by a merge they never + // asked for. + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_e: SyncEvent) => {} } as EventPublisher) + const duplicate = cache.getOrCreateSession('dup', { path: '/tmp', host: 'h' }, null, 'default') + const canonical = cache.getOrCreateSession('canon', { path: '/tmp', host: 'h' }, null, 'default') + const at = Date.now() + cache.setSessionBlockedAck(duplicate.id, 'handled out of band', at, 'notify:1000') + + cache.transferBlockedAck(duplicate.id, canonical.id, 'default') + + const row = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(row?.blockedAckKeys).toEqual(['notify:1000']) + expect(row?.blockedAckReason).toBe('handled out of band') + }) + + it('unions the two sets rather than replacing either', () => { + // Each side having dismissed a DIFFERENT prompt must not make either + // block again on the merged row. + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_e: SyncEvent) => {} } as EventPublisher) + const duplicate = cache.getOrCreateSession('dup2', { path: '/tmp', host: 'h' }, null, 'default') + const canonical = cache.getOrCreateSession('canon2', { path: '/tmp', host: 'h' }, null, 'default') + const at = Date.now() + cache.setSessionBlockedAck(duplicate.id, 'theirs', at - 1_000, 'request:a') + cache.setSessionBlockedAck(canonical.id, 'ours', at, 'request:b') + + cache.transferBlockedAck(duplicate.id, canonical.id, 'default') + + const keys = store.sessions.getSessionByNamespace(canonical.id, 'default')?.blockedAckKeys ?? [] + expect([...keys].sort()).toEqual(['request:a', 'request:b']) + }) + + it('carries arrival and delivery across a message copy, so the pair stays ordered', () => { + // The duplicate merge copies a footer AND the reply that answered it. + // Re-stamping arrival at copy time made every copied row look like it + // reached the hub now, so the footer no longer sat before its answer — + // and with the copied reply never passing through the delivery + // callback, the canonical row entered Blocked on a footer its own + // combined transcript answers. + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_e: SyncEvent) => {} } as EventPublisher) + const session = cache.getOrCreateSession('copy-order', { path: '/tmp', host: 'h' }, null, 'default') + const base = Date.now() - 600_000 + + const copied = store.messages.copyMessageToSession(session.id, { + content: { role: 'user', content: { type: 'text', text: 'here you go' }, meta: { sentFrom: 'webapp' } }, + createdAt: base, + localId: null, + invokedAt: base + 1_000, + scheduledAt: null, + deliveryState: undefined, + receivedAt: base, + agentDelivered: 1 + }) + + expect(copied.receivedAt).toBe(base) + expect(copied.agentDelivered).toBe(1) + }) + + it('falls back to createdAt when copying history written before the column existed', () => { + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_e: SyncEvent) => {} } as EventPublisher) + const session = cache.getOrCreateSession('copy-legacy', { path: '/tmp', host: 'h' }, null, 'default') + const base = Date.now() - 600_000 + + const copied = store.messages.copyMessageToSession(session.id, { + content: { role: 'user', content: { type: 'text', text: 'old' }, meta: { sentFrom: 'webapp' } }, + createdAt: base, + localId: null, + invokedAt: base, + scheduledAt: null, + deliveryState: undefined + }) + + expect(copied.receivedAt).toBe(base) + }) + + it('is a no-op when the source never dismissed anything', () => { + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_e: SyncEvent) => {} } as EventPublisher) + const duplicate = cache.getOrCreateSession('dup3', { path: '/tmp', host: 'h' }, null, 'default') + const canonical = cache.getOrCreateSession('canon3', { path: '/tmp', host: 'h' }, null, 'default') + cache.setSessionBlockedAck(canonical.id, 'ours', Date.now(), 'request:b') + + cache.transferBlockedAck(duplicate.id, canonical.id, 'default') + + expect(store.sessions.getSessionByNamespace(canonical.id, 'default')?.blockedAckKeys) + .toEqual(['request:b']) + }) +}) + +describe('merges share one rule for when a reply reached the agent (#1717)', () => { + it('answers a destination footer with a LOCAL source reply on a slow runner', async () => { + // The transcript derivation learned to use hub arrival for a reply + // with no local id; the merge path kept its own copy of the rule and + // did not. A slow runner then gave that local reply an `invoked_at` + // earlier than the footer's hub arrival, so the merge moved the + // answering reply into the destination transcript and left the row + // blocked anyway. + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_e: SyncEvent) => {} } as EventPublisher) + const source = cache.getOrCreateSession('local-src', { path: '/tmp', host: 'h' }, null, 'default') + const target = cache.getOrCreateSession('local-dst', { path: '/tmp', host: 'h' }, null, 'default') + const hubNow = Date.now() + const RUNNER_BEHIND = 3_600_000 + + cache.setSessionLastNotify(target.id, { + status: 'blocked', at: hubNow - RUNNER_BEHIND, note: 'needs a key', + receivedAt: hubNow - 60_000 + }) + // Local reply on the source: no localId, so `invoked_at` is the + // runner's clock and reads an hour before the footer's hub arrival. + store.messages.addMessage(source.id, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'cli' } + }, undefined, null, hubNow - RUNNER_BEHIND + 1_000, hubNow) + + await cache.mergeSessionHistory(source.id, target.id, 'default') + + expect(cache.getSession(target.id)?.lastNotify ?? null).toBeNull() + }) +}) + +describe('a maintenance turn does not invalidate the footer (#1717)', () => { + it('keeps the blocker when thinking starts for maintenance, and clears on the next real turn', () => { + // A scheduled /compact can reach an IDLE OpenCode session, and the + // launcher sends thinking=true before compaction starts. The + // maintenance acknowledgement preserved the footer, and then this + // keepalive deleted it anyway — so when compaction ended without a new + // status summary the session stayed out of Blocked with nothing having + // answered it. + const { cache } = makeCache() + const id = seedBlocked(cache, 'maintenance-turn') + + cache.markMaintenanceTurn(id) + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: true }) + expect(cache.getSession(id)?.lastNotify?.status).toBe('blocked') + + // The mark is consumed, so a genuine prompt turn still clears. + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: false }) + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: true }) + expect(cache.getSession(id)?.lastNotify ?? null).toBeNull() + }) + + it('never confirms a maintenance turn, even across a second tick of the same turn (cold-review round 23)', () => { + // The footer surviving in STORAGE (asserted above) is necessary but + // not sufficient: `thinkingConfirmed` drives whether the WEB hides + // the chip while `thinking` is true. Confirming it during compaction + // hid the same still-unanswered footer, and unhiding it when + // compaction ended made the arrival tracker read it as a brand-new + // blocker. `maintenanceTurnSessionIds` is a ONE-SHOT mark consumed on + // the first tick, so a naive fix that only checks it on the rising + // edge would correctly protect tick one and then confirm tick two — + // OpenCode can send `thinking: true` more than once while /compact + // runs. + const { cache } = makeCache() + const id = seedBlocked(cache, 'maintenance-turn-confirmed') + + cache.markMaintenanceTurn(id) + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: true }) + expect(cache.getSession(id)?.thinkingConfirmed).toBe(false) + + // Second tick, same turn: still thinking, no new mark to consume. + cache.handleSessionAlive({ sid: id, time: Date.now() + 1, thinking: true }) + expect(cache.getSession(id)?.thinkingConfirmed).toBe(false) + + // Compaction ends; the NEXT genuine turn confirms normally. + cache.handleSessionAlive({ sid: id, time: Date.now() + 2, thinking: false }) + cache.handleSessionAlive({ sid: id, time: Date.now() + 3, thinking: true }) + expect(cache.getSession(id)?.thinkingConfirmed).toBe(true) + }) + + it('never confirms an IMMEDIATE /compact sent through the ordinary queue path (cold-review round 24)', () => { + // Sending /compact as an ordinary message (e.g. from HAPI itself, + // rather than OpenCode scheduling it internally) queues it first — + // `markMessageQueued` flips `thinking` true and `thinkingConfirmed` + // false BEFORE the CLI ever acknowledges it is maintenance. By the + // time `markMaintenanceTurn` arrives, there is no `!wasThinking` + // rising edge left for the round-23 fix to catch — thinking was + // already true. The first genuine keepalive that follows would + // then confirm the turn and hide the footer, exactly the bug round + // 23 fixed, just reached through a different sequencing. + const { cache } = makeCache() + const id = seedBlocked(cache, 'immediate-compact') + + cache.markMessageQueued(id) + expect(cache.getSession(id)?.thinking).toBe(true) + expect(cache.getSession(id)?.thinkingConfirmed).toBe(false) + + // The CLI's ack that this queued command is maintenance arrives + // AFTER thinking already rose. + cache.markMaintenanceTurn(id) + expect(cache.getSession(id)?.thinkingConfirmed).toBe(false) + + // The CLI's first genuine keepalive for the compaction itself. + cache.handleSessionAlive({ sid: id, time: Date.now(), thinking: true }) + expect(cache.getSession(id)?.thinkingConfirmed).toBe(false) + expect(cache.getSession(id)?.lastNotify?.status).toBe('blocked') + + // Compaction ends; the NEXT genuine turn still confirms normally. + cache.handleSessionAlive({ sid: id, time: Date.now() + 1, thinking: false }) + cache.handleSessionAlive({ sid: id, time: Date.now() + 2, thinking: true }) + expect(cache.getSession(id)?.thinkingConfirmed).toBe(true) + }) +}) + +describe('notify revision is whatever SQLite says (#1717)', () => { + it('never broadcasts a revision the row does not hold', () => { + // The browser orders notify/ack payloads by `notifyUpdatedAt`, so the + // hub must have exactly one counter. SQLite versions a clear off the + // *boundary* timestamp — the answering message's clock, usually well in + // the past — while this path used to invent `Date.now()`. The patch + // then outran the row, and the next refresh looked older than a payload + // the browser had already applied, so it was dropped. In a merge that + // dropped payload is the one carrying the transferred dismissal, and a + // row the operator had marked unblocked went back to blocked. + const store = new Store(':memory:') + const emitted: SyncEvent[] = [] + const cache = new SessionCache(store, { emit: (event: SyncEvent) => { emitted.push(event) } } as EventPublisher) + const id = seedBlocked(cache, 'notify-revision') + + emitted.length = 0 + // The two counters only diverge once the clock has moved since the + // footer was stored: SQLite then advances the row by one from its own + // value while a now-based bump jumps the whole elapsed interval ahead. + // Any real gap between an agent reporting blocked and the operator + // answering is enormously longer than this. + const until = Date.now() + 3 + while (Date.now() < until) { /* advance the clock deterministically */ } + + // A reply delivered an hour ago: the boundary SQLite versions the + // clear from is in the past, so the row cannot reach hub-now. + cache.clearSessionLastNotify(id, Date.now() - 3_600_000) + + const row = store.sessions.getSessionByNamespace(id, 'default') + const patch = emitted + .filter((event) => event.type === 'session-updated') + .map((event) => (event as { data: { notifyUpdatedAt?: number } }).data) + .at(-1) + expect(row?.lastNotifyUpdatedAt).toBeGreaterThan(0) + expect(patch?.notifyUpdatedAt).toBe(row!.lastNotifyUpdatedAt!) + expect(cache.getSession(id)?.notifyUpdatedAt).toBe(row!.lastNotifyUpdatedAt!) + }) +}) + +describe('the acknowledgement broadcast stays inside its own schema (#1717)', () => { + it('publishes the persisted, bounded key set on the (limit+1)th distinct dismissal', () => { + // The cache keeps dismissal keys after their prompts resolve, so a + // long-lived session reaches the bound. SQLite trims there; the + // broadcast did not, so it carried one key over the schema's own + // limit and the web rejected the whole session — other tabs silently + // missed the live dismissal. + const store = new Store(':memory:') + const emitted: SyncEvent[] = [] + const cache = new SessionCache(store, { + emit: (event: SyncEvent) => { emitted.push(event) } + } as EventPublisher) + const session = cache.getOrCreateSession( + 'ack-bound', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + + for (let i = 0; i < ACK_KEYS_RETENTION_LIMIT + 1; i++) { + cache.setSessionBlockedAck(session.id, 'handled', Date.now() + i, `request:r${i}`) + } + + const row = store.sessions.getSessionByNamespace(session.id, 'default') + const last = emitted + .filter((event) => event.type === 'session-updated') + .map((event) => (event as { data: { blockedAck?: { keys?: string[] | null } } }).data) + .at(-1) + + expect(row?.blockedAckKeys).toHaveLength(ACK_KEYS_RETENTION_LIMIT) + expect(last?.blockedAck?.keys).toHaveLength(ACK_KEYS_RETENTION_LIMIT) + // And it is the SAME bounded set the row holds, not merely the same size. + expect(last?.blockedAck?.keys).toEqual(row?.blockedAckKeys ?? []) + expect(cache.getSession(session.id)?.blockedAck?.keys).toEqual(row?.blockedAckKeys ?? []) + }) + + it('never evicts a dismissal whose request is still pending, even when the limit\'s worth of later ones arrive (cold-review round 21)', () => { + // The bound used to keep "the newest N" by position alone. An OLD + // dismissal whose request stayed open through N later, already- + // resolved dismissals got evicted on position, and the web then + // presented that still-open, already-dismissed request as blocked + // again — a store bug, not a stale cache: the key was genuinely gone. + const store = new Store(':memory:') + const emitted: SyncEvent[] = [] + const cache = new SessionCache(store, { + emit: (event: SyncEvent) => { emitted.push(event) } + } as EventPublisher) + const session = cache.getOrCreateSession( + 'ack-bound-live', + { path: '/tmp/project', host: 'localhost' }, + // Five requests that stay open through every later dismissal below. + { requests: { + r0: { tool: 'Bash', arguments: {} }, + r1: { tool: 'Bash', arguments: {} }, + r2: { tool: 'Bash', arguments: {} }, + r3: { tool: 'Bash', arguments: {} }, + r4: { tool: 'Bash', arguments: {} } + }, completedRequests: {} }, + 'default' + ) + + // Dismiss the five still-open requests first (oldest), then enough + // more — whose requests are NOT in agentState, already resolved by + // the time they were dismissed — to land one over the bound. + const total = ACK_KEYS_RETENTION_LIMIT + 1 + for (let i = 0; i < 5; i++) { + cache.setSessionBlockedAck(session.id, 'handled', Date.now() + i, `request:r${i}`) + } + for (let i = 5; i < total; i++) { + cache.setSessionBlockedAck(session.id, 'handled', Date.now() + i, `request:r${i}`) + } + + const row = store.sessions.getSessionByNamespace(session.id, 'default') + const keys = row?.blockedAckKeys ?? [] + + expect(keys).toHaveLength(ACK_KEYS_RETENTION_LIMIT) + // Every still-open request survives regardless of how old its + // dismissal is. + for (let i = 0; i < 5; i++) { + expect(keys).toContain(`request:r${i}`) + } + // Budget for resolved keys is (limit - 5), so only the OLDEST + // resolved dismissal (r5) is evicted to make room — not a live one. + expect(keys).not.toContain('request:r5') + for (let i = 6; i < total; i++) { + expect(keys).toContain(`request:r${i}`) + } + + const last = emitted + .filter((event) => event.type === 'session-updated') + .map((event) => (event as { data: { blockedAck?: { keys?: string[] | null } } }).data) + .at(-1) + expect(last?.blockedAck?.keys).toEqual(keys) + }) + + it('keeps a full-session snapshot inside its own schema when 65 live dismissals are all still pending (cold-review round 22)', () => { + // Round 21 never evicted a LIVE key, but also never capped how many + // live keys could pile up — with 65 requests simultaneously pending + // and dismissed, the old 64-key schema bound rejected the whole + // snapshot even though every key was genuinely live and correctly + // preserved. The fix raises the schema bound to match the system's + // own ceiling on pending-request identities, not the retention + // budget for RESOLVED keys. + const store = new Store(':memory:') + const emitted: SyncEvent[] = [] + const cache = new SessionCache(store, { + emit: (event: SyncEvent) => { emitted.push(event) } + } as EventPublisher) + const requests: Record }> = {} + for (let i = 0; i < 65; i++) { + requests[`r${i}`] = { tool: 'Bash', arguments: {} } + } + const session = cache.getOrCreateSession( + 'ack-bound-all-live', + { path: '/tmp/project', host: 'localhost' }, + { requests, completedRequests: {} }, + 'default' + ) + + for (let i = 0; i < 65; i++) { + cache.setSessionBlockedAck(session.id, 'handled', Date.now() + i, `request:r${i}`) + } + + const row = store.sessions.getSessionByNamespace(session.id, 'default') + const keys = row?.blockedAckKeys ?? [] + + // All 65 survive — none evicted, because all 65 are live — and the + // count stays comfortably inside SessionBlockedAckSchema's bound. + expect(keys).toHaveLength(65) + for (let i = 0; i < 65; i++) { + expect(keys).toContain(`request:r${i}`) + } + expect(() => SessionBlockedAckSchema.parse({ at: Date.now(), reason: 'handled', keys })).not.toThrow() + }) + + it('keeps a full-session snapshot inside its own schema when the footer shares the live dismissal budget (cold-review round 23)', () => { + // PENDING_REQUEST_REFS_CAP (200) alone forgot that a dismissal can + // ALSO cover the current footer, which is a separate live key + // (`notify:`) from any of the up-to-200 request keys. 200 live + // request dismissals plus one live footer dismissal is 201 keys, + // every one of them genuinely live — the fix bounds both the + // retention limit and the schema at that true ceiling instead. + const store = new Store(':memory:') + const emitted: SyncEvent[] = [] + const cache = new SessionCache(store, { + emit: (event: SyncEvent) => { emitted.push(event) } + } as EventPublisher) + const requests: Record }> = {} + for (let i = 0; i < 200; i++) { + requests[`r${i}`] = { tool: 'Bash', arguments: {} } + } + const session = cache.getOrCreateSession( + 'ack-bound-footer-plus-requests', + { path: '/tmp/project', host: 'localhost' }, + { requests, completedRequests: {} }, + 'default' + ) + const footerAt = Date.now() + cache.setSessionLastNotify(session.id, { status: 'blocked', at: footerAt, note: 'needs creds' }) + + cache.setSessionBlockedAck(session.id, 'handled', footerAt, `notify:${footerAt}`) + for (let i = 0; i < 200; i++) { + cache.setSessionBlockedAck(session.id, 'handled', Date.now() + i, `request:r${i}`) + } + + const row = store.sessions.getSessionByNamespace(session.id, 'default') + const keys = row?.blockedAckKeys ?? [] + + // All 201 survive — the footer key is just as live as any request + // key, so none is evicted — and the count still validates against + // SessionBlockedAckSchema. + expect(keys).toHaveLength(201) + expect(keys).toContain(`notify:${footerAt}`) + for (let i = 0; i < 200; i++) { + expect(keys).toContain(`request:r${i}`) + } + expect(() => SessionBlockedAckSchema.parse({ at: Date.now(), reason: 'handled', keys })).not.toThrow() + }) + + it('keeps a full-session snapshot inside its own schema at 202 live dismissals, past the OLD 201 cap (cold-review round 24)', () => { + // `PENDING_REQUEST_REFS_CAP` (200) is a preview cap on what one + // summary SURFACES, not a ceiling on how many requests + // `AgentState.requests` can actually hold at once — it has no + // enforced max. Sizing round 23's fix at `PENDING_REQUEST_REFS_CAP + + // 1` (for the footer) treated the preview cap as if it WERE that + // ceiling, so 202 simultaneously pending-and-dismissed requests — + // one more than the 201 it allowed — broke the exact same way again. + // There is no footer in this repro at all; 202 request keys alone + // are enough. + const store = new Store(':memory:') + const emitted: SyncEvent[] = [] + const cache = new SessionCache(store, { + emit: (event: SyncEvent) => { emitted.push(event) } + } as EventPublisher) + const requests: Record }> = {} + for (let i = 0; i < 202; i++) { + requests[`r${i}`] = { tool: 'Bash', arguments: {} } + } + const session = cache.getOrCreateSession( + 'ack-bound-202-live', + { path: '/tmp/project', host: 'localhost' }, + { requests, completedRequests: {} }, + 'default' + ) + + for (let i = 0; i < 202; i++) { + cache.setSessionBlockedAck(session.id, 'handled', Date.now() + i, `request:r${i}`) + } + + const row = store.sessions.getSessionByNamespace(session.id, 'default') + const keys = row?.blockedAckKeys ?? [] + + expect(keys).toHaveLength(202) + for (let i = 0; i < 202; i++) { + expect(keys).toContain(`request:r${i}`) + } + expect(() => SessionBlockedAckSchema.parse({ at: Date.now(), reason: 'handled', keys })).not.toThrow() + }) + + it('never exceeds the cap no matter how far past it live dismissals go (cold-review round 25)', () => { + // Round 22 picked 65, round 23 picked 201, round 24 picked 2000 — + // each derived (or re-derived) from one specific repro instead of + // from the actual invariant. `AgentState.requests` has no enforced + // limit, so any fixed number eventually meets a real case one key + // over it — picking a bigger number just relocates the N+1 failure. + // The fix is structural: once every resolved key is already gone, + // `serialiseAckKeys` now evicts the oldest LIVE ones too instead of + // growing past the bound. Proven here at a scale (limit + 500) well + // beyond anything a "round up" patch would plausibly guess next. + const store = new Store(':memory:') + const cache = new SessionCache(store, { emit: (_event: SyncEvent) => {} } as EventPublisher) + const total = ACK_KEYS_RETENTION_LIMIT + 500 + const session = cache.getOrCreateSession( + 'ack-bound-beyond-any-cap', + { path: '/tmp/project', host: 'localhost' }, + { requests: {}, completedRequests: {} }, + 'default' + ) + // `SessionCache.setSessionBlockedAck` rebuilds its live-key set from + // every entry in `agentState.requests` on each call (cold-review + // round 21), so dismissing this many keys one at a time through it + // would cost O(total^2) — an unrelated, pre-existing expense this + // test doesn't need to pay to prove `serialiseAckKeys`'s eviction + // bound. Building the key sets in plain JS and calling the store + // directly exercises the exact function this fix changed, at the + // same scale, in O(total). + const dismissedKeys: string[] = [] + const livePendingKeys = new Set() + for (let i = 0; i < total; i++) { + const key = `request:r${i}` + dismissedKeys.push(key) + livePendingKeys.add(key) + } + store.sessions.setSessionBlockedAck( + session.id, + { at: Date.now(), reason: 'handled', keys: dismissedKeys, livePendingKeys }, + 'default' + ) + + const row = store.sessions.getSessionByNamespace(session.id, 'default') + const keys = row?.blockedAckKeys ?? [] + + // The structural guarantee: never more than the limit, regardless of + // how far past it live dismissals go. + expect(keys.length).toBeLessThanOrEqual(ACK_KEYS_RETENTION_LIMIT) + expect(() => SessionBlockedAckSchema.parse({ at: Date.now(), reason: 'handled', keys })).not.toThrow() + // The newest live dismissals survive; the oldest are what gets + // evicted once there is nothing resolved left to make room with. + expect(keys).toContain(`request:r${total - 1}`) + expect(keys).not.toContain('request:r0') + }) +}) + +describe('a reason-only acknowledgement cannot silently keep a stale key set (#1717 cold-review round 37)', () => { + it('rejects a reason-only request once a keyed dismissal already exists', () => { + const { cache } = makeCache() + const session = cache.getOrCreateSession( + 'reason-only-after-keyed', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + cache.setSessionBlockedAck(session.id, 'first', Date.now(), 'request:r0') + + expect(() => cache.setSessionBlockedAck(session.id, 'second, no key')).toThrow(BlockedAckMissingKeyError) + }) + + it('still accepts a reason-only request when the session has never had a keyed dismissal', () => { + // The legitimate watermark path: no prior keys to guess at, so this + // genuinely means "everything up to now". + const { cache } = makeCache() + const session = cache.getOrCreateSession( + 'reason-only-first-ever', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + + const ack = cache.setSessionBlockedAck(session.id, 'handled out of band', Date.now()) + + expect(ack?.keys ?? null).toBeNull() + expect(cache.getSession(session.id)?.blockedAck?.reason).toBe('handled out of band') + }) + + it('leaves a keyed request unaffected by the new rejection', () => { + const { cache } = makeCache() + const session = cache.getOrCreateSession( + 'keyed-unaffected', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + cache.setSessionBlockedAck(session.id, 'first', Date.now(), 'request:r0') + + const ack = cache.setSessionBlockedAck(session.id, 'second', Date.now(), 'request:r1') + + expect(ack?.keys).toEqual(['request:r0', 'request:r1']) + }) +}) + +describe('blocked acknowledgement across a session merge (#1717)', () => { + function makeSession(cache: SessionCache, tag: string): string { + return cache.getOrCreateSession( + tag, + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ).id + } + + it('carries the source acknowledgement onto the merged row', async () => { + // The merge moves the source's pending requests across with their + // original timestamps. Without the watermark they read as newer than + // nothing and a prompt the operator already dismissed blocks again. + const { cache } = makeCache() + const source = makeSession(cache, 'merge-ack-source') + const target = makeSession(cache, 'merge-ack-target') + const ackAt = Date.now() + cache.setSessionBlockedAck(source, 'handled out of band', ackAt) + + await cache.mergeSessionHistory(source, target, 'default') + + expect(cache.getSession(target)?.blockedAck?.at).toBe(ackAt) + expect(cache.getSession(target)?.blockedAck?.reason).toBe('handled out of band') + }) + + it('carries the blocked footer onto the merged row', async () => { + // `mergeSessionMessages` moves the blocked turn across but replays no + // `message-added`, so nothing re-derives the signal on the target: the + // conversation would keep the unanswered footer in its transcript and + // still vanish from the Blocked section. + const { cache } = makeCache() + const source = makeSession(cache, 'merge-notify-source') + const target = makeSession(cache, 'merge-notify-target') + const at = Date.now() + cache.setSessionLastNotify(source, { status: 'blocked', at, note: 'needs a key' }) + + await cache.mergeSessionHistory(source, target, 'default') + + expect(cache.getSession(target)?.lastNotify?.status).toBe('blocked') + expect(cache.getSession(target)?.lastNotify?.note).toBe('needs a key') + }) + + it('does not resurrect a footer the destination already answered', async () => { + // The destination's notify is null because `markMessageQueued` cleared + // it when the operator replied — not because it never had one. Copying + // the source's older footer over that would un-answer a blocker. + const { cache, store } = makeCache() + const source = makeSession(cache, 'merge-answered-source') + const target = makeSession(cache, 'merge-answered-target') + const now = Date.now() + cache.setSessionLastNotify(source, { status: 'blocked', at: now - 10_000, note: 'stale' }) + store.messages.addMessage(target, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'webapp' } + }, 'reply-1', null, now) + // Delivered, not merely queued: an uninvoked prompt has not reached + // the agent and must not count as an answer. + store.messages.markMessagesInvoked(target, ['reply-1'], now) + + await cache.mergeSessionHistory(source, target, 'default') + + expect(cache.getSession(target)?.lastNotify ?? null).toBeNull() + }) + + it('finds the answering reply even when it came from the source side', async () => { + // The reply that answered the source's footer is on the SOURCE, and + // `mergeSessionMessages` renumbers every destination row ABOVE every + // source row. A recency-bounded scan of the merged transcript therefore + // reads back nothing but destination chatter, however much of it there + // is, and concludes nothing answered the footer — so it carries a + // blocker onto the merged row that the combined transcript answers. + // Seq order is not time order after a merge, so the scan cannot be + // bounded by seq at all. + const { cache, store } = makeCache() + const source = makeSession(cache, 'merge-scan-source') + const target = makeSession(cache, 'merge-scan-target') + const now = Date.now() + + cache.setSessionLastNotify(source, { status: 'blocked', at: now - 10_000, note: 'stale' }) + store.messages.addMessage(source, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'webapp' } + }, 'source-reply', null, now - 5_000) + store.messages.markMessagesInvoked(source, ['source-reply'], now - 5_000) + + // Enough destination traffic to fill any fixed window on its own. + for (let i = 0; i < 8; i++) { + store.messages.addMessage(target, { + role: 'agent', + content: { type: 'text', text: `working ${i}` } + }, `target-${i}`, null, now - 4_000 + i) + } + + await cache.mergeSessionHistory(source, target, 'default') + + expect(cache.getSession(target)?.lastNotify ?? null).toBeNull() + }) + + it('does not let an EARLIER destination reply answer a newer source footer', async () => { + // `mergeSessionMessages` renumbers every destination row above every + // source row, so position after a merge is synthetic: an earlier + // destination prompt ends up "above" a later source footer and read as + // proof it had answered it, dropping a blocker the merged transcript + // still plainly contains. Hub arrival times are real and comparable + // across both sides, so they say what actually happened. + const { cache, store } = makeCache() + const source = makeSession(cache, 'merge-order-source') + const target = makeSession(cache, 'merge-order-target') + const now = Date.now() + + // Destination prompt delivered FIRST, an hour ago. + store.messages.addMessage(target, { + role: 'user', + content: { type: 'text', text: 'earlier, unrelated' }, + meta: { sentFrom: 'webapp' } + }, 'early-reply', null, now - 3_600_000, now - 3_600_000) + store.messages.markMessagesInvoked(target, ['early-reply'], now - 3_600_000) + + // Source blocked AFTER that, and nobody has answered it. + cache.setSessionLastNotify(source, { + status: 'blocked', at: now - 60_000, note: 'needs a key', receivedAt: now - 60_000 + }) + + await cache.mergeSessionHistory(source, target, 'default') + + expect(cache.getSession(target)?.lastNotify?.status).toBe('blocked') + expect(cache.getSession(target)?.lastNotify?.note).toBe('needs a key') + }) + + it('still lets a LATER destination reply answer the source footer', async () => { + // The other direction, so the test above cannot pass on a merge that + // simply never clears anything. + const { cache, store } = makeCache() + const source = makeSession(cache, 'merge-order-source-2') + const target = makeSession(cache, 'merge-order-target-2') + const now = Date.now() + + cache.setSessionLastNotify(source, { + status: 'blocked', at: now - 60_000, note: 'needs a key', receivedAt: now - 60_000 + }) + // Delivered after the footer arrived: a genuine answer. + store.messages.addMessage(target, { + role: 'user', + content: { type: 'text', text: 'here you go' }, + meta: { sentFrom: 'webapp' } + }, 'late-reply', null, now - 30_000, now - 30_000) + store.messages.markMessagesInvoked(target, ['late-reply'], now - 30_000) + + await cache.mergeSessionHistory(source, target, 'default') + + expect(cache.getSession(target)?.lastNotify ?? null).toBeNull() + }) + + it('keeps the newer footer when both rows have one', async () => { + const { cache } = makeCache() + const source = makeSession(cache, 'merge-notify-old') + const target = makeSession(cache, 'merge-notify-new') + const now = Date.now() + cache.setSessionLastNotify(source, { status: 'blocked', at: now - 10_000, note: 'older' }) + cache.setSessionLastNotify(target, { status: 'blocked', at: now, note: 'newer' }) + + await cache.mergeSessionHistory(source, target, 'default') + + expect(cache.getSession(target)?.lastNotify?.note).toBe('newer') + }) + + it('keeps the newer acknowledgement when both rows have one', async () => { + const { cache } = makeCache() + const source = makeSession(cache, 'merge-ack-older-source') + const target = makeSession(cache, 'merge-ack-newer-target') + const now = Date.now() + cache.setSessionBlockedAck(source, 'older', now - 10_000) + cache.setSessionBlockedAck(target, 'newer', now) + + await cache.mergeSessionHistory(source, target, 'default') + + expect(cache.getSession(target)?.blockedAck?.reason).toBe('newer') + }) +}) + +describe('future-scheduled messages leave the blocker alone (#1717)', () => { + it('keeps the footer when a reply is scheduled for later, and clears it on an immediate send', async () => { + // `MessageService.sendMessage` withholds a future-scheduled message + // from the CLI, so the agent has not been given the reply. Clearing + // the footer here would erase a blocker nobody answered — and + // cancelling the schedule would leave it erased. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'scheduled-blocked', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const cache = (engine as unknown as { sessionCache: SessionCache }).sessionCache + cache.markSessionActive(session.id) + + const seed = () => cache.setSessionLastNotify( + session.id, + { status: 'blocked', at: Date.now(), note: 'needs a decision' } + ) + + seed() + await engine.sendMessage(session.id, { text: 'later', scheduledAt: Date.now() + 3_600_000 }) + expect(cache.getSession(session.id)?.lastNotify?.status).toBe('blocked') + + // Control: an immediate send reaches the agent, and the CLI's + // confirmed consumption is what clears the footer. + seed() + await engine.sendMessage(session.id, { text: 'now' }) + engine.clearSessionLastNotifyOnDelivery(session.id) + expect(cache.getSession(session.id)?.lastNotify).toBeNull() + }) +}) + +describe('startup notify backfill (#1717)', () => { + it('does not treat a future-scheduled reply as an answer', async () => { + // `MessageService.sendMessage` withholds a future-scheduled message + // from the agent, so it has answered nothing. Stopping the scan on it + // buries an unanswered footer on restart — the same blind spot the + // live path had at `markMessageQueued`. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-scheduled', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, now - 1_000) + // Queued for an hour from now: the agent has not seen it. + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here is the key' }, + meta: { sentFrom: 'webapp' } + }, 'later-1', now + 3_600_000, now) + + const stamped = await engine.backfillRecentNotifySignals({ now }) + + expect(stamped).toBe(1) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + }) + + it('keeps a blocker whose runner clock predates the prompt that started the turn', async () => { + // The reviewer's scenario: the runner is 30 seconds behind the hub, and + // the turn the operator's prompt started ends blocked 10 seconds in. + // The footer's runner timestamp is therefore 20 seconds BEFORE the + // hub's invocation stamp for the prompt that caused it, so comparing + // the two clocks concludes the prompt answered a footer it actually + // provoked — and the blocker vanishes while sitting in the transcript. + // + // Ordered by position instead: the prompt was delivered at a seq below + // the footer that followed it, so it cannot be its answer. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-skew', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const RUNNER_BEHIND = 30_000 + + // The operator's prompt, delivered now by the hub's clock. + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'go on then' }, + meta: { sentFrom: 'webapp' } + }, 'prompt-1', null, now - 1_000) + store.messages.markMessagesInvoked(session.id, ['prompt-1'], now) + + // The turn it started ends blocked 10s later — but stamped by a runner + // running 30s slow, so it reads as 20s BEFORE the prompt's delivery. + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + // Runner-stamped author time, hub-stamped arrival: it reached the hub + // ten seconds after the prompt was delivered, which is the truth the + // runner's slow clock hides. + }, undefined, null, now + 10_000 - RUNNER_BEHIND, now + 10_000) + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(1) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + }) + + it('pages past the fixed 6-row window to find a footer buried behind trailing sidechain noise (#1717 cold-review round 30)', async () => { + // The fixed-depth scan only ever read the newest 6 rows — a footer + // sitting behind 6+ rows that report neither a status nor a reply + // (sidechain narration, plain tool chatter) sat entirely outside + // that window. The session never backfilled at all, and restarting + // the hub kept re-missing it every time. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-buried-footer', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, now - 10_000, now - 10_000) + // 8 trailing rows that report neither a status nor a reply — + // more than the fixed 6-row window, nothing decisive in any of them. + for (let i = 0; i < 8; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `sidechain note ${i}` }] } } + } + }, undefined, null, now - 9_000 + i * 1_000, now - 9_000 + i * 1_000) + } + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(1) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + }) + + it('does not trust a footer found at an intermediate page until a reply is also in view to rule out a stale replay (#1717 cold-review round 31)', async () => { + // The round 30 fix paged outward until EITHER a footer or a reply + // was found — stopping on the footer alone. A footer found at some + // intermediate depth, with no reply yet in that SAME window, is + // not yet reliable: a genuine Claude replay of an already-answered + // footer (same text, same author time — recognized only by + // CONTENT+time identity, since a live row carries no localId) + // looks identical to a fresh occurrence until the derivation can + // also see the original footer+reply pair that would mark it + // superseded. A window too small to include BOTH the replay and + // the original pair reads the replay as live. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-stale-replay', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footerAuthorAt = now - 40_000 + const footerText = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + + // Original footer, genuinely answered. + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } + } + }, undefined, null, footerAuthorAt, footerAuthorAt) + store.messages.addMessage(session.id, { + role: 'user', content: { type: 'text', text: 'here is the key' }, meta: { sentFrom: 'webapp' } + }, undefined, null, footerAuthorAt + 1_000, footerAuthorAt + 1_000) + + // 23 padding rows: enough that a 24-row scan from the end does not + // reach back to the original footer+reply pair above. + for (let i = 0; i < 23; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `note ${i}` }] } } + } + }, undefined, null, footerAuthorAt + 2_000 + i * 100, footerAuthorAt + 2_000 + i * 100) + } + + // The replay: IDENTICAL text and author time to the original — + // same content+time identity — landing well within a 24-row scan + // from the end, but with nothing else decisive in that window. + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } + } + }, undefined, null, footerAuthorAt, now - 10_000) + + // 7 more padding rows after the replay. + for (let i = 0; i < 7; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `trailing ${i}` }] } } + } + }, undefined, null, now - 9_000 + i * 1_000, now - 9_000 + i * 1_000) + } + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(0) + expect(engine.getSession(session.id)?.lastNotify).toBeNull() + }) + + it('does not trust a found footer just because SOME unrelated reply put a boundary in view, if the window still misses the replay\'s own original pair (#1717 cold-review round 32)', async () => { + // The round 31 fix stopped paging as soon as ANY boundary was + // established, assuming that meant the window had enough context. + // It didn't: an UNRELATED reply can land inside an intermediate + // window (setting `boundaryAt` non-null) while the ORIGINAL + // footer+reply pair that would mark a LATER exact-text replay as + // superseded is still further back, outside that same window. + // Nothing in view supersedes the replay, so it reads as live. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-unrelated-reply-masks-replay', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footerAuthorAt = now - 50_000 + const footerText = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + + // Original footer, genuinely answered. + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } + } + }, undefined, null, footerAuthorAt, footerAuthorAt) + store.messages.addMessage(session.id, { + role: 'user', content: { type: 'text', text: 'here is the key' }, meta: { sentFrom: 'webapp' } + }, undefined, null, footerAuthorAt + 1_000, footerAuthorAt + 1_000) + + // 23 padding rows: enough that a 24-row scan from the end does not + // reach back to the original footer+reply pair above. + for (let i = 0; i < 23; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `note ${i}` }] } } + } + }, undefined, null, footerAuthorAt + 2_000 + i * 100, footerAuthorAt + 2_000 + i * 100) + } + + // An UNRELATED reply, well within a 24-row scan from the end — + // just some other prompt that has nothing to do with the footer. + store.messages.addMessage(session.id, { + role: 'user', content: { type: 'text', text: 'how is it going' }, meta: { sentFrom: 'webapp' } + }, undefined, null, now - 11_000, now - 11_000) + + // The replay: IDENTICAL text and author time to the original, + // landing AFTER the unrelated reply above. + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } + } + }, undefined, null, footerAuthorAt, now - 10_000) + + // 7 more padding rows after the replay. + for (let i = 0; i < 7; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `trailing ${i}` }] } } + } + }, undefined, null, now - 9_000 + i * 1_000, now - 9_000 + i * 1_000) + } + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(0) + expect(engine.getSession(session.id)?.lastNotify).toBeNull() + }) + + it('recovers a footer sitting beyond the 200-row scan cap (#1717 cold-review round 33)', async () => { + // `store.messages.getMessages` never returns more than its own + // 200-row limit no matter how wide a `scanDepth` is requested, so a + // footer followed by more than 200 tool/sidechain rows was + // structurally unreachable by widening the scan window — every + // restart rescanned the same capped suffix and never found it. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-beyond-200-row-cap', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footerAt = now - 300_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, footerAt, footerAt) + for (let i = 0; i < 210; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { type: 'output', data: { type: 'tool_use', data: { tool: 'bash', input: {} } } } + }, undefined, null, footerAt + 1_000 + i * 1_000, footerAt + 1_000 + i * 1_000) + } + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(1) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + }) + + it('does not revive a replay inside the 200-row cap when its original+reply pair sits beyond it (#1717 cold-review round 33)', async () => { + // Same 200-row ceiling as above, other failure direction: a stale + // exact-text replay lands inside the capped window while the + // original footer and the reply that answered it sit beyond row + // 200 — nothing in the capped window supersedes the replay, so it + // read as a brand new live blocker. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-replay-inside-cap-original-beyond', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footerText = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + const originalAt = now - 300_000 + + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } + } + }, undefined, null, originalAt, originalAt) + store.messages.addMessage(session.id, { + role: 'user', content: { type: 'text', text: 'here is the key' }, meta: { sentFrom: 'webapp' } + }, 'reply-1', null, originalAt + 500, originalAt + 500) + store.messages.markMessagesInvoked(session.id, ['reply-1'], originalAt + 1_000) + + for (let i = 0; i < 210; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { type: 'output', data: { type: 'tool_use', data: { tool: 'bash', input: {} } } } + }, undefined, null, originalAt + 2_000 + i * 1_000, originalAt + 2_000 + i * 1_000) + } + + // Same author time as the original (that identity is what makes it + // a replay, not a new occurrence), arriving much later. + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } + } + }, undefined, null, originalAt, now - 1_000) + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(0) + expect(engine.getSession(session.id)?.lastNotify).toBeNull() + }) + + it('recovers a newer source footer the merge shifted to a lower seq than an older destination reply (#1717 cold-review round 34)', async () => { + // `mergeSessionMessages` shifts the destination's existing rows + // ABOVE every incoming source row, so seq no longer tracks real + // arrival order across the merge seam. The idle short-circuit + // above assumed it did: an OLDER destination reply landing inside + // the first small window read as "conclusively idle," even though + // a NEWER, still-unanswered source footer sat just outside it at a + // lower seq. `getMessageEpoch` (bumped by the merge) is what tells + // this scan the shortcut is not safe to trust here. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + + const target = engine.getOrCreateSession('merge-seam-target', { path: '/tmp', host: 'localhost' }, null, 'default') + const source = engine.getOrCreateSession('merge-seam-source', { path: '/tmp', host: 'localhost' }, null, 'default') + const now = Date.now() + + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(source.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } } + }, undefined, null, now - 5_000, now - 5_000) + + store.messages.addMessage(target.id, { + role: 'user', content: { type: 'text', text: 'something unrelated' }, meta: { sentFrom: 'webapp' } + }, 'target-reply', null, now - 50_000, now - 50_000) + store.messages.markMessagesInvoked(target.id, ['target-reply'], now - 50_000) + for (let i = 0; i < 5; i++) { + store.messages.addMessage(target.id, { + role: 'agent', + content: { type: 'output', data: { type: 'tool_use', data: { tool: 'bash', input: {} } } } + }, undefined, null, now - 49_000 + i * 100, now - 49_000 + i * 100) + } + + store.messages.mergeSessionMessages(source.id, target.id) + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(1) + expect(engine.getSession(target.id)?.lastNotify?.status).toBe('blocked') + }) + + it('counts a confirmed queue delivery that collided and lost its localId as answering a footer it followed (#1717 cold-review round 36)', async () => { + // The merge's collision handling clears `local_id` on the SOURCE + // copy to sever its ack path, but preserves its genuinely + // hub-stamped `invoked_at` and `agent_delivered`. Without those + // surviving the clear, the reply ordering helper read the now- + // localId-less row as "never queued" and fell back to its much + // earlier hub-arrival time, leaving a footer it actually answered + // stuck as blocked. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + + const target = engine.getOrCreateSession('collision-confirmed-target', { path: '/tmp', host: 'localhost' }, null, 'default') + const source = engine.getOrCreateSession('collision-confirmed-source', { path: '/tmp', host: 'localhost' }, null, 'default') + const now = Date.now() + const footerAt = now - 10_000 + + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(target.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } } + }, undefined, null, footerAt, footerAt) + // Destination's own copy of the colliding local id: still queued, + // never delivered on its own. + store.messages.addMessage(target.id, { + role: 'user', content: { type: 'text', text: 'here is the key' }, meta: { sentFrom: 'webapp' } + }, 'shared-reply', null, footerAt - 20_000, footerAt - 20_000) + + // Source's copy: queued BEFORE the footer, but genuinely delivered + // AFTER it — a real, hub-confirmed delivery. + store.messages.addMessage(source.id, { + role: 'user', content: { type: 'text', text: 'here is the key' }, meta: { sentFrom: 'webapp' } + }, 'shared-reply', null, footerAt - 15_000, footerAt - 15_000) + store.messages.markMessagesInvoked(source.id, ['shared-reply'], footerAt + 5_000) + + store.messages.mergeSessionMessages(source.id, target.id) + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(0) + expect(engine.getSession(target.id)?.lastNotify ?? null).toBeNull() + }) + + it('yields to the event loop between sessions instead of scanning the whole candidate set in one tick (#1717 cold-review round 34)', async () => { + // A session whose scan falls through to the unbounded transcript + // read (rounds 33/34) can take real time on its own; a fleet of + // them hitting that path on the same restart must not run + // back-to-back inside one synchronous timer callback, or REST and + // Socket.IO traffic stalls for however long the whole candidate + // set takes. Proven by racing a `setImmediate` scheduled AFTER the + // backfill starts but BEFORE it is awaited: if the loop never + // yields, that macrotask cannot run until the backfill's own + // promise has already resolved. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const now = Date.now() + for (let i = 0; i < 5; i++) { + engine.getOrCreateSession(`yield-check-${i}`, { path: '/tmp', host: 'localhost' }, null, 'default') + } + + let otherMacrotaskRanDuringBackfill = false + const backfillPromise = engine.backfillRecentNotifySignals({ now }) + setImmediate(() => { otherMacrotaskRanDuringBackfill = true }) + await backfillPromise + + expect(otherMacrotaskRanDuringBackfill).toBe(true) + }) + + it('discards a chunked fallback scan that spans a concurrent rewind rather than resurrecting a deleted footer (#1717 cold-review round 36)', async () => { + // Each yield between pages is a window for a rewind to delete a + // row a page already read. The rewind's OWN reconciliation + // correctly derives and writes state from the retained (now + // shorter) history — but the in-flight scan's accumulated pages + // still contain the deleted footer. Finishing anyway and + // stamping its signal would overwrite that correct, more recent + // write with one computed from data that no longer exists. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-rewind-mid-scan', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footerAt = now - 1_300_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, 'rewind-mid-scan-footer', null, footerAt, footerAt) + // 1200 rows after the footer: beyond the 200-row scan cap AND wide + // enough to force the chunked fallback across three 500-row pages, + // giving the rewind a real window between the first and second. + for (let i = 0; i < 1200; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { type: 'output', data: { type: 'tool_use', data: { tool: 'bash', input: {} } } } + }, undefined, null, footerAt + 1_000 + i * 1_000, footerAt + 1_000 + i * 1_000) + } + + let pageCalls = 0 + const originalGetMessagesPage = store.messages.getMessagesPage.bind(store.messages) + store.messages.getMessagesPage = (sessionId, afterSeq, limit) => { + pageCalls += 1 + // After the FIRST page is read (and before the scan reaches the + // footer, which sits before all 1200 tool rows), simulate a + // rewind: delete the footer and everything after it, then run + // the SAME write path real rewind reconciliation uses. + if (pageCalls === 2) { + store.messages.truncateMessagesFromLocalId(sessionId, 'rewind-mid-scan-footer') + engine.reconcileNotifySignalAfterImport(sessionId) + } + return originalGetMessagesPage(sessionId, afterSeq, limit) + } + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(0) + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + expect(pageCalls).toBeGreaterThan(1) + }) + + it('retries a chunked fallback scan invalidated by an epoch bump unrelated to notify state (#1717 cold-review round 36)', async () => { + // Not every epoch bump is a rewind or a merge. Cancelling a + // queued prompt bumps it too, and does no notify reconciliation + // of its own — discarding unconditionally there would leave a + // session that still ends in a genuinely unanswered footer + // sitting out of Blocked until the next restart's scan. A + // bounded retry absorbs this: the second attempt's own epoch + // check passes because nothing further changed during it. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-cancellation-mid-scan', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footerAt = now - 1_300_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, footerAt, footerAt) + // A future-scheduled prompt, cancelled mid-scan — unrelated to + // the footer or the blocked status, but still bumps the epoch. + store.messages.addMessage(session.id, { + role: 'user', content: { type: 'text', text: 'scheduled later' }, meta: { sentFrom: 'webapp' } + }, 'cancellation-mid-scan-scheduled', footerAt + 500, footerAt, footerAt) + // 1200 rows after the footer: beyond the 200-row scan cap AND wide + // enough to force the chunked fallback across three 500-row pages. + for (let i = 0; i < 1200; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { type: 'output', data: { type: 'tool_use', data: { tool: 'bash', input: {} } } } + }, undefined, null, footerAt + 1_000 + i * 1_000, footerAt + 1_000 + i * 1_000) + } + + let pageCalls = 0 + const originalGetMessagesPage = store.messages.getMessagesPage.bind(store.messages) + store.messages.getMessagesPage = (sessionId, afterSeq, limit) => { + pageCalls += 1 + if (pageCalls === 2) { + store.messages.cancelQueuedMessage(sessionId, 'cancellation-mid-scan-scheduled') + } + return originalGetMessagesPage(sessionId, afterSeq, limit) + } + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(1) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + expect(pageCalls).toBeGreaterThan(1) + }) + + it('reads the unbounded fallback scan in bounded pages rather than one synchronous decode of the whole transcript (#1717 cold-review round 36)', async () => { + // The round-33 fallback (footer beyond the 200-row scan cap) used + // to call `getAllMessages` once and decode the entire transcript + // synchronously. A long-running session with a deep transcript + // would block the event loop for however long that one decode + // took. Proven two ways: `getMessagesPage` is called more than + // once for a transcript wider than a single page, and the + // correct footer still surfaces from beyond the second page — + // nothing is lost or duplicated at the page seam. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-chunked-fallback', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footerAt = now - 700_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, footerAt, footerAt) + // 600 rows after the footer: beyond the 200-row scan cap AND wide + // enough to force the chunked fallback across more than one page. + for (let i = 0; i < 600; i += 1) { + store.messages.addMessage(session.id, { + role: 'agent', + content: { type: 'output', data: { type: 'tool_use', data: { tool: 'bash', input: {} } } } + }, undefined, null, footerAt + 1_000 + i * 1_000, footerAt + 1_000 + i * 1_000) + } + + let pageCalls = 0 + const originalGetMessagesPage = store.messages.getMessagesPage.bind(store.messages) + store.messages.getMessagesPage = (sessionId, afterSeq, limit) => { + pageCalls += 1 + return originalGetMessagesPage(sessionId, afterSeq, limit) + } + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(1) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + expect(pageCalls).toBeGreaterThan(1) + }) + + it('does not let a locally handled command answer a footer during reconciliation', async () => { + // The live path already skips the clear for a command the CLI handled + // itself, but the store still stamps the row's `invoked_at`, so every + // path that re-derives "was this answered?" from the transcript later + // — backfill, rewind, merge — read it as a delivered reply. The + // disposition is persisted now, so they agree with the live decision. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-local-command', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, now - 10_000, now - 10_000) + // `/model` — consumed and stamped, but handled inside the CLI. + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: '/model' }, + meta: { sentFrom: 'webapp' } + }, 'slash-1', null, now - 5_000) + store.messages.markMessagesInvoked(session.id, ['slash-1'], now - 5_000, { agentDelivered: false }) + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(1) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + }) + + it('still lets a genuinely delivered reply answer a footer', async () => { + // Positive control for both tests above: the scan must still stop at a + // real reply, or they would pass on a predicate that never matches. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-answered', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, now - 10_000, now - 10_000) + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here is the key' }, + meta: { sentFrom: 'webapp' } + }, 'reply-1', null, now - 5_000, now - 5_000) + store.messages.markMessagesInvoked(session.id, ['reply-1'], now - 5_000) + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(0) + expect(engine.getSession(session.id)?.lastNotify ?? null).toBeNull() + }) + + it('does not treat an overdue but never-invoked reply as an answer', async () => { + // Due time is not delivery. A scheduled reply can pass its due time + // while the agent is offline and still have a null invokedAt — the + // agent never saw it, so the blocker it was meant to answer stands. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const session = engine.getOrCreateSession( + 'backfill-overdue', + { path: '/tmp/project', host: 'localhost' }, + null, + 'default' + ) + const now = Date.now() + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(session.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, now - 10_000) + // Due an hour ago, never invoked: the agent was offline throughout. + store.messages.addMessage(session.id, { + role: 'user', + content: { type: 'text', text: 'here is the key' }, + meta: { sentFrom: 'webapp' } + }, 'overdue-1', now - 3_600_000, now - 5_000) + + expect(await engine.backfillRecentNotifySignals({ now })).toBe(1) + expect(engine.getSession(session.id)?.lastNotify?.status).toBe('blocked') + }) + + it('reaches a recently-active session ranked past the per-batch cap (cold-review round 27)', async () => { + // Candidates are sorted newest-first and the batch cap is 2 here. + // Two NEWER sessions have nothing to stamp; a third, OLDER session + // (still inside the 24h window) carries a genuine unanswered + // footer. A single `.slice(0, maxSessions)` cutoff excludes that + // third session from the scan entirely — permanently, since this + // backfill runs once per restart and the same two newer sessions + // would occupy the cap again next time. + const { SyncEngine } = await import('./syncEngine') + const { RpcRegistry } = await import('../socket/rpcRegistry') + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const now = Date.now() + + // `addMessage` stamps `updatedAt` from the real insert clock, not + // the message's own (backdated) `createdAt` — pin it explicitly so + // the candidate sort order ("newest-first") does not depend on + // which of these three `getOrCreateSession`/`addMessage` calls the + // test happens to run first in real wall-clock time. + const sessionTags: Array<[string, number]> = [['newer-a', now + 20_000], ['newer-b', now + 10_000]] + for (const [tag, pinnedUpdatedAt] of sessionTags) { + const session = engine.getOrCreateSession( + `backfill-batch-${tag}`, { path: '/tmp/project', host: 'localhost' }, null, 'default' + ) + store.messages.addMessage(session.id, { + role: 'user', content: { type: 'text', text: 'hello' }, meta: { sentFrom: 'webapp' } + }, `${tag}-msg`, null, now - 1_000) + engine.recordSessionActivity(session.id, pinnedUpdatedAt) + } + + const olderBlocked = engine.getOrCreateSession( + 'backfill-batch-older', { path: '/tmp/project', host: 'localhost' }, null, 'default' + ) + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(olderBlocked.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, now - 60_000, now - 60_000) + engine.recordSessionActivity(olderBlocked.id, now + 1_000) + + const stamped = await engine.backfillRecentNotifySignals({ now, maxSessions: 2 }) + + expect(stamped).toBe(1) + expect(engine.getSession(olderBlocked.id)?.lastNotify?.status).toBe('blocked') + }) +}) diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 0e9201b34a2..6a6bae90202 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -7,7 +7,7 @@ * - No E2E encryption; data is stored as JSON in SQLite */ -import { type SessionReadStateRequest, isKnownFlavor, matchesClaudeSessionId, isLiveLifecycleState, isSteeringSupportedForSession, hasActiveSteeringTurn, MACHINE_CAPABILITIES, type LocalResumeTarget, type ResumableSession, type SessionEndReason } from '@hapi/protocol' +import { BLOCKED_NOTIFY_STALE_MS, notifyBlockerKey, isBlockedNotifyStatus, type SessionReadStateRequest, isKnownFlavor, matchesClaudeSessionId, isLiveLifecycleState, isSteeringSupportedForSession, hasActiveSteeringTurn, MACHINE_CAPABILITIES, type LocalResumeTarget, type ResumableSession, type SessionEndReason } from '@hapi/protocol' import { cliBinaryUpdatedOnDisk, isMachineCapabilitySkewed, @@ -93,7 +93,7 @@ import { ArchiveCleanupError } from './archiveCleanupError' import { AutomaticTitleSuggestionService } from './automaticTitleSuggestion' import { extractMessageEventType } from '../notifications/eventParsing' import { SessionEnumerationCache } from './sessionEnumerationCache' -import { ingestNotifySummaryFromMessage } from './workGraphNotifyIngest' +import { buildOperatorUnblockEvent, deliveredOperatorReplyAt, extractSessionNotifySignal, messageReceivedAt, notifySignalIdentity, operatorReplyDeliveredAt, ingestNotifySummaryFromMessage, isDeliveredOperatorReply, isOperatorReplyMessage } from './workGraphNotifyIngest' import { MetadataSchema, type OpenCodeRewindOperation } from '@hapi/protocol/schemas' import type { OpenCodeRewindReport } from '@hapi/protocol/apiTypes' import { extractTodoWriteTodosFromMessageContent } from './todos' @@ -104,6 +104,27 @@ import { import { getConfiguration } from '../configuration' import { getSettingsFile, readSettingsOrThrowCached } from '../config/settings' +/** Startup notify backfill bounds (#1717) — see `backfillRecentNotifySignals`. */ +const NOTIFY_BACKFILL_MAX_SESSIONS = 200 +const NOTIFY_BACKFILL_MESSAGE_SCAN = 6 +/** Ceiling for `findNotifySignalInTranscript`'s paging retry (#1717 + * cold-review round 30) — matches `getMessages`'s own hard cap, so paging + * past it would just re-read the identical last-200 rows forever. */ +const NOTIFY_BACKFILL_MESSAGE_SCAN_MAX = 200 +/** Page size for `deriveNotifyStateFromTranscriptChunked`'s fallback read + * (#1717 cold-review round 36) — bounds how much of a long transcript is + * decoded before yielding, rather than one unbounded `getAllMessages`. */ +const NOTIFY_BACKFILL_CHUNK_SIZE = 500 +/** Extra attempts `deriveNotifyStateFromTranscriptChunked` makes after an + * epoch change invalidates a scan (#1717 cold-review round 36) — bounded + * so a session under genuinely constant mutation still gives up rather + * than retrying forever. */ +const NOTIFY_BACKFILL_CHUNKED_SCAN_RETRIES = 2 +/** Rewind reconciliation scans deeper than the startup backfill: the retained + * footer can sit behind a run of sidechain or tool rows, and missing it there + * does not merely delay the signal — the replacement write clears it. */ +const NOTIFY_REWIND_MESSAGE_SCAN = 60 + type PiResumeAttempt = NonNullable['piResumeAttempt']> type PtyResumeAttempt = NonNullable['ptyResumeAttempt']> @@ -182,6 +203,43 @@ function asRecord(value: unknown): Record | null { : null } +/** [hub-arrival time, seq] position tuple used by the notify derivation's + * "at or before a boundary" comparisons. Module-level so a cross-session + * caller (`computeNotifyStateAcrossDuplicateSessions`'s override check) can + * compare a candidate message against another session's OWN boundary + * using the exact same seq tiebreak the single-session derivation uses + * internally — an untimestamped Codex import stamps every row in its + * batch with the same hub-arrival time, so dropping the tiebreak lets an + * initiating prompt tie its own still-open footer's timestamp and read as + * "at or before" it, same bug the tiebreak exists to prevent in the + * first place. */ +type NotifyPosition = [number, number] +type DerivedNotifyState = { + signal: { + status: string + at: number + note: string | null + receivedAt?: number | null + /** `notifySignalIdentity`'s identity for this footer — a native + * message id when one exists, content otherwise. Two footers can + * share every displayed field (status, note, author time) while + * being genuinely distinct occurrences; identity is what tells + * them apart when a stronger signal than content is available + * (#1717 cold-review round 36). */ + identity: string + } | null + boundaryAt: number | null + /** Full tiebreak-aware position of the boundary, for a caller that + * needs to compare a FOREIGN message against THIS session's own + * boundary precisely — see `computeNotifyStateAcrossDuplicateSessions`. + * `boundaryAt` alone drops the seq tiebreak. */ + boundaryPosition: NotifyPosition | null + authorCutoff: number | null +} +function positionAtOrBefore(a: NotifyPosition, b: NotifyPosition): boolean { + return a[0] < b[0] || (a[0] === b[0] && a[1] <= b[1]) +} + function normalizeUserMessageText(value: string): string | undefined { const text = value.trim().replace(/\s+/g, ' ') return text.length > 0 ? text : undefined @@ -225,6 +283,56 @@ function extractClaudeUserMessageTextFromAgentOutput(content: unknown): string | return extractUserMessageText(message.content) } +/** + * The stable field set an OpenCode rewind reservation hashes its transcript + * against (#1717 cold-review round 21). + * + * `hashOpenCodeRewindTranscript` used to hash `JSON.stringify` of the whole + * `StoredMessage` array. `StoredMessage` keeps growing — this PR alone added + * `sweptAt` / `receivedAt` / `agentDelivered` — and every one of those fields + * is emitted as `null` even for an untouched row migrated from an older + * schema version. A reservation hashed before a hub upgrade can never match + * the same, unchanged transcript hashed after it: the hash input gained keys + * the old hub never wrote. The hub then rejected an already-applied native + * rewind as "source transcript changed" and kept retrying against a + * reservation it could never satisfy, blocking new prompts. + * + * Projecting to this fixed, named field set — the contract as it stood before + * this PR — means a FUTURE field addition to `StoredMessage` cannot silently + * repeat the same regression; it would have to touch this function on + * purpose. + */ +function hashableOpenCodeRewindFields(message: StoredMessage): Record { + // Reproduces `toStoredMessage`'s pre-#1717 shape BYTE FOR BYTE: same key + // order, and the three conditional fields OMITTED when absent rather than + // defaulted to `null` (cold-review round 22). `JSON.stringify` preserves + // insertion order and distinguishes a missing key from a `null` one, so + // either difference alone still changes the hash string for an unchanged + // transcript — defeating the point of this function. `sweptAt` / + // `receivedAt` / `agentDelivered` are genuinely new and stay excluded + // entirely, not nulled: a pre-upgrade hub's serialized row never had + // those keys at all. + return { + id: message.id, + sessionId: message.sessionId, + ...(message.contentRevision !== undefined ? { contentRevision: message.contentRevision } : {}), + content: message.content, + createdAt: message.createdAt, + seq: message.seq, + localId: message.localId, + invokedAt: message.invokedAt, + scheduledAt: message.scheduledAt, + ...(message.deliveryState !== undefined ? { deliveryState: message.deliveryState } : {}), + ...(message.deliveryPending !== undefined ? { deliveryPending: message.deliveryPending } : {}) + } +} + +export function hashOpenCodeRewindTranscript(messages: StoredMessage[]): string { + return createHash('sha256') + .update(JSON.stringify(messages.map(hashableOpenCodeRewindFields))) + .digest('hex') +} + export class SyncEngine { private readonly archiveRequests = new Map>() // KillSession's beforeKill drain completes before the CLI's async cleanup @@ -430,6 +538,861 @@ export class SyncEngine { return this.sessionCache.getSessions() } + /** See `SessionCache.hubGeneration` (#1717 cold-review round 29). */ + get hubGeneration(): string { + return this.sessionCache.hubGeneration + } + + /** + * Operator manually marks a session unblocked (#1717). + * + * Two effects, deliberately: it dismisses the chrome, AND it writes a + * work-graph event. Replying to an agent leaves the rationale in the + * transcript for anyone to read later; dismissing + * silently would leave a state change with no "why", which is exactly the + * gap the reason prompt exists to close. + */ + /** Confirmed prompt delivery cleared the agent's last self-report (#1717). */ + clearSessionLastNotifyOnDelivery(sessionId: string, deliveredAt?: number): void { + // A hub stamp, and compared only against other hub stamps: a footer's + // hub ARRIVAL on the way in, and the author time of the footer this + // delivery superseded on the way past. The footer's own timestamp is + // the runner's clock and is never measured against this. + this.sessionCache.clearSessionLastNotify(sessionId, deliveredAt) + } + + /** @throws {BlockedAckMissingKeyError} see `SessionCache.setSessionBlockedAck`. */ + acknowledgeSessionBlocked( + sessionId: string, + reason: string, + observedAt?: number, + observedKey?: string + ): { at: number; reason: string } | null { + const session = this.getSession(sessionId) + if (!session) return null + + // The ledger has to describe the blocker the operator READ, not + // whatever the session reports at confirmation time. If a newer footer + // landed while they were typing, recording that one attaches their + // reason to something they never saw. + const observedNotify = session.lastNotify + && (!observedKey || observedKey === `notify:${session.lastNotify.at}`) + ? session.lastNotify + : null + const priorNotify = observedNotify + // Watermark the blocker the operator actually reviewed, not the hub's + // receive time. A permission request or footer that landed between the + // dialog opening and this call is a blocker they never saw, and + // stamping `now` would silence it under a reason written for another. + // Clamped so a skewed or forged client clock cannot dismiss the future. + const ackAt = typeof observedAt === 'number' + ? Math.min(observedAt, Date.now()) + : Date.now() + const ack = this.sessionCache.setSessionBlockedAck(sessionId, reason, ackAt, observedKey) + if (!ack) return null + + // The ledger records WHEN THE OPERATOR DECIDED, which is now — not the + // blocker's own timestamp, and not `ack.at`, which is kept monotonic + // and so may belong to a newer prompt than the one just dismissed. + // The log sorts by event time, so either of those filed today's + // rationale among days-old activity, or outside a recent-events window + // entirely. What was dismissed is carried as detail instead. + const decidedAt = Date.now() + try { + this.store.workGraph.insertEvent(session.namespace, buildOperatorUnblockEvent({ + sessionId, + ownerUserId: this.hubOwnerUserId, + reason, + acknowledgedAt: decidedAt, + observedAt: ackAt, + // Carry the identity even when the footer it named has already + // been replaced: an event that records the reason with null + // prior fields cannot be matched back to what was dismissed. + observedKey: observedKey ?? null, + priorNotify: priorNotify + }), { ts: decidedAt }) + } catch (error) { + // Best-effort ledger capture — never fail the operator's dismissal + // because the event log rejected the row. + console.error('[work-graph] operator_unblock capture failed', error) + } + + return ack + } + + /** + * One-shot startup backfill for the blocked session-list chrome (#1717). + * + * `lastNotify` is normally stamped as messages arrive, so a hub upgraded + * mid-flight would show nothing until every agent speaks again. Rather than + * rescan every session's history (600+ sessions x 200 messages), only look + * at sessions that moved inside the staleness window the UI actually + * renders loudly — anything older would be drawn muted anyway. + * + * Sessions with no footer in their last few messages are rescanned on each + * restart. That is accepted: the candidate set is already bounded by both + * the 24h window and `NOTIFY_BACKFILL_MAX_SESSIONS`, and a "we looked and + * found nothing" marker would be more state than the scan costs. + * + * `maxSessions` bounds each BATCH's transcript-scanning work, not the + * total candidate set (#1717 cold-review round 27): a `.slice` cutting + * the newest-first-sorted list off at the cap permanently excluded the + * 201st-and-later recently-active session, even one whose last message + * is a genuinely unanswered footer — every restart kept rescanning the + * same 200 newer sessions and never reached it until something else + * made it speak again. Looping in batches instead covers every + * candidate inside the 24h window while still scanning transcripts + * `maxSessions` at a time per batch. + * + * Yields after every session, not just every batch (#1717 cold-review + * round 34): a session whose scan falls through to the unbounded + * transcript read (rounds 33/34) can take real time on its own, and a + * fleet of them hitting that path on the SAME restart previously ran + * back-to-back inside this one timer callback, delaying REST and + * Socket.IO traffic for however long the whole candidate set took. + * `setImmediate` lets queued I/O drain between sessions without + * changing which sessions get scanned or what they resolve to. + */ + async backfillRecentNotifySignals(options: { now?: number; maxSessions?: number } = {}): Promise { + const now = options.now ?? Date.now() + const maxSessions = options.maxSessions ?? NOTIFY_BACKFILL_MAX_SESSIONS + const candidates = this.sessionCache.getSessions() + .filter((session) => !session.lastNotify + && now - session.updatedAt <= BLOCKED_NOTIFY_STALE_MS) + .sort((a, b) => b.updatedAt - a.updatedAt) + + let stamped = 0 + for (let offset = 0; offset < candidates.length; offset += maxSessions) { + const batch = candidates.slice(offset, offset + maxSessions) + for (const session of batch) { + if (await this.restoreNotifySignalFromTranscript(session.id)) stamped += 1 + await new Promise((resolve) => setImmediate(resolve)) + } + } + return stamped + } + + /** + * Re-derive `lastNotify` from the stored transcript, newest footer wins. + * + * Returns true when a footer was found and stamped. + */ + private async restoreNotifySignalFromTranscript(sessionId: string): Promise { + const signal = await this.findNotifySignalInTranscript(sessionId) + if (!signal) return false + this.sessionCache.setSessionLastNotify(sessionId, signal) + return true + } + + /** + * Newest eligible footer in the retained transcript, or null. + * + * Pages the scan window outward, but a FOUND SIGNAL only short-circuits + * once we've seen ENOUGH of the transcript to rule out an earlier + * occurrence of its identity, not just once ANY boundary happens to be + * in view (#1717 cold-review round 32 — the round 31 fix still stopped + * one case too early). A reply that exists in the current window but + * is unrelated to the found footer can set `boundaryAt` non-null + * without the window reaching far enough back to contain the ORIGINAL + * footer+reply pair a later exact-text replay needs to be recognized + * against — `deriveNotifyStateFromTranscript` can then read that + * replay as live, having nothing in view to supersede it with. + * + * The asymmetry that makes this safe to bound: a CONCLUSIVELY IDLE + * result (`signal === null` with a boundary established) is stable + * under MORE history — every message paging-further reveals is OLDER + * than everything already seen, hence at-or-before the same boundary, + * hence superseded by POSITION alone regardless of content. A result + * reporting something LIVE has no equivalent guarantee — an identical, + * already-answered occurrence could still be waiting further back — + * so only the idle case may return early; a found signal keeps paging + * to the cap, where whatever was last found becomes the best + * available answer. + * + * The cap itself is a hard ceiling, not just this loop's own choice: + * `store.messages.getMessages` never returns more than its own 200-row + * limit regardless of the depth requested, so widening `depth` further + * cannot reach a footer — or the reply/original pair that would + * supersede a replay of one — sitting beyond the newest 200 rows + * (#1717 cold-review round 33). Falling through to a full scan closes + * the gap; only the rare session whose signal survived every doubling + * up to the cap pays for it, since anything else resolved well under + * it. That fallback reads in bounded pages with a yield between each + * rather than one synchronous decode of the whole transcript (#1717 + * cold-review round 36) — this is the one caller unbounded enough to + * make that cost worth paying for; the other three (reconcile-after- + * rewind, reconcile-after-import, cross-duplicate-session resolution) + * are each already rare enough on their own that one synchronous scan + * is an acceptable cost. + * + * The idle short-circuit's own stability argument assumed `seq` + * tracks real arrival order, which `mergeSessionMessages` breaks: it + * shifts the destination's existing rows ABOVE every incoming source + * row, so an OLDER destination reply can sit inside a small window + * while a NEWER, still-unanswered source footer sits at a LOWER seq + * just outside it — paging further back after a merge can reveal + * something NEWER, not just older (#1717 cold-review round 34). + * `getMessageEpoch` is bumped by every merge (and rewind, a false + * positive here but a safe one), so epoch 0 is the one case the + * original ordering assumption is still actually true for — the + * short-circuit stays restricted to that case; everything else pages + * to the cap and falls through like the found-signal path already + * does. + */ + private async findNotifySignalInTranscript( + sessionId: string, + scanDepth: number | null = NOTIFY_BACKFILL_MESSAGE_SCAN + ): Promise<{ status: string; at: number; note: string | null; seq?: number | null } | null> { + if (scanDepth === null) return (await this.deriveNotifyStateFromTranscriptChunked(sessionId))?.signal ?? null + const seqOrderIsArrivalOrder = this.store.messages.getMessageEpoch(sessionId) === 0 + let depth = scanDepth + for (;;) { + const result = this.deriveNotifyStateFromTranscript(sessionId, depth) + if (seqOrderIsArrivalOrder && result.signal === null && result.boundaryAt !== null) return null + if (depth >= NOTIFY_BACKFILL_MESSAGE_SCAN_MAX) { + return (await this.deriveNotifyStateFromTranscriptChunked(sessionId))?.signal ?? null + } + depth = Math.min(depth * 4, NOTIFY_BACKFILL_MESSAGE_SCAN_MAX) + } + } + + /** + * Derive both the surviving footer and its clear boundary from the + * transcript, each in the only domain that can order it (#1717). + * + * Two separate comparisons, deliberately not one sort: + * + * - footer vs footer: both were stamped by the same agent runner inside + * one transcript, so authorship time is authoritative between them. + * Insertion `seq` is not — Claude replays an older footer after a newer + * one and it lands at a HIGHER seq while being older in fact. + * - footer vs reply: the footer's own timestamp is the runner's clock and + * the reply's is the hub's, so no comparison between those is sound in + * either direction. The footer's hub ARRIVAL is, because the boundary is + * a hub stamp too. A position cannot serve: cancelling a queued row + * frees its `seq` for reuse, and a merge renumbers one side's positions + * into something synthetic rather than real. + * + * A single ordering key cannot satisfy both, which is why mixing hub + * invocation times with runner footer times could drop a blocker still + * visible in the transcript whenever the two clocks disagreed. + */ + private deriveNotifyStateFromTranscript( + sessionId: string, + scanDepth: number | null = NOTIFY_BACKFILL_MESSAGE_SCAN + ): DerivedNotifyState { + const scanned = scanDepth === null + ? this.store.messages.getAllMessages(sessionId) + : this.store.messages.getMessages(sessionId, scanDepth) + return this.deriveNotifyStateFromMessages(scanned) + } + + /** + * Same derivation as `deriveNotifyStateFromTranscript`, but reading the + * full transcript in bounded pages with a yield between each rather + * than one synchronous `getAllMessages` decode (#1717 cold-review + * round 36). Only the startup backfill's unbounded fallback uses + * this — every other caller already bounds its own read depth or + * accepts paying for one full scan on a rare rewind, so there is no + * need to route them through an extra await. + * + * Each yield is a window for a concurrent change to invalidate a page + * already read — most importantly a rewind deleting a row, whose OWN + * reconciliation then correctly derives and writes state from the + * retained history while this scan's accumulated pages still contain + * the deleted row. Finishing anyway and returning its signal would + * let a caller that stamps it (the backfill) overwrite that correct, + * more recent write with one computed from data that no longer + * exists (#1717 cold-review round 36). `getMessageEpoch` is bumped by + * every rewind and merge, but ALSO by changes with nothing to do + * with notify state at all — cancelling a future-scheduled prompt, + * for one — which do no reconciliation of their own, so discarding + * unconditionally on any epoch change left a session with a + * genuinely unanswered footer sitting out of Blocked until the next + * restart's scan or a fresh live report. Retrying a bounded number of + * times absorbs exactly that case — a retry against an epoch a + * rewind already reconciled just recomputes the same correct answer + * reconciliation already wrote, so there is no harm in not knowing + * which kind of change it was. + */ + private async deriveNotifyStateFromTranscriptChunked(sessionId: string): Promise { + for (let attempt = 0; attempt <= NOTIFY_BACKFILL_CHUNKED_SCAN_RETRIES; attempt += 1) { + const result = await this.deriveNotifyStateFromTranscriptChunkedOnce(sessionId) + if (result !== null) return result + } + return null + } + + /** One attempt of the scan `deriveNotifyStateFromTranscriptChunked` retries. */ + private async deriveNotifyStateFromTranscriptChunkedOnce(sessionId: string): Promise { + const epochBefore = this.store.messages.getMessageEpoch(sessionId) + const scanned: StoredMessage[] = [] + let afterSeq = 0 + for (;;) { + const page = this.store.messages.getMessagesPage(sessionId, afterSeq, NOTIFY_BACKFILL_CHUNK_SIZE) + if (page.length === 0) break + scanned.push(...page) + afterSeq = page[page.length - 1]!.seq + if (page.length < NOTIFY_BACKFILL_CHUNK_SIZE) break + await new Promise((resolve) => setImmediate(resolve)) + } + if (this.store.messages.getMessageEpoch(sessionId) !== epochBefore) return null + return this.deriveNotifyStateFromMessages(scanned) + } + + private deriveNotifyStateFromMessages(scanned: StoredMessage[]): DerivedNotifyState { + // Position in the hub's arrival order, with `seq` breaking ties. + // + // The tie-break is not cosmetic: a Codex Desktop transcript carries no + // per-message timestamps, so the importer stamps every row with the + // same import time. Comparing arrival alone then made a transcript's + // FINAL message — an unanswered blocked footer — compare equal to the + // prompt that started it and read as already answered, so the + // conversation went missing from Blocked entirely. `seq` is the native + // transcript order for imported rows, which is exactly the information + // the timestamps lack. + const position = (message: StoredMessage): NotifyPosition => + [messageReceivedAt(message), message.seq] + const atOrBefore = positionAtOrBefore + + // Where the operator's most recent genuine reply sits. Only a reply the + // agent was actually given counts: a locally handled slash command has + // `invoked_at` stamped but answered nothing. + let boundary: NotifyPosition | null = null + let boundaryAt: number | null = null + for (const message of scanned) { + if (!isDeliveredOperatorReply(message)) continue + const here: NotifyPosition = [operatorReplyDeliveredAt(message), message.seq] + if (boundary === null || !atOrBefore(here, boundary)) { + boundary = here + boundaryAt = here[0] + } + } + + // Reconstruct the author cutoff that live ingestion holds in + // `last_notify_cleared_author_at`. + // + // That cutoff is SESSION state, so a derivation that reads only the + // transcript cannot see it — and a rewind retaining both the reply and + // an older footer replay would hand back the replay that live + // ingestion had already rejected, reopening an answered turn. The + // transcript does carry the equivalent: any footer that arrived at or + // before the boundary belongs to a turn the reply superseded, so + // nothing authored at or before the newest of those can be current. + let authorCutoff: number | null = null + // Identities of the footers the boundary superseded. A Claude replay + // is the SAME footer stored a second time — same status, same note, + // same author timestamp — and it arrives after the reply, so neither + // arrival nor a strict author comparison can reject it. Identity can. + // This is what keeps the strict comparison below safe: equal author + // times are accepted for a genuinely new footer (an untimestamped + // import synthesizes one timestamp for every row) but refused for an + // exact duplicate of something already answered. + const supersededIdentities = new Set() + const identity = notifySignalIdentity + const footers: Array<{ + signal: { status: string; at: number; note: string | null } + position: NotifyPosition + identity: string + }> = [] + for (const message of scanned) { + const signal = extractSessionNotifySignal(message.content, message.createdAt) + if (!signal) continue + const here = position(message) + footers.push({ signal, position: here, identity: identity(message, signal) }) + if (boundary !== null && atOrBefore(here, boundary)) { + if (authorCutoff === null || signal.at > authorCutoff) authorCutoff = signal.at + supersededIdentities.add(identity(message, signal)) + } + } + + // The newest footer the boundary does not already answer. Eligibility + // is decided on arrival order (same clock as the boundary) and on the + // author cutoff (same clock as the other footers); which of the + // eligible ones is newest is decided on AUTHOR time. + let best: { + signal: { status: string; at: number; note: string | null } + position: NotifyPosition + identity: string + } | null = null + for (const footer of footers) { + if (boundary !== null && atOrBefore(footer.position, boundary)) continue + // STRICTLY older, not "at or older". An untimestamped Codex + // Desktop import synthesizes one timestamp for every row, so an + // earlier turn's footer sets a cutoff EQUAL to the final footer's + // author time — and `<=` then discarded a blocker that is still + // unanswered and is the last thing in the transcript. Where the + // author clock cannot discriminate, position already has: this + // footer is after the boundary. A genuine replay is strictly + // older than the footer it duplicates, so `<` still rejects it. + if (authorCutoff !== null && footer.signal.at < authorCutoff) continue + // An exact duplicate of a footer the reply already answered. + if (supersededIdentities.has(footer.identity)) continue + if (best === null + || footer.signal.at > best.signal.at + || (footer.signal.at === best.signal.at && !atOrBefore(footer.position, best.position))) { + best = footer + } + } + return { + signal: best === null ? null : { ...best.signal, receivedAt: best.position[0], identity: best.identity }, + boundaryAt, + boundaryPosition: boundary, + authorCutoff + } + } + + /** + * Reconcile the persisted notify signal after history truncation (#1717). + * + * A rewind can delete the very message whose footer is driving the blocked + * chrome. Nothing else repairs that: a Codex rollback does not start a new + * turn, so the clear-on-new-turn transition never fires, and the next + * refresh simply re-reads the stale columns. + */ + private reconcileNotifySignalAfterTruncate(sessionId: string): void { + // Derive FIRST, then write the signal and its boundary together. + // + // Clearing and restoring as two steps made the restore fail its own + // check: the clear stamps the boundary at `now`, and the retained + // footer predates that, so a session whose retained history still ends + // blocked dropped out of the Blocked section entirely. After a + // truncation the transcript is the truth, not arrival order. + const session = this.sessionCache.getSession(sessionId) + if (!session) return + // Scan ALL retained history. Any fixed window is wrong here: a miss + // does not delay the signal, it writes null and drops the session out + // of Blocked while its transcript still ends unanswered. Rewind is + // rare, so the full read is affordable. + // Scope the boundaries to the surviving transcript too. They were left + // describing deleted history, and the clear's MAX meant no later + // delivery could lower them again — so after a rewind the session + // could reject every genuine footer it went on to emit. + const retained = this.deriveNotifyStateFromTranscript(sessionId, null) + this.sessionCache.replaceNotifyAfterTruncate( + sessionId, + retained.signal, + retained.boundaryAt ?? 0, + retained.authorCutoff + ) + } + + /** + * Re-derive the blocked signal after importing a transcript (#1717). + * + * An import replays historical rows through live ingestion, which saves + * each footer as it passes but never clears one: an imported reply does + * not go through the CLI delivery callback, so nothing marks the footer it + * answered as answered. The conversation entered Blocked on a footer its + * own transcript closes. + * + * The ordinary derivation is correct here, because an imported row carries + * the transcript's own time in BOTH `received_at` and `invoked_at` — so + * its footers and its replies are directly comparable, exactly as live + * rows are in the hub's clock. Only the one-shot re-derivation is needed. + */ + reconcileNotifySignalAfterImport(sessionId: string): void { + if (!this.sessionCache.getSession(sessionId)) return + const derived = this.deriveNotifyStateFromTranscript(sessionId, null) + this.sessionCache.replaceNotifyAfterTruncate( + sessionId, + derived.signal, + derived.boundaryAt ?? 0, + derived.authorCutoff + ) + } + + /** + * Compute the blocked/notify projection across a Codex Desktop + * duplicate-session merge group, from every session's OWN untouched + * pre-merge messages (#1717). Does NOT commit the result — see + * `applyReconciledNotifyState`, which a caller must invoke AFTER the + * merge finishes touching the transcript, not before. + * + * Each session's own signal is derived independently, via the ordinary + * SINGLE-session derivation — never combined across sessions on a raw + * timestamp. A Codex Desktop import carries NO per-row timestamp at all; + * every row of one import batch is stamped with that import's OWN wall + * clock moment, which can land arbitrarily far after (or before) a + * live session's real activity on the SAME thread. Comparing "latest by + * hub arrival" across sessions therefore compares two numbers that do + * not mean the same thing, and an import whose own transcript genuinely + * ends blocked can beat a live session that already answered the exact + * same footer, purely because the import happened to run later in + * wall-clock terms than the live reply did. + * + * What IS sound across sessions is CONTENT: if session A's own + * self-consistent timeline shows a reply answering a footer with a given + * status+note, that fact holds regardless of what any OTHER session's + * copy of the same footer is stamped with. So a session's own blocked + * signal is overridden (treated as already answered) when ANY session + * in the group — using only ITS OWN clock, full tiebreak included — shows + * that same status+note at or before ITS OWN boundary. Dropping the seq + * tiebreak here (comparing bare `messageReceivedAt` numbers) reopens + * exactly the bug the tiebreak exists to prevent: an untimestamped + * import stamps its initiating prompt and its own still-open footer with + * the SAME arrival time, so a bare `<=` reads the footer as "at or + * before" the prompt's own position and misreads it as answered by it. + * + * Among whatever's left unresolved, the representative is picked by the + * SAME deterministic order the merge already sorts its sessions into + * (most messages, then newest `updatedAt`, then session id) — preferring + * canonical's own signal, falling back to the first surviving duplicate + * in that order. This is the exact order the row-dedup loop in the merge + * processes sources in, so the chosen signal and whichever row the + * content-dedup happens to keep are never pointing at different events. + * + * `sessionIds` MUST already be in that order — this function trusts the + * caller's sort (`survivors[0]`) rather than re-deriving it, so passing + * an arbitrary order silently changes which signal represents the + * group, with nothing here to catch it. + * + * The winner's own dismissal is SNAPSHOTTED here, not transferred + * here: when the winner is a source about to be deleted, its ack + * keys only exist before the merge removes that session, so there is + * no later point left to READ them from — but the WRITE, like + * canonical's own strip below, is deferred to + * `applyReconciledNotifyState` (returned as `pendingAckTransfer`), + * for the same reason: writing it immediately committed the merge + * even when the caller's own later steps refused it. Applying the + * strip BEFORE the transfer there, in that fixed order, is what + * keeps the two from clobbering each other when both apply to the + * SAME coincidental key (#1717 cold-review round 36) — see the + * comment where `pendingAckTransfer` is computed, below. + */ + computeNotifyStateAcrossDuplicateSessions( + // Caller's deterministic merge order (most messages, newest + // `updatedAt`, then session id) — canonical first. See the doc + // comment above; this function does not re-sort. + sessionIds: string[], + canonicalSessionId: string, + namespace: string + ): { + signal: { status: string; at: number; note: string | null; receivedAt?: number | null } | null + boundaryAt: number | null + authorCutoff: number | null + /** Computed but not yet applied — see `applyReconciledNotifyState` + * (#1717 cold-review round 36). `null` when canonical's own + * dismissal needs no change. */ + pendingCanonicalAckEdit: + | { kind: 'clear' } + | { kind: 'set'; at: number; reason: string; keys: string[] } + | null + /** Winner's own ack, snapshotted before the merge can delete that + * session, for `applyReconciledNotifyState` to transfer onto + * canonical AFTER `pendingCanonicalAckEdit` above — applying the + * strip and the transfer in that order is what keeps a + * winningKey the winner legitimately owns from being removed by + * a strip computed before the transfer added it back (#1717 + * cold-review round 36). `null` when the winner IS canonical + * (nothing to transfer) or has nothing to transfer. + */ + pendingAckTransfer: { + fromSessionId: string + winningKey: string + sourceSnapshot: { blockedAckAt: number | null; blockedAckKeys: string[] | null; blockedAckReason: string | null } + } | null + } { + let pendingCanonicalAckEdit: { + kind: 'clear' + } | { + kind: 'set' + at: number + reason: string + keys: string[] + } | null = null + let pendingAckTransfer: { + fromSessionId: string + winningKey: string + sourceSnapshot: { blockedAckAt: number | null; blockedAckKeys: string[] | null; blockedAckReason: string | null } + } | null = null + const perSession = sessionIds.map((sessionId) => ({ + sessionId, + ackKeys: this.store.sessions.getSessionByNamespace(sessionId, namespace)?.blockedAckKeys ?? [], + derived: this.deriveNotifyStateFromTranscript(sessionId, null) + })) + + // No cross-session "already resolved" check (#1717 cold-review + // round 31) — there used to be one here, matching a candidate's + // signal against a SIBLING's transcript by status+note CONTENT. + // Content equality is not evidence the two occurrences are the + // SAME real event: the self-exclusion fix (round 29) already + // proved recurring identical text is a real pattern, not + // hypothetical, and nothing stops the SAME pattern splitting + // across two duplicate sessions' independently-synced histories + // instead of within one. Matching would need a stable cross-copy + // identity to be sound, and #1717 (filed as hapi#2577) traced that + // none exists today for any flavor's live-vs-imported pairing — + // the dominant real scenario this code has to handle. + // + // Given that, the only safe default is to decline: a session's own + // self-consistent derivation (which DOES use real identity for its + // own within-session ordering) is trusted as-is, full stop. The + // cost is a dismissal legitimately recorded on a sibling session + // occasionally not carrying across the merge — an answered blocker + // stays visible until something touches it directly. That is the + // safe direction to be wrong in; the alternative (matching by + // content) can hide a genuinely unanswered blocker instead, which + // is the failure this entire subsystem exists to prevent. + const survivors = perSession.filter((source) => source.derived.signal !== null) + // When survivors report DIFFERENT content, the representative is + // whichever one's signal is newest by author time, not whichever + // sorts first in the merge's canonical-selection order (most + // messages, newest updatedAt) — that order answers "which + // session's OTHER metadata to keep," a different question from + // "which blocker is most current" (#1717 cold-review round 32). A + // session can have fewer messages and still be reporting the + // genuinely later real episode; picking the first survivor in + // merge order silently preferred an older blocker from a longer + // duplicate over a newer one from a shorter sibling. + // + // But when every survivor reports the IDENTICAL status+note, author + // time stops being a safe tie-break: an untimestamped Codex import + // stamps every row with the import's OWN wall-clock moment, not a + // real conversation timestamp (#1717 cold-review round 25's test + // scenario — two projections of the SAME event, each a duplicate's + // own import batch artifact). Comparing those as if "later" meant + // "more current" would just be cross-session content+timestamp + // matching again, wearing a tie-break's clothes. Identical content + // keeps the deterministic merge order instead — the question is + // genuinely undecidable from the data, same reasoning as declining + // to resolve by content above, so pick the SAME default that + // reasoning already settled on. + // + // Picking by author time across DIFFERENT content is itself only + // safe between two signals of the SAME polarity — two blockers, or + // two non-blocking reports. Between a blocked survivor and a + // non-blocking one it reopens the exact question round 31 declined + // to answer by content, just dressed as a timestamp comparison: an + // untimestamped import stamps its last row with the IMPORT's own + // wall-clock moment, which can land after a live session's + // genuinely earlier blocked report in raw numeric terms while the + // import's real episode is actually OLDER — a later number does + // not mean it actually resolved the other session's blocker + // (#1717 cold-review round 33). Restrict the pool to blocked + // survivors whenever any exist; a non-blocking report only wins + // when nothing survived blocked. + // + // "Blocked" means any status the list itself treats as a blocker + // (`stalled`, `needs_decision`, ... — not just the literal string + // `blocked`), and a survivor whose OWN session already dismissed + // that exact signal does not count as an unresolved one either + // (#1717 cold-review round 34) — otherwise a newer, already- + // acknowledged report could still outrank a distinct, genuinely + // unresolved blocker from a sibling purely by author time, and a + // live session reporting `stalled` (true but not literally + // "blocked") lost to a stale import's `done` for the same reason + // round 33 fixed for the literal status. + const unresolvedBlockedSurvivors = survivors.filter((source) => { + const signal = source.derived.signal! + if (!isBlockedNotifyStatus(signal.status)) return false + return !source.ackKeys.includes(notifyBlockerKey(signal.at)) + }) + const pool = unresolvedBlockedSurvivors.length > 0 ? unresolvedBlockedSurvivors : survivors + const distinctContents = new Set( + pool.map((source) => `${source.derived.signal!.status} ${source.derived.signal!.note ?? ''}`) + ) + const winner = distinctContents.size <= 1 + ? (pool[0] ?? null) + : pool.reduce( + (latest, candidate) => ( + latest === null || candidate.derived.signal!.at > latest.derived.signal!.at + ) ? candidate : latest, + null + ) + + if (winner && winner.derived.signal !== null) { + const winningKey = notifyBlockerKey(winner.derived.signal.at) + // `notifyBlockerKey` is a function of the timestamp alone, so a + // DISTINCT footer that happens to share CANONICAL's own author + // time with something canonical already dismissed produces the + // SAME key — exactly the untimestamped-import coincidence round + // 25 already established happens in practice. Left untouched, + // canonical's stale dismissal of its OWN (different) footer + // would silently suppress the winner's unrelated one on the + // web side, which only ever sees keys, never content (#1717 + // cold-review round 36). Strip it first, before anything else + // runs: canonical's own derivation is the one piece of content + // identity actually available here to tell the two apart. + const canonicalEntry = perSession.find((source) => source.sessionId === canonicalSessionId) + const canonicalSignal = canonicalEntry?.derived.signal ?? null + // A reply can answer canonical's OWN footer between the + // dismissal and this merge, leaving `canonicalSignal` null — + // its transcript derives nothing current — while the stale + // key sticks around (#1717 cold-review round 36, the gap in + // the first pass at this exact fix: requiring a CURRENT + // canonical signal to differ from the winner's meant an + // ALREADY-ANSWERED canonical footer had nothing to compare + // against and the key survived unexamined). Default to + // stripping a colliding key; only a canonical signal whose + // IDENTITY — not just its displayed content — matches the + // winner's is positive evidence the key is actually FOR the + // surviving occurrence, not a coincidence. Content equality + // alone is not identity: two footers can share every + // displayed field (status, note, author time) while a native + // message id proves they are genuinely distinct occurrences + // (the second pass at this fix compared content and still + // missed exactly that case — #1717 cold-review round 36). + // `notifySignalIdentity` already prefers that id when one + // exists, falling back to content only when it does not, so + // comparing identities subsumes the content comparison for + // the one case content comparison is actually sound in. + const canonicalAckKeyIsForWinner = canonicalSignal !== null + && canonicalSignal.identity === winner.derived.signal.identity + const staleCollision = !canonicalAckKeyIsForWinner + && (canonicalEntry?.ackKeys ?? []).includes(winningKey) + if (staleCollision && canonicalEntry) { + const sanitizedKeys = canonicalEntry.ackKeys.filter((key) => key !== winningKey) + const canonicalStored = this.store.sessions.getSessionByNamespace(canonicalSessionId, namespace) + if (canonicalStored?.blockedAckAt != null) { + // Computed here, but NOT written here — see + // `pendingCanonicalAckEdit` below and this function's own + // "NOT committed yet" convention for `signal` (#1717 + // cold-review round 36). Writing immediately committed + // the strip even when the caller's own merge later + // refused (e.g. source deletion blocked on an + // unconfirmed resume) — the canonical footer could then + // reappear on a cache refresh with no replacement ever + // actually applied, because nothing rolled the strip + // back when the merge it was computed for did not + // happen. + pendingCanonicalAckEdit = sanitizedKeys.length === 0 + ? { kind: 'clear' } + : { + kind: 'set', + at: canonicalStored.blockedAckAt, + reason: canonicalStored.blockedAckReason ?? '', + keys: sanitizedKeys + } + } + } + + // Only the WINNER's own acknowledgement ever transfers — never + // a sibling's, even one whose content happens to match (#1717 + // cold-review round 31, same reasoning as declining the + // cross-session resolve above). The winner's own ack is the + // one case identity is actually certain: it is the session's + // own acknowledgement of its own signal, by construction, not + // a content match across two distinct objects. + // + // Snapshotted here, not transferred here (#1717 cold-review + // round 36): when canonical answered its OWN dismissed footer + // (making `staleCollision` strip that key above) and the + // winner is a DISTINCT, ALSO-dismissed footer sharing that + // same coincidental key, writing the transfer eagerly — union + // merging the winner's key into canonical's keys immediately + // — and the strip as a separately-computed, deferred + // snapshot of canonical's PRE-transfer keys raced each other: + // applying the stale snapshot after the eager transfer wiped + // out the very key the transfer had just legitimately added. + // Reading the winner's ack now (before a source winner can be + // deleted) but applying both in the fixed order strip-then- + // transfer in `applyReconciledNotifyState` is what keeps them + // from clobbering each other regardless of which one (if + // either) actually has something to do. + if (winner.sessionId !== canonicalSessionId && winner.ackKeys.length > 0) { + const winnerStored = this.store.sessions.getSessionByNamespace(winner.sessionId, namespace) + if (winnerStored) { + pendingAckTransfer = { + fromSessionId: winner.sessionId, + winningKey, + sourceSnapshot: { + blockedAckAt: winnerStored.blockedAckAt, + blockedAckKeys: winnerStored.blockedAckKeys, + blockedAckReason: winnerStored.blockedAckReason + } + } + } + } + } + + return { + signal: winner?.derived.signal ?? null, + boundaryAt: winner?.derived.boundaryAt ?? Date.now(), + authorCutoff: winner?.derived.authorCutoff ?? null, + pendingCanonicalAckEdit, + pendingAckTransfer + } + } + + /** + * Commit a projection already computed by + * `computeNotifyStateAcrossDuplicateSessions` (#1717). + * + * MUST run AFTER the merge finishes copying and emitting appended + * transcript rows, never before: `emitImportedMessageEvents` replays + * each copied row through live ingestion + * (`SyncEngine.handleRealtimeEvent`'s `message-received` branch), which + * unconditionally overwrites the session's notify signal from whatever + * footer content that ONE row happens to carry — with no knowledge that + * a correct, already-computed reconciliation already accounted for it. + * Replaying a copied REPLY never undoes that (an imported row never goes + * through the delivery-confirmation callback a real reply does), so an + * answered blocker could resurface as blocked purely from replaying its + * own already-resolved footer back through the live path. Committing + * the precomputed projection last makes it the final word regardless of + * what the replay touched. + * + * Also applies `pendingCanonicalAckEdit` when present, for the same + * reason and at the same point: a caller must not reach here unless + * the merge it was computed for actually succeeded (#1717 cold-review + * round 36). + */ + applyReconciledNotifyState( + sessionId: string, + namespace: string, + computed: { + signal: { status: string; at: number; note: string | null; receivedAt?: number | null } | null + boundaryAt: number | null + authorCutoff: number | null + pendingCanonicalAckEdit?: + | { kind: 'clear' } + | { kind: 'set'; at: number; reason: string; keys: string[] } + | null + pendingAckTransfer?: { + fromSessionId: string + winningKey: string + sourceSnapshot: { blockedAckAt: number | null; blockedAckKeys: string[] | null; blockedAckReason: string | null } + } | null + } + ): void { + this.sessionCache.replaceNotifyAfterTruncate( + sessionId, + computed.signal, + computed.boundaryAt ?? Date.now(), + computed.authorCutoff + ) + if (computed.pendingCanonicalAckEdit?.kind === 'clear') { + this.store.sessions.clearSessionBlockedAck(sessionId, namespace) + } else if (computed.pendingCanonicalAckEdit?.kind === 'set') { + const edit = computed.pendingCanonicalAckEdit + this.store.sessions.setSessionBlockedAck(sessionId, { + at: edit.at, + reason: edit.reason, + keys: edit.keys + }, namespace) + } + // Strip BEFORE transfer, never the reverse: both can touch the + // SAME coincidental key when canonical answered its own dismissed + // footer and the winner is a distinct, also-dismissed footer + // sharing that key. Applying the strip first, against canonical's + // pre-transfer keys, then letting the transfer's own fresh read + // union the winner's keys back in — reading canonical's keys + // AFTER the strip rather than before — is what keeps the winner's + // legitimate key from being removed by a strip that was computed + // before the transfer added it (#1717 cold-review round 36). + if (computed.pendingAckTransfer) { + const transfer = computed.pendingAckTransfer + this.transferBlockedAck( + transfer.fromSessionId, + sessionId, + namespace, + new Map([[transfer.winningKey, transfer.winningKey]]), + transfer.sourceSnapshot + ) + } + } + private resolveOnlineMachineForSession( session: Session, namespace: string, @@ -826,6 +1789,23 @@ export class SyncEngine { // Capture is independent of chat display settings (#1462/#1464). const session = this.getSession(event.sessionId) if (session) { + // #1717: stamp the footer onto the session first, so the + // blocked session-list chrome is not hostage to work-graph + // validation bounds failing on the same message. + const notifySignal = extractSessionNotifySignal( + event.message.content, + event.message.createdAt + ) + if (notifySignal) { + // Hub arrival is what the delivery boundary is compared + // against — the footer's own timestamp is the runner's + // clock, and a position is reusable and merge-renumbered. + this.sessionCache.setSessionLastNotify(session.id, { + ...notifySignal, + receivedAt: messageReceivedAt(event.message) + }) + } + try { ingestNotifySummaryFromMessage({ store: this.store, @@ -1348,6 +2328,22 @@ export class SyncEngine { this.sessionCache.transferAttachedJobs(fromSessionId, toSessionId, namespace) } + /** The next turn is maintenance, so it must not clear the footer (#1717). */ + markMaintenanceTurn(sessionId: string): void { + this.sessionCache.markMaintenanceTurn(sessionId) + } + + /** Carry a dismissal across a merge that copies messages itself (#1717). */ + transferBlockedAck( + fromSessionId: string, + toSessionId: string, + namespace: string, + notifyKeyRemap?: ReadonlyMap, + sourceSnapshot?: { blockedAckAt: number | null; blockedAckKeys: string[] | null; blockedAckReason: string | null } + ): void { + this.sessionCache.transferBlockedAck(fromSessionId, toSessionId, namespace, notifyKeyRemap, sourceSnapshot) + } + /** Shared REST/SSE watermark allocator for attachedJob patches. */ allocateAttachedJobVersion(sessionId: string): number { return this.sessionCache.allocateAttachedJobVersion(sessionId) @@ -2080,7 +3076,17 @@ export class SyncEngine { { touchUpdatedAt: false }) this.sessionCache.refreshSession(actualSessionId) } - this.sessionCache.markMessageQueued(actualSessionId, Date.now(), activeTurnStartedAt) + // A future-scheduled message is deliberately withheld from the CLI by + // `MessageService.sendMessage`, so the agent has not been given the + // reply yet. Marking it queued would start a thinking turn that nothing + // ends, and (#1717) clear the blocked footer for a blocker the operator + // has not actually answered — cancelling the schedule would leave it + // erased. The matured-scheduled path marks it queued when it really is. + const futureScheduled = typeof payload.scheduledAt === 'number' + && payload.scheduledAt > Date.now() + if (!futureScheduled) { + this.sessionCache.markMessageQueued(actualSessionId, Date.now(), activeTurnStartedAt) + } this.sessionCache.recordSessionActivity(actualSessionId, Date.now()) } @@ -3040,7 +4046,7 @@ export class SyncEngine { // reject when a turn completes in between, so the token never pins // a tail the sampled cut does not cover (same guard as the // OpenCode rewind reservation). - const fingerprintBefore = createHash('sha256').update(JSON.stringify(rows)).digest('hex') + const fingerprintBefore = hashOpenCodeRewindTranscript(rows) try { nativeCut = await this.rpcGateway.previewForkBoundary(sessionId, mode === 'message' ? { mode, messageLocalId } : { mode }) @@ -3048,7 +4054,7 @@ export class SyncEngine { return { type: 'error', message: error instanceof Error ? error.message : String(error) } } rows = this.store.messages.getAllMessages(sessionId) - if (createHash('sha256').update(JSON.stringify(rows)).digest('hex') !== fingerprintBefore) { + if (hashOpenCodeRewindTranscript(rows) !== fingerprintBefore) { return { type: 'error', message: 'The source conversation changed while the preview was prepared; try again' } } } @@ -3275,7 +4281,15 @@ export class SyncEngine { createdAt: message.createdAt, localId: message.localId, invokedAt: message.invokedAt, - scheduledAt: message.scheduledAt + scheduledAt: message.scheduledAt, + // Carried, not dropped: without these, a copied footer's + // position is judged on `createdAt` (the runner's own + // clock) instead of real hub arrival, which can place a + // slow-to-report footer "before" the prompt that + // actually preceded its arrival and read it as already + // answered (#1717 cold-review round 34). + receivedAt: message.receivedAt, + agentDelivered: message.agentDelivered })) ) this.sessionCache.rebuildTodosFromTranscript(childId) @@ -3513,6 +4527,7 @@ export class SyncEngine { this.store.messages.truncateMessagesFromLocalId(sessionId, truncateFromLocalId, [], discardedThroughSeq) this.scrubHistoryLocators(sessionId, namespace) this.sessionCache.rebuildTodosFromTranscript(sessionId) + this.reconcileNotifySignalAfterTruncate(sessionId) this.markClaudeRewindCutApplied(sessionId, namespace, truncateFromLocalId) this.eventPublisher.emit({ type: 'messages-invalidated', @@ -3752,7 +4767,7 @@ export class SyncEngine { workerId: metadata.opencodeWorkerId, workerPid: metadata.opencodeWorkerProcess.pid, workerStartMarker: metadata.opencodeWorkerProcess.startMarker, requestedLocalId: localId, nativeMessageId, cutoffSeq: boundary.seq, sourceEpoch: this.store.messages.getMessageEpoch(session.id), sourceMaxSeq: Math.max(0, ...messages.map(m => m.seq)), - sourceTranscriptHash: createHash('sha256').update(JSON.stringify(messages)).digest('hex'), + sourceTranscriptHash: hashOpenCodeRewindTranscript(messages), reservationVersion: current.metadataVersion + 1, phase: 'reserved' } // Durable reservation before the first native/RPC await. No generic // metadata retry can reserve against a different source version. @@ -3800,7 +4815,7 @@ export class SyncEngine { const rows = this.store.messages.getAllMessages(sessionId) const hubBoundary = rows.find(m => m.localId === op.requestedLocalId && m.seq === op.cutoffSeq && m.invokedAt != null) if (this.store.messages.getMessageEpoch(sessionId) !== op.sourceEpoch - || createHash('sha256').update(JSON.stringify(rows)).digest('hex') !== op.sourceTranscriptHash + || hashOpenCodeRewindTranscript(rows) !== op.sourceTranscriptHash || Math.max(0, ...rows.map(m => m.seq)) !== op.sourceMaxSeq || !hubBoundary || this.store.messages.getUninvokedLocalMessages(sessionId).length) throw new Error('OpenCode source transcript changed') @@ -3838,6 +4853,11 @@ export class SyncEngine { if (invalidated) { const todos = this.store.messages.getAllMessages(sessionId).map(m => extractTodoWriteTodosFromMessageContent(m.content)).filter(Boolean).at(-1) ?? null this.store.sessions.replaceSessionTodos(sessionId, todos, namespace) + // OpenCode rewinds here rather than through + // `truncateHubTranscriptFrom`, so it needs the same notify + // reconcile: a rollback starts no new turn, and the refresh + // below would otherwise restore the deleted footer's signal. + this.reconcileNotifySignalAfterTruncate(sessionId) } return next }) @@ -4357,12 +5377,17 @@ export class SyncEngine { }) } - async deleteSession(sessionId: string): Promise { + /** Throws if a pending operation makes `deleteSession` refuse this session. */ + assertSessionDeletable(sessionId: string): void { if (this.openCodeRewindPending(sessionId)) throw new Error('OpenCode rewind requires reconciliation') if (this.sessionCache.getSession(sessionId)?.metadata?.codexResumePending) throw new Error('Codex resume startup is unconfirmed; archive to confirm termination before deleting') if (this.historyActionsInFlight.has(sessionId) || this.archivedForkPending(sessionId)) { throw new Error('Archived fork is pending; reconcile it before deleting the source') } + } + + async deleteSession(sessionId: string): Promise { + this.assertSessionDeletable(sessionId) await this.sessionCache.deleteSession(sessionId) this.titleTurnCompletedIds.delete(sessionId) this.automaticTitleSuggestionService.forgetSession(sessionId) diff --git a/hub/src/sync/syncEngineHandleRealtimeEvent.test.ts b/hub/src/sync/syncEngineHandleRealtimeEvent.test.ts index 04c5397ec61..c72387bdc6d 100644 --- a/hub/src/sync/syncEngineHandleRealtimeEvent.test.ts +++ b/hub/src/sync/syncEngineHandleRealtimeEvent.test.ts @@ -203,6 +203,91 @@ describe('SyncEngine.handleRealtimeEvent notify → work-graph ingest', () => { expect(rows[0]!.payloadJson).toMatchObject({ status: 'done' }) }) + function footerEvent( + sessionId: string, + id: string, + seq: number, + createdAt: number, + status: string + ): SyncEvent { + return { + type: 'message-received', + sessionId, + message: { + id, + seq, + localId: null, + createdAt, + content: { + role: 'agent', + content: { + type: 'output', + data: { + type: 'assistant', + message: { + content: [{ + type: 'text', + text: `Update.\n\nAGENT_NOTIFY_SUMMARY {"status":"${status}","summary":"s-${status}","project":"hapi"}` + }] + } + } + } + } + } + } as SyncEvent + } + + it('a replayed older footer does not restore a blocker the newer one closed', () => { + // Through LIVE ingestion, which is the only path that supplies a `seq` + // — a store/cache test without one cannot see this at all. + // + // `seq` is allocated MAX(seq)+1 at insertion, so a footer Claude + // replays AFTER a newer one carries a HIGHER seq while being older in + // fact. Ordering footers against each other by seq therefore let the + // stale `blocked` win and put an answered session back into Blocked. + // Two footers share one runner clock, so between them authorship time + // is authoritative; seq is only for comparing a footer to a + // hub-stamped reply. + const { engine, store } = makeEngine() + const session = store.sessions.getOrCreateSession( + 'notify-replay-order', + { path: '/tmp', host: 'h', flavor: 'claude' }, + null, + 'default' + ) + engine.handleRealtimeEvent({ type: 'session-updated', sessionId: session.id }) + + const blockedAt = 1_660_000_000_000 + // The agent reported blocked, then reported done ten seconds later. + engine.handleRealtimeEvent(footerEvent(session.id, 'm-1', 1, blockedAt, 'blocked')) + engine.handleRealtimeEvent(footerEvent(session.id, 'm-2', 2, blockedAt + 10_000, 'done')) + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBe('done') + + // Now the older `blocked` turn is replayed, keeping its original + // timestamp but landing at a higher insertion seq. + engine.handleRealtimeEvent(footerEvent(session.id, 'm-3', 3, blockedAt, 'blocked')) + + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBe('done') + }) + + it('still accepts a genuinely newer footer through live ingestion', () => { + // Positive control: the guard above must not simply freeze the footer. + const { engine, store } = makeEngine() + const session = store.sessions.getOrCreateSession( + 'notify-replay-forward', + { path: '/tmp', host: 'h', flavor: 'claude' }, + null, + 'default' + ) + engine.handleRealtimeEvent({ type: 'session-updated', sessionId: session.id }) + + const base = 1_660_000_000_000 + engine.handleRealtimeEvent(footerEvent(session.id, 'f-1', 1, base, 'done')) + engine.handleRealtimeEvent(footerEvent(session.id, 'f-2', 2, base + 5_000, 'blocked')) + + expect(store.sessions.getSession(session.id)?.lastNotifyStatus).toBe('blocked') + }) + it('does not ingest when the footer is missing', () => { const { engine, store } = makeEngine() const session = store.sessions.getOrCreateSession( diff --git a/hub/src/sync/workGraphNotifyIngest.test.ts b/hub/src/sync/workGraphNotifyIngest.test.ts index 42bf1c3b417..f851ae47376 100644 --- a/hub/src/sync/workGraphNotifyIngest.test.ts +++ b/hub/src/sync/workGraphNotifyIngest.test.ts @@ -1,14 +1,19 @@ import { describe, expect, it } from 'bun:test' -import { WORK_GRAPH_MAX_STRING, WORK_GRAPH_MAX_SUMMARY } from '@hapi/protocol' +import { WORK_GRAPH_MAX_STRING, WORK_GRAPH_MAX_SUMMARY, WorkGraphEventCreateSchema } from '@hapi/protocol' import type { SyncEvent } from '@hapi/protocol/types' import { Store } from '../store' import type { EventPublisher } from './eventPublisher' import { SessionCache } from './sessionCache' import { WORK_AD_DEFAULT_TTL_MS, + buildOperatorUnblockEvent, buildWorkAdFromNotify, + extractSessionNotifySignal, ingestNotifySummaryFromMessage, - mapNotifyStatusToWorkAdStatus + isDeliveredOperatorReply, + isOperatorReplyMessage, + mapNotifyStatusToWorkAdStatus, + operatorReplyDeliveredAt } from './workGraphNotifyIngest' function assistantOutput(text: string) { @@ -1203,3 +1208,352 @@ describe('notify cause consumption watermark', () => { expect((next?.event.payloadJson as { causeSeq?: number })?.causeSeq).toBe(nextUser.seq) }) }) + +describe('extractSessionNotifySignal (#1717 blocked session-list chrome)', () => { + it('ignores a subagent (sidechain) footer', () => { + // A subagent's footer describes the subagent, not the session. Without + // this a background subagent's `done` erases the main agent's + // unanswered blocker, and its `blocked` flags a finished parent. + const text = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'done', summary: 'subtask finished' }) + const sidechain = { + role: 'agent', + content: { + type: 'output', + data: { + type: 'assistant', + isSidechain: true, + message: { content: [{ type: 'text', text }] } + } + } + } + expect(extractSessionNotifySignal(sidechain, 1_000)).toBeNull() + }) + + it('ignores a subagent footer carrying parentToolUseId instead', () => { + const text = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'subtask stuck' }) + const sidechain = { + role: 'agent', + content: { + type: 'output', + data: { + type: 'assistant', + parentToolUseId: 'toolu_abc123', + message: { content: [{ type: 'text', text }] } + } + } + } + expect(extractSessionNotifySignal(sidechain, 1_000)).toBeNull() + }) + + it('still reads a main-agent footer', () => { + const text = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + expect(extractSessionNotifySignal(assistantOutput(text), 1_000)?.status).toBe('blocked') + }) + + const ts = 1_700_000_000_000 + + it('lowercases the status and carries the action as the operator note', () => { + const signal = extractSessionNotifySignal( + assistantOutput('Stuck.\nAGENT_NOTIFY_SUMMARY {"version":1,"status":"BLOCKED","action":"need prod creds","summary":"cannot deploy"}'), + ts + ) + expect(signal).toEqual({ status: 'blocked', at: ts, note: 'need prod creds' }) + }) + + it('falls back to summary when the footer carries no action', () => { + const signal = extractSessionNotifySignal( + assistantOutput('AGENT_NOTIFY_SUMMARY {"version":1,"status":"stalled","summary":"waiting on review"}'), + ts + ) + expect(signal).toEqual({ status: 'stalled', at: ts, note: 'waiting on review' }) + }) + + it('keeps non-blocking statuses but stores no note for them', () => { + // `done` must still be recorded: it is what clears a stale `blocked`. + const signal = extractSessionNotifySignal( + assistantOutput('AGENT_NOTIFY_SUMMARY {"version":1,"status":"done","action":"nothing","summary":"shipped"}'), + ts + ) + expect(signal).toEqual({ status: 'done', at: ts, note: null }) + }) + + it('ignores user messages and footerless agent prose', () => { + expect(extractSessionNotifySignal( + userInbound('AGENT_NOTIFY_SUMMARY {"version":1,"status":"blocked"}'), + ts + )).toBeNull() + expect(extractSessionNotifySignal(assistantOutput('just some prose'), ts)).toBeNull() + }) + + it('ignores a footer with no status', () => { + expect(extractSessionNotifySignal( + assistantOutput('AGENT_NOTIFY_SUMMARY {"version":1,"summary":"no status here"}'), + ts + )).toBeNull() + }) +}) + +describe('isOperatorReplyMessage (#1717 backfill boundary)', () => { + it('recognises a real operator prompt', () => { + expect(isOperatorReplyMessage(userInbound('unblocked: use the staging key'))).toBe(true) + }) + + it('ignores the Claude transcript echo of that same prompt', () => { + // The echo replays the prompt as a second role=user row; treating it as + // a fresh reply would move the backfill boundary past a real footer. + expect(isOperatorReplyMessage( + userInbound('unblocked: use the staging key', 'cli', { isTranscriptEcho: true }) + )).toBe(false) + }) + + it('ignores agent output', () => { + expect(isOperatorReplyMessage(assistantOutput('working on it'))).toBe(false) + }) +}) + +describe('extractSessionNotifySignal ignores live stream snapshots (#1717)', () => { + const footer = 'Working.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + + function codexMessage(extra: Record) { + return { + role: 'agent', + content: { type: 'codex', data: { type: 'message', message: footer, ...extra } } + } + } + + it('reads a footer from settled output', () => { + // Positive control: without it the null assertions below would pass on + // any content shape this function simply cannot read. + expect(extractSessionNotifySignal(assistantOutput(footer), 1_000)?.status).toBe('blocked') + }) + + it('reads a footer from a settled codex message', () => { + // The shape the snapshot case is built from, proving it parses when it + // is not marked live — so the next test isolates `live`, nothing else. + expect(extractSessionNotifySignal(codexMessage({}), 1_000)?.status).toBe('blocked') + }) + + it('ignores a live snapshot of a message still being written', () => { + // A snapshot is a transient cumulative render that the hub sweeps once + // the message settles. It can end on a valid footer while the settled + // message goes on to add prose after it and carry no valid footer — + // and the list kept the status derived from the snapshot, showing the + // session blocked once thinking ended. The work-graph ingest has + // skipped these all along; list status now agrees. + expect(extractSessionNotifySignal( + codexMessage({ streamSnapshot: true, live: true }), 1_000 + )).toBeNull() + }) + + it('still reads a snapshot-shaped message once it is no longer live', () => { + // `live` is what marks it transient; a settled row that kept the + // snapshot shape is the agent's real output and must still count. + expect(extractSessionNotifySignal( + codexMessage({ streamSnapshot: true }), 1_000 + )?.status).toBe('blocked') + }) +}) + +describe('isDeliveredOperatorReply (#1717 what counts as an answer)', () => { + function reply(overrides: { + invokedAt?: number | null + sweptAt?: number | null + agentDelivered?: number | null + }) { + // `in`, not `??`: an explicit null is the case under test here, and + // `??` would quietly substitute the default for it. + return { + content: userInbound('here is the key'), + scheduledAt: null, + invokedAt: 'invokedAt' in overrides ? overrides.invokedAt! : 1_000, + sweptAt: 'sweptAt' in overrides ? overrides.sweptAt! : null, + agentDelivered: 'agentDelivered' in overrides ? overrides.agentDelivered! : null + } + } + + it('counts a prompt the agent was actually handed', () => { + expect(isDeliveredOperatorReply(reply({}))).toBe(true) + }) + + it('does not count a prompt still sitting in the queue', () => { + // A null `invokedAt` means the agent never saw it, so treating it as an + // answer buries a footer nobody replied to. + expect(isDeliveredOperatorReply(reply({ invokedAt: null }))).toBe(false) + }) + + it('does not count the session-end sweep', () => { + // The sweep stamps `invokedAt` to unpin the floating bar on rows the + // runtime never received. Treating that as a delivered reply let a + // session simply ending answer a blocker nobody replied to. + expect(isDeliveredOperatorReply(reply({ sweptAt: 1_000 }))).toBe(false) + }) + + it('does not count a row the CLI handled locally', () => { + // Independent of the sweep check: a slash command the CLI handled + // itself has `invoked_at` stamped and no sweep marker at all. + expect(isDeliveredOperatorReply(reply({ agentDelivered: 0 }))).toBe(false) + }) + + it('rejects a swept row on the disposition alone, without the sweep marker', () => { + // Defence in depth for the case above: the sweep now records + // `agentDelivered: false` as well, so losing the `sweptAt` comparison + // would not silently turn session-end into an answer. + expect(isDeliveredOperatorReply(reply({ sweptAt: null, agentDelivered: 0 }))).toBe(false) + }) + + it('treats a row written before the disposition existed as delivered', () => { + // NULL is "not recorded", and history already on disk must not be + // retroactively un-answered by an upgrade. + expect(isDeliveredOperatorReply(reply({ agentDelivered: null }))).toBe(true) + }) +}) + +describe('operatorReplyDeliveredAt (#1717 cold-review round 36)', () => { + it('trusts invokedAt for a confirmed queue delivery even after localId is cleared', () => { + // A session merge's collision handling clears `local_id` on an + // older copy while preserving its genuinely hub-stamped + // `invoked_at` and `agent_delivered`, purely to sever its ack path + // — nothing to do with whether the hub ever actually saw it. + // `localId == null` alone cannot tell this apart from a reply + // typed straight into a local terminal, which never goes through + // the queue at all. + const confirmedThenCollisionCleared = { + createdAt: 1_000, + receivedAt: 1_000, + scheduledAt: null, + invokedAt: 5_000, + agentDelivered: 1, + localId: null + } + expect(operatorReplyDeliveredAt(confirmedThenCollisionCleared)).toBe(5_000) + }) + + it('falls back to hub arrival for a genuinely local reply that never queued', () => { + // Positive control: a row that truly never went through the queue + // has no `agentDelivered` marker at all (never set by + // markMessagesInvoked), so the fallback to hub arrival time — + // the only clock comparable to a footer's — still applies. + const neverQueued = { + createdAt: 1_000, + receivedAt: 1_000, + scheduledAt: null, + invokedAt: 5_000, + agentDelivered: null, + localId: null + } + expect(operatorReplyDeliveredAt(neverQueued)).toBe(1_000) + }) + + it('still trusts invokedAt for a row that still has its localId', () => { + // Unaffected baseline: the ordinary queued-and-delivered case, + // local id intact. + const stillQueued = { + createdAt: 1_000, + receivedAt: 1_000, + scheduledAt: null, + invokedAt: 5_000, + agentDelivered: 1, + localId: 'local-1' + } + expect(operatorReplyDeliveredAt(stillQueued)).toBe(5_000) + }) +}) + +describe('buildOperatorUnblockEvent (#1717 posterity record)', () => { + it('positions the event at the decision time, with the blocker time as detail', () => { + // The session event log sorts by event time. Stamping a days-old + // blocker's timestamp filed today's rationale among last week's + // activity — or outside a recent-events window entirely — so the + // operator could not find the reason they had just written. + const decidedAt = 1_700_000_000_000 + const blockedAt = decidedAt - 3 * 86_400_000 + const event = buildOperatorUnblockEvent({ + sessionId: 's1', + ownerUserId: 7, + reason: 'handled out of band', + acknowledgedAt: decidedAt, + observedAt: blockedAt, + observedKey: `notify:${blockedAt}`, + priorNotify: { status: 'blocked', at: blockedAt, note: 'needs a key' } + }) + + expect(event.payload_json).toMatchObject({ + acknowledged_at: decidedAt, + observed_at: blockedAt, + blocker_key: `notify:${blockedAt}`, + prior_at: blockedAt + }) + // Both are kept: the decision is findable in time order, and what was + // dismissed is still identifiable. + const payload = event.payload_json as { acknowledged_at: number; observed_at: number } + expect(payload.acknowledged_at).not.toBe(payload.observed_at) + }) + + it('records the operator rationale against the session, as a human principal', () => { + const event = buildOperatorUnblockEvent({ + sessionId: 'sess-1', + ownerUserId: 42, + reason: 'handled outside HAPI', + acknowledgedAt: 1700, + priorNotify: { status: 'blocked', at: 1000, note: 'needs prod creds' } + }) + + expect(event.event_type).toBe('operator_unblock') + expect(event.related_session_id).toBe('sess-1') + expect(event.summary).toBe('handled outside HAPI') + expect(event.principal).toEqual({ kind: 'human', id: '42' }) + expect(event.payload_json).toEqual({ + reason: 'handled outside HAPI', + acknowledged_at: 1700, + // Null here because this call names no observed blocker; the + // identity is recorded whenever the dialog supplies one. + blocker_key: null, + // Likewise null without an observed blocker. When present it is + // the dismissed blocker's own timestamp, kept as detail so + // `acknowledged_at` can stay the decision time. + observed_at: null, + // The agent's claim travels with the dismissal so a reader can tell + // "operator disagreed" from "resolved elsewhere". + prior_status: 'blocked', + prior_note: 'needs prod creds', + prior_at: 1000 + }) + }) + + it('is valid against the work-graph create schema', () => { + const event = buildOperatorUnblockEvent({ + sessionId: 'sess-1', + ownerUserId: 'owner-abc', + reason: 'not actually blocked', + acknowledgedAt: 1700, + priorNotify: null + }) + expect(WorkGraphEventCreateSchema.safeParse(event).success).toBe(true) + }) + + it('survives an oversized rationale without breaking ledger bounds', () => { + const event = buildOperatorUnblockEvent({ + sessionId: 'sess-1', + ownerUserId: 1, + reason: 'x'.repeat(WORK_GRAPH_MAX_SUMMARY * 2), + acknowledgedAt: 1, + priorNotify: null + }) + expect(WorkGraphEventCreateSchema.safeParse(event).success).toBe(true) + }) + + it('nulls the prior claim when no footer was stored', () => { + const event = buildOperatorUnblockEvent({ + sessionId: 'sess-1', + ownerUserId: 1, + reason: 'abandoning this work', + acknowledgedAt: 5, + priorNotify: null + }) + expect(event.payload_json).toMatchObject({ prior_status: null, prior_note: null, prior_at: null }) + }) +}) diff --git a/hub/src/sync/workGraphNotifyIngest.ts b/hub/src/sync/workGraphNotifyIngest.ts index cbea45b9893..8c5c0ebdcfe 100644 --- a/hub/src/sync/workGraphNotifyIngest.ts +++ b/hub/src/sync/workGraphNotifyIngest.ts @@ -9,7 +9,11 @@ import { unwrapRoleWrappedRecordEnvelope, type NotifySummary, type WorkGraphEvent, - type WorkGraphEventCreate + type WorkGraphEventCreate, + isBlockedNotifyStatus, + normalizeNotifyStatus, + pickNotifyNote, + type SessionNotifySignal } from '@hapi/protocol' import type { Store, StoredMessage } from '../store' import { WorkGraphValidationError } from '../store' @@ -600,3 +604,300 @@ export function ingestNotifySummaryFromMessage(input: NotifyIngestInput): Notify throw error } } + +/** + * True for an operator prompt the agent has actually been given. + * + * A scheduled message is withheld from the CLI until it matures AND is + * invoked, so an overdue-but-uninvoked one has still answered nothing — the + * due time alone is not delivery. Ordering uses the invocation time, because + * that is when the agent saw it. + */ +export function isDeliveredOperatorReply( + message: { + content: unknown + scheduledAt: number | null + invokedAt: number | null + sweptAt?: number | null + agentDelivered?: number | null + } +): boolean { + if (!isOperatorReplyMessage(message.content)) return false + // The CLI consumed the row synchronously without prompting the agent: a + // slash command it handled itself, a rejected or aborted message, a failed + // steer. `invoked_at` is stamped regardless, so without the persisted + // disposition the transcript paths read it as an answer the agent never + // got. NULL is "written before this was recorded" and stays permissive. + if (message.agentDelivered === 0) return false + // The session-end sweep stamps `invokedAt` to unpin the floating bar, on + // rows the runtime never received. Its own documentation calls that + // synthetic. Treating it as a delivered reply let a session end answer a + // blocker nobody replied to. + if (message.sweptAt != null && message.sweptAt === message.invokedAt) return false + // Delivery evidence for EVERY queued reply, not just scheduled ones: a + // prompt still sitting in the queue with a null `invokedAt` has not + // reached the agent either, and treating it as an answer buries a footer + // the agent never saw. + return message.invokedAt !== null +} + +/** + * When the hub received a message, as opposed to when its author wrote it. + * + * The key a delivery boundary is measured against (#1717). `createdAt` is the + * agent runner's own clock, preserved verbatim through transcript replay, so it + * cannot be compared with the hub-stamped `invokedAt` of a reply. Hub arrival + * can: both sides are then the same clock. A position cannot be used either — + * insertion `seq` is allocated as MAX(seq)+1, so cancelling a queued row frees + * its number for reuse, and a merge renumbers one side's positions into + * something synthetic rather than real. + * + * Rows written before `received_at` existed fall back to `createdAt`, the only + * evidence they carry. + */ +export function messageReceivedAt( + message: { createdAt: number; receivedAt?: number | null } +): number { + return message.receivedAt ?? message.createdAt +} + +/** + * When a delivered reply reached the agent, in the hub's clock (#1717). + * + * `invoked_at` is hub-stamped only for a reply that went through the hub + * QUEUE. A prompt typed straight into a local agent terminal has no local id, + * so nothing ever stamped it and `invoked_at` carries the runner's transcript + * clock — measuring that against a footer's hub arrival is the cross-clock + * comparison this area exists to avoid. For those, the row's own hub arrival + * is the right stand-in, because that is when the hub saw the reply. + * + * `localId == null` alone is not proof a reply was never queued: a session + * merge's collision handling clears `local_id` on an older copy while + * preserving its genuinely hub-stamped `invoked_at` and `agent_delivered` + * (`messages.ts`'s `mergeSessionMessages`) — purely to sever its ack path, + * nothing to do with whether the hub ever saw it. `agent_delivered` is only + * ever set to `1` by a real queue-ack (`markMessagesInvoked`) or carried + * forward from one by a copy, so it survives that clearing and is the + * positive signal a never-queued local reply has no way to produce (#1717 + * cold-review round 36). + * + * Shared by every path that has to order a reply against a footer — live + * ingestion, the transcript derivation, and the session merges — because the + * two that had their own copy of this rule disagreed about local replies. + */ +export function operatorReplyDeliveredAt( + message: { + createdAt: number + receivedAt?: number | null + scheduledAt: number | null + invokedAt: number | null + agentDelivered?: number | null + localId?: string | null + } +): number { + const wasConfirmedThroughTheQueue = message.localId != null || message.agentDelivered === 1 + return wasConfirmedThroughTheQueue + ? deliveredOperatorReplyAt(message) + : messageReceivedAt(message) +} + +/** + * When the agent actually saw a delivered reply. + */ +export function deliveredOperatorReplyAt( + message: { createdAt: number; scheduledAt: number | null; invokedAt: number | null } +): number { + // Invocation time, always. A reply composed before a footer can be + // invoked after it; ordering on `createdAt` would let that reply "answer" + // a footer written while it was still queued. + return message.invokedAt ?? message.createdAt +} + +/** + * Stable identity for a notify footer, independent of which session or + * which `createdAt` it happens to carry there (#1717). + * + * A Codex Desktop duplicate-session merge can hold two separate + * PROJECTIONS of the exact same underlying footer — a live Hapi session's + * own copy and a Desktop import of the same thread — each stamped with + * its own session's clock, so the same event can carry two different + * `createdAt` values depending on which session you read it from. Text + * plus status plus note is not enough on its own either: a Claude replay + * genuinely repeats the same footer a second time, same fields, and that + * replay IS meant to compare equal to the original. The native transcript + * id breaks the tie where one exists: an imported row carries it as + * `localId`, so two distinct turns that happen to report the same status + * and note are still two different messages. A live Claude reply has no + * local id at all and shares every field with the row it duplicates, so + * there the text (plus status, author time, and note) IS the only + * identity available. + */ +/** + * The joins below use a literal NUL byte, not a space, as the field + * separator — deliberately: it is the one character guaranteed not to + * appear in a status, note, or local id, so no combination of real field + * values can collide into the same key a different combination would + * also produce. This is intentional design, not corruption — but it + * means this file is byte-for-byte binary to a plain `grep`, which skips + * it silently and looks identical to "the string isn't here" (#1717 + * cold-review round 36). Use `grep -a` (or any NUL-tolerant search) on + * this file. + */ +export function notifySignalIdentity( + message: { localId: string | null }, + signal: { status: string; at: number; note: string | null } +): string { + return message.localId == null + ? `text${signal.status}${signal.at}${signal.note ?? ''}` + : `msg${message.localId}` +} + +/** + * True for a real operator prompt — the thing that answers a blocked agent. + * Excludes the Claude jsonl transcript echo, which replays the same prompt as + * a second `role=user` row and would otherwise look like a fresh reply. + */ +export function isOperatorReplyMessage(content: unknown): boolean { + if (!isInboundUserMessage(content)) return false + return asRecord(asRecord(content)?.meta)?.isTranscriptEcho !== true +} + +/** + * Parse an agent message down to the compact signal the session list renders + * (#1717 blocked chrome). + * + * Shares the agent-message gating and footer extraction with the work-graph + * ingest below so both surfaces agree on what counts as a footer — the list + * must never light up on something the ledger ignored, or vice versa. + * + * `note` is only carried for blocked statuses: it exists to give the row + * tooltip something actionable, and storing it for every `done` footer would + * grow the /sessions payload for nothing. + */ +/** + * True for Claude subagent (sidechain) output. + * + * Checked on the raw record and one envelope level down, because the local + * transcript scanner and the remote SDK converter wrap the flags differently. + */ +function isSidechainOutput(content: unknown, depth: number = 0): boolean { + const record = asRecord(content) + if (!record || depth > 4) return false + if (record.isSidechain === true) return true + if (typeof record.parentToolUseId === 'string' && record.parentToolUseId.length > 0) return true + for (const key of ['content', 'data', 'message'] as const) { + if (isSidechainOutput(record[key], depth + 1)) return true + } + return false +} + +export function extractSessionNotifySignal( + content: unknown, + ts: number +): SessionNotifySignal | null { + if (!isAgentMessageContent(content)) { + return null + } + + // A subagent's footer describes the subagent, not the session. Both the + // local transcript scanner and the remote SDK converter forward sidechain + // assistant output, so without this a background subagent's `done` erases + // the main agent's unanswered blocker — or its `blocked` flags a parent + // that actually finished. + if (isSidechainOutput(content)) { + return null + } + + // A live stream snapshot is a transient cumulative render of a message + // still being written, and the hub sweeps it from the transcript once the + // message settles. OpenCode emits them, so a snapshot can end on a valid + // footer while the settled message goes on to add prose after it and carry + // no valid footer at all — and the list kept the status derived from the + // snapshot, showing blocked once thinking ended. The work-graph ingest has + // skipped these all along; list status has to agree, and for the same + // reason: only settled output is the agent's actual self-report. + if (isLiveStreamSnapshot(content)) { + return null + } + + const agentBody = unwrapRoleWrappedRecordEnvelope(content) + const agentContent = agentBody?.role === 'agent' ? agentBody.content : content + const plainText = extractAssistantPlainText(agentContent) + if (!plainText) { + return null + } + + const notify = extractNotifySummary(plainText) + if (!notify) { + return null + } + + const status = normalizeNotifyStatus(notify.status) + if (!status) { + return null + } + + return { + status, + at: ts, + note: isBlockedNotifyStatus(status) ? pickNotifyNote(notify) : null + } +} + +/** + * Ledger event for an operator's manual unblock (#1717). + * + * Pure so the recorded payload is testable without standing + * up a SyncEngine. Carries the agent's prior claim alongside the operator's + * rationale, so a reader can distinguish "operator disagreed with the agent" + * from "operator resolved it elsewhere" — the two have very different + * implications for whether the agent's judgement should be trusted next time. + */ +export function buildOperatorUnblockEvent(input: { + sessionId: string + ownerUserId: string | number + reason: string + /** When the operator made this decision — hub now, NOT the blocker's own + * timestamp. The session event log sorts by event time, so stamping a + * days-old blocker's time filed today's rationale among last week's + * activity, or outside a recent-events window entirely. */ + acknowledgedAt: number + /** The dismissed blocker's own timestamp, kept as a detail rather than as + * the event's position in the log. */ + observedAt?: number | null + /** Identity of the blocker the operator dismissed. Recorded even when the + * footer it named has since been replaced, so the event can still be + * matched back to what was actually reviewed. */ + observedKey?: string | null + priorNotify: NotifySummary | SessionNotifySignal | null +}): WorkGraphEventCreate { + const principalId = String(input.ownerUserId) + const prior = input.priorNotify + return { + source_kind: 'operator', + source_ref: principalId, + sink_kind: 'session', + sink_ref: input.sessionId, + event_type: 'operator_unblock', + summary: clampUtf8(input.reason, WORK_GRAPH_MAX_SUMMARY), + related_session_id: input.sessionId, + provenance: 'hapi-web/session-action-menu', + payload_json: { + reason: clampJsonUtf8(input.reason, WORK_GRAPH_MAX_STRING), + acknowledged_at: input.acknowledgedAt, + // The identity is recorded unconditionally. The prior_* fields go + // null when the footer named by the key has already been replaced, + // and without the key the event could not be matched back to what + // the operator actually dismissed — including for a live request, + // which has no footer at all. + blocker_key: input.observedKey + ? clampJsonUtf8(input.observedKey, WORK_GRAPH_MAX_STRING) + : null, + observed_at: input.observedAt ?? null, + prior_status: prior?.status ?? null, + prior_note: (prior && 'note' in prior ? prior.note : null) ?? null, + prior_at: (prior && 'at' in prior ? prior.at : null) ?? null + }, + principal: { kind: 'human', id: principalId } + } +} diff --git a/hub/src/web/routes/codexDesktop.test.ts b/hub/src/web/routes/codexDesktop.test.ts index 48138449a39..77717edc5b4 100644 --- a/hub/src/web/routes/codexDesktop.test.ts +++ b/hub/src/web/routes/codexDesktop.test.ts @@ -1,10 +1,11 @@ import { afterEach, describe, expect, it } from 'bun:test' +import type { Database } from 'bun:sqlite' import { randomUUID } from 'node:crypto' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Hono } from 'hono' -import { AGENT_MESSAGE_PAYLOAD_TYPE } from '@hapi/protocol' +import { AGENT_MESSAGE_PAYLOAD_TYPE, notifyBlockerKey, type SyncEvent } from '@hapi/protocol' import { Store } from '../../store' import { SyncEngine, type Machine } from '../../sync/syncEngine' import { RpcRegistry } from '../../socket/rpcRegistry' @@ -51,6 +52,9 @@ function createImportSyncEngine(store: Store, machines: Machine[], transcripts?: store.sessions.getOrCreateSession(tag, metadata, agentState, namespace) as unknown as ReturnType ), handleRealtimeEvent: () => {}, + reconcileNotifySignalAfterImport: () => {}, + computeNotifyStateAcrossDuplicateSessions: () => ({ signal: null, boundaryAt: null, authorCutoff: null }), + applyReconciledNotifyState: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') } @@ -1036,6 +1040,1859 @@ describe('Codex Desktop import routes', () => { } }) + it('does not duplicate a prompt that the live projection and the importer both hold', async () => { + // The live Codex projection and the Desktop importer mirror the same + // prompt under two different local ids. Keying on the native + // transcript id treated those as distinct occurrences and appended the + // imported copy a second time — and that copy's later timestamp let + // reconciliation read an initiating prompt as an answer and clear an + // unanswered blocker. One event, one row: occurrences are aligned by + // position among rows that share a key, so a mirror is not surplus. + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + const store = new Store(':memory:') + const canonical = store.sessions.getOrCreateSession( + 'canon-mirror', { codexSessionId: 'codex-thread-12' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-mirror', { codexSessionId: 'codex-thread-12' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + // Canonical holds filler plus the live projection's copy of the prompt. + for (let i = 0; i < 4; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `filler ${i}` }] } } + } + }, `mirror-filler-${i}`, base) + } + store.messages.addMessage(canonical.id, { + role: 'user', content: { type: 'text', text: 'Continue' }, meta: { sentFrom: 'webapp' } + }, 'live-projection-id', null, base + 1_000, base + 1_000) + store.messages.markMessagesInvoked(canonical.id, ['live-projection-id'], base + 2_000) + + // The duplicate holds the SAME event under the importer's id, with the + // same delivery time — one prompt, mirrored. + store.messages.addMessage(duplicate.id, { + role: 'user', content: { type: 'text', text: 'Continue' }, meta: { sentFrom: 'webapp' } + }, 'importer-id', null, base + 1_000, base + 1_000) + store.messages.markMessagesInvoked(duplicate.id, ['importer-id'], base + 2_000) + + const engine = { + getSessionsByNamespace: () => [], + transferBlockedAck: () => {}, + assertSessionDeletable: () => {}, + transferAttachedJobs: () => {}, + deleteSession: async (sessionId: string) => { + store.sessions.deleteSession(sessionId, 'default') + }, + handleRealtimeEvent: () => {}, + reconcileNotifySignalAfterImport: () => {}, + computeNotifyStateAcrossDuplicateSessions: () => ({ signal: null, boundaryAt: null, authorCutoff: null }), + applyReconciledNotifyState: () => {}, + recordSessionActivity: () => {} + } as unknown as SyncEngine + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-12'] }) + }) + expect(response.status).toBe(200) + const body = await response.json() as { merged: Array<{ canonicalSessionId?: string }> } + const survivorId = body.merged[0]?.canonicalSessionId + expect(survivorId).toBe(canonical.id) + + const prompts = store.messages.getAllMessages(survivorId!) + .filter((row) => JSON.stringify(row.content).includes('Continue')) + expect(prompts).toHaveLength(1) + } finally { + store.close() + } + }) + + + it('does not transfer a dismissal from a non-winning duplicate just because its footer text matches the survivor\'s (#1717 cold-review round 31)', async () => { + // Was "remaps a dismissed source footer's key to the surviving + // occurrence's own timestamp" (cold-review round 25) — that test's + // own premise (a different `createdAt` in two projections is still + // "the SAME event") is exactly the cross-session content-match + // assumption round 31 retired. Two sessions reporting identical + // footer text at different timestamps are not provably the same + // real occurrence without a stable cross-copy identity, which + // #1717 (hapi#2577) found does not exist for this pairing. The + // canonical row's OWN footer — nobody ever dismissed THAT specific + // occurrence — now correctly stays blocked rather than silently + // inheriting a sibling's unrelated-by-proof dismissal. + const { SyncEngine } = await import('../../sync/syncEngine') + const { RpcRegistry } = await import('../../socket/rpcRegistry') + const { notifyBlockerKey } = await import('@hapi/protocol') + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-footer-remap', { codexSessionId: 'codex-thread-25b', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-footer-remap', { codexSessionId: 'codex-thread-25b', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footerText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs creds' }) + + // Survivor: padding so it wins canonical selection, then its OWN + // projection of the footer — a different `createdAt` than the + // duplicate's copy of the same event. + for (let i = 0; i < 6; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `remap-pad-${i}`, base) + } + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'remap-canonical-footer', base + 5_000) + + // Duplicate: its OWN projection of the SAME footer, a different + // `createdAt` — and the operator already dismissed THIS occurrence. + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'remap-duplicate-footer', base + 1_000) + store.sessions.setSessionBlockedAck(duplicate.id, { + at: base + 1_000, + reason: 'handled', + keys: [notifyBlockerKey(base + 1_000)] + }, 'default') + + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-25b'] }) + }) + expect(response.status).toBe(200) + + const footers = store.messages.getAllMessages(canonical.id) + .filter((row) => JSON.stringify(row.content).includes('AGENT_NOTIFY_SUMMARY')) + // One footer — the duplicate's copy was deduplicated, not + // appended — and it kept the SURVIVOR's own createdAt. The + // transcript dedup rule is unrelated to the ack-transfer + // change and still holds. + expect(footers).toHaveLength(1) + expect(footers[0]!.createdAt).toBe(base + 5_000) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + // Neither key transfers: canonical's own occurrence was never + // dismissed, and the duplicate's dismissal (for a + // content-matched, not identity-certain, occurrence) correctly + // declines to carry across. + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base + 5_000)) + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base + 1_000)) + expect(merged?.lastNotifyStatus).toBe('blocked') + } finally { + store.close() + } + }) + + it('carries a dismissed duplicate\'s ack forward when ITS OWN footer is the one the merge keeps as canonical\'s representative (#1717 cold-review round 29)', async () => { + // The canonical row has no footer of its own; the only blocker in + // the whole duplicate group comes from a dismissed duplicate, which + // becomes the winning representative. The transfer loop's own key + // equals the winning key in exactly this case (the winner IS the + // key's source) — skipping the transfer there specifically skipped + // it exactly when it mattered most: nothing else carries the ack + // forward once the merge deletes the duplicate's row, so the + // already-dismissed blocker would reappear live on canonical. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-ack-carries', { codexSessionId: 'codex-thread-ack-carries', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-ack-carries', { codexSessionId: 'codex-thread-ack-carries', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footerText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs creds' }) + + // Canonical: padding only, no signal of its own. + for (let i = 0; i < 6; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `ack-carries-pad-${i}`, base) + } + + // Duplicate: the only footer in the group, already dismissed. + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'ack-carries-footer', base + 1_000) + const { notifyBlockerKey: notifyBlockerKeyFn } = await import('@hapi/protocol') + store.sessions.setSessionBlockedAck(duplicate.id, { + at: base + 1_000, + reason: 'already handled', + keys: [notifyBlockerKeyFn(base + 1_000)] + }, 'default') + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-ack-carries'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + // The dismissal must have carried forward onto canonical's own + // key for the signal it just inherited. + expect(merged?.blockedAckKeys ?? []).toContain(notifyBlockerKeyFn(base + 1_000)) + } finally { + store.close() + } + }) + + it('does not transfer a dismissal of an OLD blocker onto a distinct, still-open one with the same status and note (#1717)', async () => { + // A source session can hold two DISTINCT real episodes that happen + // to repeat the same status+note (e.g. "needs creds" recurring) — + // the operator dismissed the earlier one, and a later, genuinely + // unanswered occurrence is the session's own CURRENT signal. + // Matching a dismissal by "any occurrence anywhere in this + // session's history with matching content" instead of "the one + // occurrence this session's own timeline currently considers + // live" transferred the OLD dismissal onto the NEW occurrence and + // hid a real blocker that was never dismissed. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-recurring', { codexSessionId: 'codex-thread-recurring', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-recurring', { codexSessionId: 'codex-thread-recurring', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footerText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs creds' }) + + // Canonical: padding only, no signal of its own — the winning + // representative must come from the duplicate. + for (let i = 0; i < 6; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `recurring-pad-${i}`, base) + } + + // Duplicate: the SAME status+note blocked TWICE, at different + // turns — the first one dismissed, the second one not. + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'recurring-old-footer', base + 1_000) + const { notifyBlockerKey: notifyBlockerKeyFn } = await import('@hapi/protocol') + store.sessions.setSessionBlockedAck(duplicate.id, { + at: base + 1_000, + reason: 'handled the first time', + keys: [notifyBlockerKeyFn(base + 1_000)] + }, 'default') + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'recurring-new-footer', base + 9_000) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-recurring'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + // The winning representative is the NEW (undismissed) + // occurrence — nothing dismisses it. + expect(merged?.lastNotifyAt).toBe(base + 9_000) + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKeyFn(base + 9_000)) + } finally { + store.close() + } + }) + + it('does not let a session\'s own earlier, already-replied-to footer resolve its own later, genuinely unanswered occurrence with identical text (#1717)', async () => { + // Originally fixed by excluding the candidate's own session from a + // cross-session "is this content already answered elsewhere" scan + // (round 29) — that scan no longer exists at all (round 31: no + // cross-session content match of ANY kind is sound without a + // stable cross-copy identity, which #1717/hapi#2577 found doesn't + // exist). This test still holds trivially: a session's own + // single-session derivation already excludes a superseded episode + // by message IDENTITY when picking its current signal, and that + // derivation is untouched by round 31 — there is no longer a + // SEPARATE cross-session check left to re-litigate it by content. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-self-answered', { codexSessionId: 'codex-thread-self-answered', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-self-answered', { codexSessionId: 'codex-thread-self-answered', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footerText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs creds' }) + + // Canonical: padding only, no signal or reply of its own — the + // winning representative must come from the duplicate. + for (let i = 0; i < 6; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `self-answered-pad-${i}`, base) + } + + // Duplicate: the SAME status+note blocked, replied to, then blocked + // again with IDENTICAL text — nothing ever answers the second one. + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'self-answered-old-footer', base + 1_000) + store.messages.addImportedMessage(duplicate.id, { + role: 'user', content: { type: 'text', text: 'try the staging key' }, meta: { sentFrom: 'webapp' } + }, 'self-answered-reply', base + 2_000) + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'self-answered-new-footer', base + 9_000) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-self-answered'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + // The second, genuinely unanswered occurrence must still be the + // representative signal — not cleared by its own answered twin. + expect(merged?.lastNotifyStatus).toBe('blocked') + expect(merged?.lastNotifyAt).toBe(base + 9_000) + } finally { + store.close() + } + }) + + it('does not let a SIBLING duplicate\'s own already-replied-to footer resolve a candidate\'s distinct, unanswered occurrence of the same text (#1717 cold-review round 31)', async () => { + // The self-exclusion fix (round 29) stopped a session's own + // history from resolving itself. It did nothing for the SAME + // conflation happening ACROSS two duplicate sessions instead of + // within one — a sibling's own reply answering ITS copy of a + // footer said nothing about whether a candidate's distinct, later + // occurrence of the identical text was ever answered, but content + // equality alone could not tell them apart. Fixed by declining + // cross-session content matching entirely (round 31): a + // candidate's own self-consistent derivation is now trusted + // as-is, regardless of what any sibling's transcript shows. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-sibling-answered', { codexSessionId: 'codex-thread-sibling-answered', path: '/tmp', host: 'h' }, {}, 'default' + ) + const siblingA = store.sessions.getOrCreateSession( + 'sibling-a-answered', { codexSessionId: 'codex-thread-sibling-answered', path: '/tmp', host: 'h' }, {}, 'default' + ) + const siblingB = store.sessions.getOrCreateSession( + 'sibling-b-unanswered', { codexSessionId: 'codex-thread-sibling-answered', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footerText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs creds' }) + + // Canonical: padding only, no signal or reply of its own — most + // messages, wins canonical selection regardless of notify state. + for (let i = 0; i < 10; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `sibling-answered-pad-${i}`, base) + } + + // Sibling A: its OWN copy of the footer, genuinely answered within + // ITS OWN transcript. + store.messages.addImportedMessage(siblingA.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'sibling-answered-a-footer', base + 1_000) + store.messages.addImportedMessage(siblingA.id, { + role: 'user', content: { type: 'text', text: 'try the staging key' }, meta: { sentFrom: 'webapp' } + }, 'sibling-answered-a-reply', base + 2_000) + + // Sibling B: a DISTINCT, later occurrence of the IDENTICAL text — + // nothing in B's own transcript answers it, and A's reply cannot + // be proven to either. + store.messages.addImportedMessage(siblingB.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'sibling-unanswered-b-footer', base + 9_000) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-sibling-answered'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + // Sibling B's occurrence must still surface as the group's + // blocker — not silently cleared by sibling A's unrelated, + // self-answered copy of the same text. + expect(merged?.lastNotifyStatus).toBe('blocked') + } finally { + store.close() + } + }) + + it('keeps a GENUINELY LATER blocker from a shorter duplicate over an older one from a longer sibling (#1717 cold-review round 32)', async () => { + // The representative used to be `survivors[0]` in the merge's own + // canonical-selection order (most messages, newest updatedAt) — a + // heuristic for "which session's OTHER metadata to keep," not + // "which blocker is most current." A duplicate with fewer messages + // can still be reporting the genuinely LATER real episode; picking + // the first survivor in merge order silently preferred an older + // blocker from a longer sibling over a newer one from a shorter + // sibling. The representative is now whichever survivor's own + // signal is newest by author time. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-latest-wins', { codexSessionId: 'codex-thread-latest-wins', path: '/tmp', host: 'h' }, {}, 'default' + ) + const longerDup = store.sessions.getOrCreateSession( + 'dup-latest-wins-longer', { codexSessionId: 'codex-thread-latest-wins', path: '/tmp', host: 'h' }, {}, 'default' + ) + const shorterDup = store.sessions.getOrCreateSession( + 'dup-latest-wins-shorter', { codexSessionId: 'codex-thread-latest-wins', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + // canonical: most messages of all, no signal of its own. + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `latest-wins-canon-pad-${i}`, base) + } + + // longerDup: more messages than shorterDup, carries an OLDER, still + // genuinely unanswered blocker (nothing in ITS OWN history answers it). + const olderFooterText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs an OLDER key' }) + for (let i = 0; i < 5; i++) { + store.messages.addImportedMessage(longerDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `longer-pad ${i}` }] } } } + }, `latest-wins-longer-pad-${i}`, base + 5_000) + } + store.messages.addImportedMessage(longerDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: olderFooterText }] } } } + }, 'latest-wins-older-footer', base + 10_000) + + // shorterDup: a single message, a GENUINELY LATER, distinct + // unresolved blocker. + const laterFooterText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a LATER, different key' }) + store.messages.addImportedMessage(shorterDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: laterFooterText }] } } } + }, 'latest-wins-later-footer', base + 50_000) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-latest-wins'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + // The LATER footer, not the older one from the longer sibling. + expect(merged?.lastNotifyAt).toBe(base + 50_000) + } finally { + store.close() + } + }) + + it('does not let a stale import\'s done report outrank a live session\'s blocker just because its synthetic createdAt is later (#1717 cold-review round 33)', async () => { + // Author-time-when-content-differs (round 32, above) is only safe + // between two signals of the SAME polarity. A non-blocking report + // from a Codex Desktop import carries no real per-row timestamp — + // its last row is stamped with the IMPORT's own wall-clock moment, + // which can land numerically AFTER a live session's genuinely + // earlier blocked report while describing an OLDER real episode. + // Picking by raw author time across that polarity boundary + // resolved a blocker nothing in the live transcript ever answered. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-stale-import-done', { codexSessionId: 'codex-thread-stale-import-done', path: '/tmp', host: 'h' }, {}, 'default' + ) + const liveDup = store.sessions.getOrCreateSession( + 'dup-live-blocked', { codexSessionId: 'codex-thread-stale-import-done', path: '/tmp', host: 'h' }, {}, 'default' + ) + const staleImportDup = store.sessions.getOrCreateSession( + 'dup-stale-import-done', { codexSessionId: 'codex-thread-stale-import-done', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `stale-import-done-canon-pad-${i}`, base) + } + + // The LIVE session: genuine, recent blocked footer. + const blockedFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addMessage(liveDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: blockedFooter }] } } } + }, undefined, null, base + 5_000, base + 5_000) + + // The STALE IMPORT duplicate: its last row has no real per-row + // timestamp, so the import path stamps it with the import's own + // moment — later in raw numeric terms than the live blocked + // report, even though the episode it describes is actually older. + const doneFooter = 'Done.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'done', summary: 'all set' }) + store.messages.addImportedMessage(staleImportDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: doneFooter }] } } } + }, 'stale-import-done-footer', base + 100_000) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-stale-import-done'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + } finally { + store.close() + } + }) + + it('does not let a stale import\'s done report outrank a live session reporting a non-literal blocking status (#1717 cold-review round 34)', async () => { + // Round 33 only excluded non-blocking reports from the pool when the + // literal string was "blocked". The list treats several OTHER + // statuses (stalled, needs_decision, ...) as blockers too via + // `isBlockedNotifyStatus` — a live session reporting one of those + // lost to a stale import's `done` for the exact same reason round 33 + // fixed for the literal status. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-stalled-vs-done', { codexSessionId: 'codex-thread-stalled-vs-done', path: '/tmp', host: 'h' }, {}, 'default' + ) + const liveDup = store.sessions.getOrCreateSession( + 'dup-live-stalled', { codexSessionId: 'codex-thread-stalled-vs-done', path: '/tmp', host: 'h' }, {}, 'default' + ) + const staleImportDup = store.sessions.getOrCreateSession( + 'dup-stale-done', { codexSessionId: 'codex-thread-stalled-vs-done', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `stalled-vs-done-canon-pad-${i}`, base) + } + + const stalledFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'stalled', summary: 'needs a key' }) + store.messages.addMessage(liveDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: stalledFooter }] } } } + }, undefined, null, base + 5_000, base + 5_000) + + const doneFooter = 'Done.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'done', summary: 'all set' }) + store.messages.addImportedMessage(staleImportDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: doneFooter }] } } } + }, 'stalled-vs-done-footer', base + 100_000) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-stalled-vs-done'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('stalled') + } finally { + store.close() + } + }) + + it('does not let a newer, already-dismissed blocked report outrank an older, distinct unresolved blocker (#1717 cold-review round 34)', async () => { + // A survivor's own dismissal state matters too, not just its + // status: a session whose operator already acknowledged its + // blocker is not an unresolved candidate anymore, even though its + // signal is still literally "blocked" and numerically newer than a + // sibling's genuinely unresolved, distinct blocker. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-dismissed-vs-unresolved', { codexSessionId: 'codex-thread-dismissed-vs-unresolved', path: '/tmp', host: 'h' }, {}, 'default' + ) + const dismissedDup = store.sessions.getOrCreateSession( + 'dup-dismissed', { codexSessionId: 'codex-thread-dismissed-vs-unresolved', path: '/tmp', host: 'h' }, {}, 'default' + ) + const unresolvedDup = store.sessions.getOrCreateSession( + 'dup-unresolved', { codexSessionId: 'codex-thread-dismissed-vs-unresolved', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `dismissed-vs-unresolved-canon-pad-${i}`, base) + } + + // Newer blocked footer, but already dismissed by the operator. + const dismissedFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'already handled' }) + store.messages.addImportedMessage(dismissedDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: dismissedFooter }] } } } + }, 'dismissed-footer', base + 50_000) + store.sessions.setSessionBlockedAck(dismissedDup.id, { + at: base + 60_000, reason: 'handled', keys: [notifyBlockerKey(base + 50_000)] + }, 'default') + + // Older blocked footer, genuinely unresolved, distinct content. + const unresolvedFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'still needs a key' }) + store.messages.addImportedMessage(unresolvedDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: unresolvedFooter }] } } } + }, 'unresolved-footer', base + 10_000) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-dismissed-vs-unresolved'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + expect(merged?.lastNotifyAt).toBe(base + 10_000) + } finally { + store.close() + } + }) + + it('strips a stale canonical ack key that would coincidentally collide with a distinct merged footer at the same timestamp (#1717 cold-review round 36)', async () => { + // notifyBlockerKey(at) is a pure function of the timestamp alone, with + // no status/note component. If canonical dismissed its OWN (different) + // footer at time T, and the merge later picks a DIFFERENT, genuinely + // unresolved footer from a duplicate that also happens to land at time + // T, canonical's stale key coincidentally matches the winner's key and + // silently suppresses it — isAcknowledgedBlocker only ever sees keys, + // never content. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-coincidence', { codexSessionId: 'codex-thread-coincidence', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-coincidence', { codexSessionId: 'codex-thread-coincidence', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `coincidence-canon-pad-${i}`, base - 10_000) + } + + // Canonical's own, already-dismissed footer — lands at `base`. + const dismissedFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'old issue, already handled' }) + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: dismissedFooter }] } } } + }, 'coincidence-canon-footer', base) + store.sessions.setSessionBlockedAck(canonical.id, { + at: base + 1_000, reason: 'handled', keys: [notifyBlockerKey(base)] + }, 'default') + + // Duplicate's distinct, genuinely unresolved footer — same timestamp. + const distinctFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'completely different problem' }) + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: distinctFooter }] } } } + }, 'coincidence-dup-footer', base) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-coincidence'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base)) + // The stripped key was canonical's ONLY key. An empty key set + // serialises identically to "never dismissed," but a surviving + // `blockedAckAt` would still re-cover this same winner through + // isAcknowledgedBlocker's own watermark fallback (#1717 + // cold-review round 36) — so the ack must be gone entirely, + // not just emptied of keys. + expect(merged?.blockedAckAt).toBeNull() + } finally { + store.close() + } + }) + + it('keeps a surviving, non-colliding ack key and timestamp when canonical has more than one dismissal (#1717 cold-review round 36)', async () => { + // Positive control for the previous test: stripping the ONE stale + // key that collides must not clear an ack that still has other, + // genuinely unrelated live keys. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-multi-key', { codexSessionId: 'codex-thread-multi-key', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-multi-key', { codexSessionId: 'codex-thread-multi-key', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const earlierAt = base - 100_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `multi-key-canon-pad-${i}`, earlierAt - 10_000) + } + + // An EARLIER, unrelated dismissal that must survive untouched. + const earlierFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'unrelated, already handled' }) + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: earlierFooter }] } } } + }, 'multi-key-canon-earlier-footer', earlierAt) + + // Canonical's own, already-dismissed footer at `base` — this key + // collides with the duplicate's distinct footer below. + const dismissedFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'old issue, already handled' }) + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: dismissedFooter }] } } } + }, 'multi-key-canon-footer', base) + store.sessions.setSessionBlockedAck(canonical.id, { + at: base + 1_000, + reason: 'handled', + keys: [notifyBlockerKey(earlierAt), notifyBlockerKey(base)] + }, 'default') + + // Duplicate's distinct, genuinely unresolved footer — same timestamp as `base`. + const distinctFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'completely different problem' }) + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: distinctFooter }] } } } + }, 'multi-key-dup-footer', base) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-multi-key'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base)) + expect(merged?.blockedAckKeys ?? []).toContain(notifyBlockerKey(earlierAt)) + expect(merged?.blockedAckAt).toBe(base + 1_000) + } finally { + store.close() + } + }) + + it('strips a colliding canonical dismissal even when canonical has since been answered and derives no current signal (#1717 cold-review round 36)', async () => { + // The first pass at the round-36 fix only stripped a colliding key + // when canonical's CURRENT signal had different content from the + // winner's — using that comparison to prove the key was for a + // DIFFERENT footer. But a reply answering canonical's own footer + // after the dismissal leaves canonical's derived signal null, + // with nothing to compare against — so the stale key survived + // unexamined and still hid the duplicate's distinct, genuinely + // unresolved footer at the same coincidental timestamp. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-answered-collision', { codexSessionId: 'codex-thread-answered-collision', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-answered-collision', { codexSessionId: 'codex-thread-answered-collision', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `answered-collision-canon-pad-${i}`, base - 10_000) + } + + // Canonical's own footer, dismissed... + const dismissedFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'old issue, already handled' }) + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: dismissedFooter }] } } } + }, 'answered-collision-canon-footer', base) + store.sessions.setSessionBlockedAck(canonical.id, { + at: base + 1_000, reason: 'handled', keys: [notifyBlockerKey(base)] + }, 'default') + // ...and THEN also genuinely answered, so canonical's own derived + // signal is null by the time the merge runs. + store.messages.addImportedMessage(canonical.id, { + role: 'user', content: { type: 'text', text: 'here is the answer' }, meta: { sentFrom: 'webapp' } + }, 'answered-collision-reply', base + 2_000) + store.messages.markMessagesInvoked(canonical.id, ['answered-collision-reply'], base + 2_000) + + // Duplicate's distinct, genuinely unresolved footer — same timestamp as `base`. + const distinctFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'completely different problem' }) + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: distinctFooter }] } } } + }, 'answered-collision-dup-footer', base) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-answered-collision'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base)) + } finally { + store.close() + } + }) + + it('strips a canonical dismissal even when its content exactly matches the winner, when their native message ids differ (#1717 cold-review round 36)', async () => { + // The second pass at this fix compared CONTENT (status, note, at) + // to prove a colliding key belonged to a different footer — but + // content equality is not identity. Two imported rows can carry + // the exact same displayed status/note/timestamp while being + // genuinely distinct occurrences, each with its own native + // message id. Canonical dismissed its OWN still-current footer; + // the duplicate's distinct occurrence (different id, identical + // content) is the one that wins the unresolved pool, since + // canonical's own ack already resolves it from canonical's own + // perspective. The stale key must still be stripped even though + // every displayed field matches. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-identical-content', { codexSessionId: 'codex-thread-identical-content', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-identical-content', { codexSessionId: 'codex-thread-identical-content', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `identical-content-canon-pad-${i}`, base - 10_000) + } + + // Canonical's own footer, still its current signal, dismissed by + // canonical's own ack. + const sharedFooterText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'shared wording' }) + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: sharedFooterText }] } } } + }, 'identical-content-canon-footer', base) + store.sessions.setSessionBlockedAck(canonical.id, { + at: base + 1_000, reason: 'handled', keys: [notifyBlockerKey(base)] + }, 'default') + + // Duplicate's DISTINCT occurrence: identical status, note, and + // timestamp, but a different native message id — the one thing + // that actually tells the two apart. + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: sharedFooterText }] } } } + }, 'identical-content-dup-footer', base) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-identical-content'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base)) + } finally { + store.close() + } + }) + + it('preserves the winning dismissal when canonical answered its own footer at the same coincidental timestamp (#1717 cold-review round 36)', async () => { + // Canonical answered its OWN dismissed footer (its derived signal + // is now null), making the collision check strip its stale key. + // The winner — a distinct footer from the duplicate, ALSO + // dismissed by the duplicate's own ack, sharing the same + // coincidental timestamp key — transfers that SAME key onto + // canonical. Applying the strip (computed against canonical's + // PRE-transfer keys) after the transfer had already written the + // winner's key would wipe out a dismissal the operator actually + // made. The merged session must keep the winning key, not lose + // it to a strip meant for a stale, unrelated one. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-winning-dismissal', { codexSessionId: 'codex-thread-winning-dismissal', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-winning-dismissal', { codexSessionId: 'codex-thread-winning-dismissal', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `winning-dismissal-canon-pad-${i}`, base - 10_000) + } + + // Canonical's own footer, dismissed, then ALSO genuinely answered — + // its derived signal is null by the time the merge runs. + const canonFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'old issue, already handled' }) + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: canonFooter }] } } } + }, 'winning-dismissal-canon-footer', base) + store.sessions.setSessionBlockedAck(canonical.id, { + at: base + 1_000, reason: 'handled', keys: [notifyBlockerKey(base)] + }, 'default') + store.messages.addImportedMessage(canonical.id, { + role: 'user', content: { type: 'text', text: 'here is the answer' }, meta: { sentFrom: 'webapp' } + }, 'winning-dismissal-reply', base + 2_000) + store.messages.markMessagesInvoked(canonical.id, ['winning-dismissal-reply'], base + 2_000) + + // Duplicate's distinct footer, at the SAME timestamp, dismissed + // by the DUPLICATE's own ack — this is the key that must survive. + const dupFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'completely different problem' }) + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: dupFooter }] } } } + }, 'winning-dismissal-dup-footer', base) + store.sessions.setSessionBlockedAck(duplicate.id, { + at: base + 500, reason: 'handled elsewhere', keys: [notifyBlockerKey(base)] + }, 'default') + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-winning-dismissal'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.blockedAckKeys ?? []).toContain(notifyBlockerKey(base)) + } finally { + store.close() + } + }) + + it('does not strip a colliding canonical dismissal when the merge itself is refused (#1717 cold-review round 36)', async () => { + // The strip computed above used to write immediately, before the + // merge loop even reaches source deletion. If deletion is then + // refused — an unconfirmed Codex resume, here — the request + // fails, but the write had already committed: canonical's own + // footer could reappear on a cache refresh with no replacement + // ever actually applied, since the merge that was supposed to + // bring the replacement in never completed. The strip must only + // commit once the merge actually succeeds. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-refused-merge', { codexSessionId: 'codex-thread-refused-merge', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-refused-merge', + { + codexSessionId: 'codex-thread-refused-merge', path: '/tmp', host: 'h', + // Makes `engine.deleteSession` refuse this session once the + // merge loop reaches it, mirroring the finding's own + // trigger ("an inactive Codex resume is still unconfirmed"). + codexResumePending: { machineId: 'm', nativeSessionId: 'n' } + }, + {}, + 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `refused-merge-canon-pad-${i}`, base - 10_000) + } + + const sharedFooterText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'shared wording' }) + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: sharedFooterText }] } } } + }, 'refused-merge-canon-footer', base) + store.sessions.setSessionBlockedAck(canonical.id, { + at: base + 1_000, reason: 'handled', keys: [notifyBlockerKey(base)] + }, 'default') + + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: sharedFooterText }] } } } + }, 'refused-merge-dup-footer', base) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-refused-merge'] }) + }) + const body = await response.json() as { success: boolean } + expect(body.success).toBe(false) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.blockedAckKeys ?? []).toContain(notifyBlockerKey(base)) + } finally { + store.close() + } + }) + + it('does not transfer the winner\'s own ack onto canonical when the merge itself is refused (#1717 cold-review round 36)', async () => { + // The transfer is also snapshotted (read before a source winner + // could be deleted) but committed only in applyReconciledNotifyState, + // same as the strip. If source deletion is refused, that commit + // point is never reached at all — the winner's dismissal must + // stay exactly where it was, not partially or fully applied to + // canonical. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-refused-transfer', { codexSessionId: 'codex-thread-refused-transfer', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-refused-transfer', + { + codexSessionId: 'codex-thread-refused-transfer', path: '/tmp', host: 'h', + codexResumePending: { machineId: 'm', nativeSessionId: 'n' } + }, + {}, + 'default' + ) + const base = Date.now() - 600_000 + + for (let i = 0; i < 20; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } } + }, `refused-transfer-canon-pad-${i}`, base - 10_000) + } + + // Canonical has no footer of its own — the duplicate's footer is + // the only candidate, so it wins and its own ack is a transfer + // candidate. + const footer = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } } + }, 'refused-transfer-dup-footer', base) + store.sessions.setSessionBlockedAck(duplicate.id, { + at: base + 500, reason: 'handled', keys: [notifyBlockerKey(base)] + }, 'default') + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-refused-transfer'] }) + }) + const body = await response.json() as { success: boolean } + expect(body.success).toBe(false) + + const mergedCanonical = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(mergedCanonical?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base)) + const stillSeparateDuplicate = store.sessions.getSessionByNamespace(duplicate.id, 'default') + expect(stillSeparateDuplicate?.blockedAckKeys ?? []).toContain(notifyBlockerKey(base)) + } finally { + store.close() + } + }) + + it('does not let an untimestamped import\'s own initiating prompt resolve its own still-open footer through a merge\'s cross-session override check (#1717)', async () => { + // Within ONE session, the untimestamped-import tiebreak (seq) is + // already proven correct (#1717 round 27). But the cross-session + // "is this content already answered elsewhere" override check + // compared a candidate message's bare `receivedAt` against the + // OTHER session's `boundaryAt` NUMBER, dropping that same seq + // tiebreak — so when a duplicate's own initiating prompt and its + // own still-open footer share the SAME untimestamped-batch stamp, + // the override read the footer as "at or before" the prompt that + // merely preceded it, and cleared a blocker nothing ever answered. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-tiebreak', { codexSessionId: 'codex-thread-tiebreak', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-tiebreak', { codexSessionId: 'codex-thread-tiebreak', path: '/tmp', host: 'h' }, {}, 'default' + ) + const importedAt = Date.now() - 600_000 + const footerText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs creds' }) + + // Canonical: padding only, no signal of its own. + for (let i = 0; i < 6; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `tiebreak-pad-${i}`, importedAt) + } + + // Duplicate: a genuinely untimestamped import batch — the + // initiating prompt and the footer it caused share the EXACT same + // stamp, with only transcript order (seq) telling them apart. + store.messages.addImportedMessage(duplicate.id, { + role: 'user', content: { type: 'text', text: 'Continue' }, meta: { sentFrom: 'webapp' } + }, 'tiebreak-prompt', importedAt) + store.messages.addImportedMessage(duplicate.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'tiebreak-footer', importedAt) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-tiebreak'] }) + }) + expect(response.status).toBe(200) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + } finally { + store.close() + } + }) + + it('does not let a copied distractor row\'s live-ingestion replay overwrite the precomputed blocker (#1717)', async () => { + // The merge copies new rows into canonical, then replays each + // through live ingestion — which unconditionally re-derives the + // notify signal from whatever ONE row it is looking at, with no + // knowledge of the correct, already-computed reconciliation. An + // UNRELATED footer, already answered within its OWN source + // session and therefore irrelevant to the merge's real blocker, + // still gets copied in (distinct content from anything canonical + // already has) and still carries a genuine AGENT_NOTIFY_SUMMARY — + // replaying it overwrote the correct blocker's own status/note + // with this unrelated, already-resolved one's. Applying the + // precomputed projection BEFORE that replay let the replay's + // one-sided side effect (a footer replay sets the signal; a reply + // replay never clears it, since an imported row never goes + // through the delivery-confirmation callback a real one does) win + // last. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-clobber', { codexSessionId: 'codex-thread-clobber', path: '/tmp', host: 'h' }, {}, 'default' + ) + const realBlocker = store.sessions.getOrCreateSession( + 'dup-real-blocker', { codexSessionId: 'codex-thread-clobber', path: '/tmp', host: 'h' }, {}, 'default' + ) + const distractor = store.sessions.getOrCreateSession( + 'dup-distractor', { codexSessionId: 'codex-thread-clobber', path: '/tmp', host: 'h' }, {}, 'default' + ) + // Both duplicates have an equal message count, so the merge's own + // deterministic order (used for its row-copy loop, and which this + // test's bug hinges on) ties on message count and falls back to + // `updatedAt` descending. Pinned explicitly so the distractor's + // footer is the LAST thing replayed — ahead of real `Date.now()` + // since `touchSessionUpdatedAt` is monotonic and both sessions' + // creation-time `updatedAt` already sit at real "now". + store.sessions.touchSessionUpdatedAt(realBlocker.id, Date.now() + 10_000, 'default') + store.sessions.touchSessionUpdatedAt(distractor.id, Date.now() + 5_000, 'default') + const base = Date.now() - 600_000 + const realFooter = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs X' }) + const distractorFooter = 'Stuck too.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs Y' }) + + // Canonical: padding only, to win canonical selection. + for (let i = 0; i < 8; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `clobber-pad-${i}`, base) + } + + // The REAL blocker: a reply that precedes the footer (so it does + // NOT answer it) gives this session a real, non-null boundary — + // without one, the precomputed projection's own `boundaryAt` falls + // back to "now", which would coincidentally protect this test for + // the wrong reason. + store.messages.addMessage(realBlocker.id, { + role: 'user', content: { type: 'text', text: 'starting' }, meta: { sentFrom: 'webapp' } + }, 'clobber-early-reply', null, base + 500, base + 500) + store.messages.markMessagesInvoked(realBlocker.id, ['clobber-early-reply'], base + 500) + store.messages.addMessage(realBlocker.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: realFooter }] } } } + }, undefined, null, base + 1_000, base + 1_000) + + // The distractor: a DIFFERENT, already-answered footer — distinct + // content, so it is copied into canonical rather than + // deduplicated, and its own `createdAt` lands AFTER the real + // blocker's boundary, so the store's monotonic guard does not + // reject the replay. + store.messages.addMessage(distractor.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: distractorFooter }] } } } + }, undefined, null, base + 2_000, base + 2_000) + store.messages.addMessage(distractor.id, { + role: 'user', content: { type: 'text', text: 'Fixed Y' }, meta: { sentFrom: 'webapp' } + }, 'clobber-distractor-reply', null, base + 3_000, base + 3_000) + store.messages.markMessagesInvoked(distractor.id, ['clobber-distractor-reply'], base + 3_000) + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-clobber'] }) + }) + expect(response.status).toBe(200) + + const rows = store.messages.getAllMessages(canonical.id) + expect(rows.some((row) => JSON.stringify(row.content).includes('needs Y'))).toBe(true) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + expect(merged?.lastNotifyStatus).toBe('blocked') + expect(merged?.lastNotifyNote).toBe('needs X') + } finally { + store.close() + } + }) + + it('does not let a live session\'s own resolution silently suppress a sibling\'s independently unresolved occurrence (#1717 cold-review round 31)', async () => { + // Was "does not let an untimestamped Desktop import outrank a live + // session that already answered the exact same footer" — asserting + // the OPPOSITE of what it now should. That test's premise (the live + // session's reply answers the import's footer because the text + // matches) is the cross-session content-match round 31 retired: + // two sessions' copies of "the same" footer are not provably the + // same real occurrence without a stable cross-copy identity, which + // #1717 (hapi#2577) found does not exist for a live-vs-imported + // pairing specifically. The live session's own transcript genuinely + // answers ITS OWN footer — that derivation is untouched, still + // correct, and still produces no signal from the live session's + // side. But the import's footer is unanswered within ITS OWN + // transcript, and nothing can safely prove the live reply covers + // it too — so it now correctly surfaces as the group's + // representative instead of being silently suppressed. + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const live = store.sessions.getOrCreateSession( + 'live-answered', { codexSessionId: 'codex-thread-untimestamped', path: '/tmp', host: 'h' }, {}, 'default' + ) + const stale = store.sessions.getOrCreateSession( + 'stale-import', { codexSessionId: 'codex-thread-untimestamped', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footerText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs creds' }) + + // Live session: padding (wins canonical selection), the footer, then + // a REAL reply that answers it — all genuinely timestamped, in the + // past. + for (let i = 0; i < 6; i++) { + store.messages.addImportedMessage(live.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `untimestamped-pad-${i}`, base) + } + store.messages.addMessage(live.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, undefined, null, base + 1_000, base + 1_000) + store.messages.addMessage(live.id, { + role: 'user', content: { type: 'text', text: 'Continue' }, meta: { sentFrom: 'webapp' } + }, 'untimestamped-live-reply', null, base + 1_500, base + 1_500) + store.messages.markMessagesInvoked(live.id, ['untimestamped-live-reply'], base + 2_000) + + // Stale import: its OWN projection of the SAME footer, with no + // explicit timestamp of its own — exactly like a real Codex + // transcript, which carries none — so it is stamped with the + // import's own `Date.now()`, necessarily after `base`. + store.messages.addImportedMessage(stale.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'untimestamped-import-footer', Date.now()) + + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-untimestamped'] }) + }) + expect(response.status).toBe(200) + const body = await response.json() as { merged: Array<{ canonicalSessionId?: string }> } + const survivorId = body.merged[0]?.canonicalSessionId + expect(survivorId).toBe(live.id) + + const merged = store.sessions.getSessionByNamespace(survivorId!, 'default') + // The live session's own transcript genuinely answers its own + // footer — canonical selection is unaffected and still picks + // the live session. But the stale import's footer is + // unanswered within ITS OWN transcript, and nothing safely + // proves the live reply covers it too, so the group's overall + // signal is now the import's, not silently cleared by a + // sibling's unrelated-by-proof resolution. + expect(merged?.lastNotifyStatus).toBe('blocked') + } finally { + store.close() + } + }) + + it('picks the representative by deterministic session order, but no longer remaps a dismissal from the OTHER duplicate onto it (#1717 cold-review round 31)', async () => { + // Was "remaps a LATER dismissal onto the representative..." — + // asserting a transfer round 31 retired. Neither duplicate's + // footer is answered anywhere, so the overall status is + // unambiguously blocked either way — what is still genuinely under + // test is WHICH occurrence becomes the representative. Picking + // "whichever footer's raw timestamp is latest" is unsound here: a + // Codex Desktop import carries no per-row timestamp at all, so + // `base + 1_000` and `base + 2_000` reflect nothing but each + // duplicate's own import batch stamp, not which one is + // conversationally more current. The representative is instead + // the first survivor in the SAME deterministic order the merge + // sorts sessions into for canonical selection — that part is + // unchanged and still correct. What changed: the second + // duplicate's dismissal no longer transfers onto the first + // duplicate's (winning) occurrence just because the footer text + // matches — that match is exactly the content-based cross-session + // assumption round 31 retired, so the representative now correctly + // stays undismissed. + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'tri-copy-canon', { codexSessionId: 'codex-thread-26b', path: '/tmp', host: 'h' }, {}, 'default' + ) + const firstDup = store.sessions.getOrCreateSession( + 'tri-copy-first', { codexSessionId: 'codex-thread-26b', path: '/tmp', host: 'h' }, {}, 'default' + ) + const secondDup = store.sessions.getOrCreateSession( + 'tri-copy-second', { codexSessionId: 'codex-thread-26b', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footerText = 'Stuck.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs creds' }) + + // Duplicates with an equal message count (one footer each) process + // in DESCENDING `updatedAt` order — pinned explicitly, to values + // AHEAD of real `Date.now()` since `touchSessionUpdatedAt` is + // monotonic and both sessions' creation-time `updatedAt` already sit + // at real "now". Pinning so which duplicate supplies the copy and + // which supplies the dismissal does not depend on wall-clock timing + // between the two `getOrCreateSession` calls above. + store.sessions.touchSessionUpdatedAt(firstDup.id, Date.now() + 10_000, 'default') + store.sessions.touchSessionUpdatedAt(secondDup.id, Date.now() + 5_000, 'default') + + // Survivor: padding only, no footer of its own — the footer must be + // COPIED from a duplicate, not matched against an existing row. + for (let i = 0; i < 6; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `tri-copy-pad-${i}`, base) + } + + // First duplicate: processed first (newer `updatedAt`), supplies the + // footer genuinely new to canonical — goes through the COPY path. + store.messages.addImportedMessage(firstDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'tri-copy-first-footer', base + 1_000) + + // Second duplicate: its OWN projection of the SAME footer, a + // different `createdAt` — and the operator already dismissed THIS + // occurrence. Processed after the first, so it lands in the + // deduplicate branch once the copy above makes room for it. + store.messages.addImportedMessage(secondDup.id, { + role: 'agent', + content: { type: 'output', data: { type: 'assistant', message: { content: [{ type: 'text', text: footerText }] } } } + }, 'tri-copy-second-footer', base + 2_000) + const { notifyBlockerKey } = await import('@hapi/protocol') + store.sessions.setSessionBlockedAck(secondDup.id, { + at: base + 2_000, + reason: 'handled', + keys: [notifyBlockerKey(base + 2_000)] + }, 'default') + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-26b'] }) + }) + expect(response.status).toBe(200) + + const footers = store.messages.getAllMessages(canonical.id) + .filter((row) => JSON.stringify(row.content).includes('AGENT_NOTIFY_SUMMARY')) + // One footer in the merged TRANSCRIPT — the second duplicate's + // copy deduplicated against the first duplicate's COPIED row, + // not appended again. This is still the unchanged base merge + // rule: whichever content occurrence is seen first wins. + expect(footers).toHaveLength(1) + expect(footers[0]!.createdAt).toBe(base + 1_000) + + const merged = store.sessions.getSessionByNamespace(canonical.id, 'default') + // The representative is still the FIRST duplicate's occurrence + // — same deterministic order the merge itself used to decide + // which row the content-dedup keeps, unaffected by round 31. + // But the second duplicate's dismissal, for a content-matched + // (not identity-certain) occurrence, no longer transfers onto + // it — the representative correctly stays undismissed. + expect(merged?.lastNotifyAt).toBe(base + 1_000) + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base + 1_000)) + expect(merged?.blockedAckKeys ?? []).not.toContain(notifyBlockerKey(base + 2_000)) + expect(merged?.lastNotifyStatus).toBe('blocked') + } finally { + store.close() + } + }) + + it('does not duplicate an initiating prompt across a THREE-session merge', async () => { + // Survivor holds a blocked footer. One duplicate supplies the live + // prompt that preceded it; another supplies the Desktop import of that + // SAME prompt. Bumping only the tally a row was measured against left + // the other stale, so the second duplicate saw a count that did not + // include the row just copied and appended the prompt again — with a + // synthetic stamp after the footer, which reconciliation then read as + // an answer and hid an unanswered blocker. + const { SyncEngine } = await import('../../sync/syncEngine') + const { RpcRegistry } = await import('../../socket/rpcRegistry') + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + // Created through the STORE, not the engine: `engine.getOrCreateSession` + // with a shared `codexSessionId` engages the engine's own duplicate + // handling, which raced the route-level merge under test and made this + // flaky (2 of 3 runs) before I caught it. + const canonical = store.sessions.getOrCreateSession( + 'tri-canon', { codexSessionId: 'codex-thread-14', path: '/tmp', host: 'h' }, {}, 'default' + ) + const liveDup = store.sessions.getOrCreateSession( + 'tri-live', { codexSessionId: 'codex-thread-14', path: '/tmp', host: 'h' }, {}, 'default' + ) + const importDup = store.sessions.getOrCreateSession( + 'tri-import', { codexSessionId: 'codex-thread-14', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + + // Survivor: padding so it wins canonical selection, then the footer. + for (let i = 0; i < 6; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `tri-pad-${i}`, base) + } + store.messages.addMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, base + 3_000, base + 3_000) + // The footer is set directly rather than derived first: deriving it + // pre-merge depended on engine cache priming and made this flaky. What + // is under test is whether the MERGE's reconciliation keeps it, so the + // starting state only has to be unambiguous. + engine.handleRealtimeEvent({ type: 'session-updated', sessionId: canonical.id }) + store.sessions.setSessionLastNotify( + canonical.id, + { status: 'blocked', at: base + 3_000, note: 'needs a key', receivedAt: base + 3_000 }, + 'default' + ) + const blockedStatus = () => store.sessions + .getSessionByNamespace(canonical.id, 'default')?.lastNotifyStatus + expect(blockedStatus()).toBe('blocked') + + // Duplicate A: the live prompt, real hub acknowledgement. + store.messages.addMessage(liveDup.id, { + role: 'user', content: { type: 'text', text: 'Continue' }, meta: { sentFrom: 'webapp' } + }, 'tri-live-id', null, base + 1_000, base + 1_000) + store.messages.markMessagesInvoked(liveDup.id, ['tri-live-id'], base + 2_000) + // Duplicate B: the Desktop import of the same prompt, synthetic stamp + // AFTER the footer. + store.messages.addImportedMessage(importDup.id, { + role: 'user', content: { type: 'text', text: 'Continue' }, meta: { sentFrom: 'webapp' } + }, 'tri-import-id', base + 9_000) + + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-14'] }) + }) + expect(response.status).toBe(200) + + const prompts = store.messages.getAllMessages(canonical.id) + .filter((row) => JSON.stringify(row.content).includes('Continue')) + expect(prompts).toHaveLength(1) + expect(blockedStatus()).toBe('blocked') + } finally { + store.close() + } + }) + + it('aligns a live prompt with its LATER Desktop import, under real reconciliation', async () => { + // My previous test gave both copies the same delivery timestamp and + // stubbed reconciliation, which is the easy version of this. In + // reality the live projection carries a real hub acknowledgement time + // while the untimestamped Desktop import synthesizes its own, so the + // two never matched: the prompt was appended again and its later + // timestamp let reconciliation read an initiating prompt as a reply + // and hide the blocker. Real engine, real reconciliation here. + const { SyncEngine } = await import('../../sync/syncEngine') + const { RpcRegistry } = await import('../../socket/rpcRegistry') + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + const store = new Store(':memory:') + const io = { of: () => ({ to: () => ({ emit() {} }) }) } + const engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const canonical = store.sessions.getOrCreateSession( + 'canon-real', { codexSessionId: 'codex-thread-13', path: '/tmp', host: 'h' }, {}, 'default' + ) + const duplicate = store.sessions.getOrCreateSession( + 'dup-real', { codexSessionId: 'codex-thread-13', path: '/tmp', host: 'h' }, {}, 'default' + ) + const base = Date.now() - 600_000 + const footer = 'Prose.\n\nAGENT_NOTIFY_SUMMARY ' + + JSON.stringify({ version: 1, status: 'blocked', summary: 'needs a key' }) + + // Survivor: the live projection's prompt (real hub ack time), then an + // unanswered blocked footer AFTER it. + for (let i = 0; i < 4; i++) { + store.messages.addImportedMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: `pad ${i}` }] } } + } + }, `pad-${i}`, base) + } + store.messages.addMessage(canonical.id, { + role: 'user', content: { type: 'text', text: 'Continue' }, meta: { sentFrom: 'webapp' } + }, 'live-id', null, base + 1_000, base + 1_000) + store.messages.markMessagesInvoked(canonical.id, ['live-id'], base + 2_000) + store.messages.addMessage(canonical.id, { + role: 'agent', + content: { + type: 'output', + data: { type: 'assistant', message: { content: [{ type: 'text', text: footer }] } } + } + }, undefined, null, base + 3_000, base + 3_000) + // The footer is set directly rather than derived first: deriving it + // pre-merge depended on engine cache priming and made this flaky. What + // is under test is whether the MERGE's reconciliation keeps it, so the + // starting state only has to be unambiguous. + engine.handleRealtimeEvent({ type: 'session-updated', sessionId: canonical.id }) + store.sessions.setSessionLastNotify( + canonical.id, + { status: 'blocked', at: base + 3_000, note: 'needs a key', receivedAt: base + 3_000 }, + 'default' + ) + const blockedStatus = () => store.sessions + .getSessionByNamespace(canonical.id, 'default')?.lastNotifyStatus + expect(blockedStatus()).toBe('blocked') + + // The duplicate holds the SAME prompt as an untimestamped import, so + // its delivery stamp is synthetic and LATER than the footer. + store.messages.addImportedMessage(duplicate.id, { + role: 'user', content: { type: 'text', text: 'Continue' }, meta: { sentFrom: 'webapp' } + }, 'import-id', base + 9_000) + + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + try { + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-13'] }) + }) + expect(response.status).toBe(200) + + const prompts = store.messages.getAllMessages(canonical.id) + .filter((row) => JSON.stringify(row.content).includes('Continue')) + expect(prompts).toHaveLength(1) + // And the blocker is still there, because nothing answered it. + expect(blockedStatus()).toBe('blocked') + } finally { + store.close() + } + }) + it('merges duplicate sessions discovered across SyncEngine cache and persistent store', async () => { const app = new Hono() app.use('*', async (c, next) => { @@ -1050,6 +2907,8 @@ describe('Codex Desktop import routes', () => { store.messages.addMessage(engineSession.id, { type: 'text', text: 'engine-only message' }, 'engine-1') const engine = { getSessionsByNamespace: () => [engineSession], + transferBlockedAck: () => {}, + assertSessionDeletable: () => {}, transferAttachedJobs: (fromSessionId: string, toSessionId: string) => { store.sessionJobs.transfer(fromSessionId, toSessionId) }, @@ -1057,6 +2916,9 @@ describe('Codex Desktop import routes', () => { store.sessions.deleteSession(sessionId, 'default') }, handleRealtimeEvent: () => {}, + reconcileNotifySignalAfterImport: () => {}, + computeNotifyStateAcrossDuplicateSessions: () => ({ signal: null, boundaryAt: null, authorCutoff: null }), + applyReconciledNotifyState: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') } @@ -1086,6 +2948,66 @@ describe('Codex Desktop import routes', () => { } }) + it('keeps completed sources merged and leaves a refused source untouched', async () => { + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + const store = new Store(':memory:') + const createDuplicate = (tag: string, texts: string[], metadata: Record = {}) => { + const session = store.sessions.getOrCreateSession( + tag, + { path: 'C:\\work\\project', host: 'test', codexSessionId: 'codex-thread-partial', ...metadata }, + {}, + 'default' + ) + texts.forEach((text, index) => { + store.messages.addMessage(session.id, codexUserMessage(text), `${tag}-${index}`) + }) + return session + } + // Merge order follows message count: canonical, then removable, then refused. + const canonical = createDuplicate('canonical', ['canonical 1', 'canonical 2', 'canonical 3']) + const removable = createDuplicate('removable', ['removable 1', 'removable 2']) + const refused = createDuplicate('refused', ['refused 1'], { + codexResumePending: { machineId: 'machine', nativeSessionId: 'native-refused' } + }) + store.sessionJobs.upsert(refused.id, 'import', { label: 'import', status: 'running', remaining: 5 }) + + const events: SyncEvent[] = [] + const engine = new SyncEngine(store, {} as never, new RpcRegistry(), { + broadcast: (event: SyncEvent) => events.push(event) + } as never) + app.route('/api', createCodexDesktopRoutes({ store, getSyncEngine: () => engine })) + + try { + events.length = 0 + const response = await app.request('/api/codex/merge-duplicate-sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionIds: ['codex-thread-partial'] }) + }) + + const body = await response.json() as { success: false; error: string } + expect(body.success).toBe(false) + expect(body.error).toMatch(/resume startup is unconfirmed/i) + expect(store.sessions.getSessionByNamespace(removable.id, 'default')).toBeNull() + expect(store.sessions.getSessionByNamespace(refused.id, 'default')).not.toBeNull() + // Nothing from the refused source moved into the canonical session. + expect(store.messages.getAllMessages(canonical.id)).toHaveLength(5) + expect(store.messages.getAllMessages(refused.id)).toHaveLength(1) + expect(store.sessionJobs.getPrimaryRunning(refused.id)?.key).toBe('import') + // The completed source is still announced to connected clients. + expect(events.filter((event) => ( + event.type === 'message-received' && event.sessionId === canonical.id + ))).toHaveLength(2) + } finally { + engine.stop() + store.close() + } + }) + it('defers no-engine merge when the source still has attached jobs', async () => { const app = new Hono() app.use('*', async (c, next) => { diff --git a/hub/src/web/routes/codexExtras.ts b/hub/src/web/routes/codexExtras.ts index 70540235e65..af6d0b85ff7 100644 --- a/hub/src/web/routes/codexExtras.ts +++ b/hub/src/web/routes/codexExtras.ts @@ -793,6 +793,7 @@ export function emitImportedMessageEvents( localId: message.localId ?? null, content: message.content, createdAt: message.createdAt, + receivedAt: message.receivedAt, invokedAt: message.invokedAt } }) @@ -837,7 +838,6 @@ async function mergeSingleDuplicateCodexSessionGroup(options: { const knownKeys = new Set(canonical.comparableKeys) const removedSessionIds: string[] = [] - const appendedMessages: StoredMessage[] = [] let latestActivity = canonical.updatedAt if ( @@ -851,7 +851,34 @@ async function mergeSingleDuplicateCodexSessionGroup(options: { ) } + // Computed from every duplicate's OWN pre-merge messages, BEFORE any of + // them are touched (#1717). The footer and the reply that answers it can + // live in two different sessions — a live projection and an import of + // the same thread — so deriving this from the merge's OWN output would + // need the merge to preserve which row answered which. Computing first + // means the merge never has to carry that evidence through: it can + // dedupe by plain content key, exactly as it always could, because there + // is nothing left here for dropping a duplicate row to lose. + // + // NOT committed yet — see where `applyReconciledNotifyState` is called + // below, after the appended rows are emitted, and why that ordering is + // required. + // + // `sessionStates` is already in the function's required deterministic + // order (most messages, newest `updatedAt`, session id — canonical + // first); see that function's own doc comment for why this matters. + const precomputedNotify = engine + ? engine.computeNotifyStateAcrossDuplicateSessions( + sessionStates.map((candidate) => candidate.sessionId), + canonical.sessionId, + options.namespace + ) + : null + for (const source of sessionStates.slice(1)) { + // Check before touching the source: copies and job transfers are not rolled back. + engine?.assertSessionDeletable(source.sessionId) + const appendedMessages: StoredMessage[] = [] latestActivity = Math.max(latestActivity, source.updatedAt) for (const message of source.storedMessages) { const comparableKey = getComparableStoredMessageKey(message) @@ -864,7 +891,14 @@ async function mergeSingleDuplicateCodexSessionGroup(options: { createdAt: message.createdAt, localId: message.localId, invokedAt: message.invokedAt, - scheduledAt: message.scheduledAt + scheduledAt: message.scheduledAt, + // Arrival and delivery disposition belong to the original + // event, independent of the row-survival rules above: a + // LATER re-derivation (a rewind, a restart backfill) still + // reads this session's own merged transcript and needs its + // real hub-arrival time, not a copy-time restamp (#1717). + receivedAt: message.receivedAt, + agentDelivered: message.agentDelivered }) knownKeys.add(comparableKey) appendedMessages.push(copied) @@ -884,21 +918,42 @@ async function mergeSingleDuplicateCodexSessionGroup(options: { } } removedSessionIds.push(source.sessionId) - } - if (appendedMessages.length > 0) { - emitImportedMessageEvents(engine, canonical.sessionId, appendedMessages) + // Publish per source: a later refusal must not hide what is already committed. + if (appendedMessages.length > 0) { + emitImportedMessageEvents(engine, canonical.sessionId, appendedMessages) + } + + if (engine) { + engine.recordSessionActivity(canonical.sessionId, latestActivity) + // 即使这次只是删除重复分身、没有新增消息,也主动刷新 canonical 会话,确保左侧列表立刻收敛到合并后的状态。 + engine.handleRealtimeEvent({ + type: 'session-updated', + sessionId: canonical.sessionId + }) + } else { + options.store.sessions.touchSessionUpdatedAt(canonical.sessionId, latestActivity, options.namespace) + } } - if (engine) { - engine.recordSessionActivity(canonical.sessionId, latestActivity) - // 即使这次只是删除重复分身、没有新增消息,也主动刷新 canonical 会话,确保左侧列表立刻收敛到合并后的状态。 + // Committed LAST, after every source's appended rows are emitted + // (#1717): replaying a copied footer through `emitImportedMessageEvents` + // re-derives and overwrites the notify signal via live ingestion, with + // no knowledge that the precomputed projection above already accounted + // for it correctly — replaying a copied REPLY never undoes that, since + // an imported row never goes through the delivery-confirmation callback + // a real one does. Applying the precomputed result after the last + // per-source replay makes it the final word rather than something a + // replay can clobber. + if (engine && precomputedNotify) { + engine.applyReconciledNotifyState(canonical.sessionId, options.namespace, precomputedNotify) + // The per-source refresh above already fired with the pre-correction + // notify state; re-fire once more so a client that rendered off that + // refresh is not left showing it. engine.handleRealtimeEvent({ type: 'session-updated', sessionId: canonical.sessionId }) - } else { - options.store.sessions.touchSessionUpdatedAt(canonical.sessionId, latestActivity, options.namespace) } return { diff --git a/hub/src/web/routes/codexGenericImport.test.ts b/hub/src/web/routes/codexGenericImport.test.ts index 7f7b1dc4a08..c434b1a7ac3 100644 --- a/hub/src/web/routes/codexGenericImport.test.ts +++ b/hub/src/web/routes/codexGenericImport.test.ts @@ -67,6 +67,7 @@ function createImportSyncEngine(store: Store, machines: Machine[]): SyncEngine { store.sessions.getOrCreateSession(tag, metadata, agentState, namespace) as unknown as ReturnType ), handleRealtimeEvent: () => {}, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: () => {} } as unknown as SyncEngine } diff --git a/hub/src/web/routes/devices.test.ts b/hub/src/web/routes/devices.test.ts index 3cc564ef99c..b0031a90bdd 100644 --- a/hub/src/web/routes/devices.test.ts +++ b/hub/src/web/routes/devices.test.ts @@ -209,4 +209,67 @@ describe('devices routes', () => { expect(unregister.status).toBe(200) expect(store.fcm.getDevicesByNamespace('default', ['ios'])).toHaveLength(0) }) + + it('accepts per-device push preferences, preserves them when omitted, and returns hubId when provided', async () => { + const store = new Store(':memory:') + const app = new Hono() + app.use('*', createAuthMiddleware(JWT_SECRET)) + app.route('/api', createDevicesRoutes(store, 'hub-uuid-1234')) + const headers = { ...await authHeaders(), 'content-type': 'application/json' } + const pushKey = Buffer.alloc(32, 6).toString('base64') + + const first = await app.request('/api/devices/register', { + method: 'POST', + headers, + body: JSON.stringify({ + token: 'apns-pref-1', + platform: 'ios', + deviceId: 'iphone-pref', + pushKey, + preferences: { ready: false, permissionRequest: true, inputRequest: false, modelError: true } + }) + }) + expect(first.status).toBe(200) + expect(await first.json()).toEqual({ ok: true, hubId: 'hub-uuid-1234' }) + expect(store.fcm.getDevicesByNamespace('default', ['ios'])[0].preferences).toEqual({ + ready: false, + permissionRequest: true, + inputRequest: false, + modelError: true + }) + + // Omitting preferences keeps the previously registered preferences intact. + const second = await app.request('/api/devices/register', { + method: 'POST', + headers, + body: JSON.stringify({ + token: 'apns-pref-2', + platform: 'ios', + deviceId: 'iphone-pref', + pushKey + }) + }) + expect(second.status).toBe(200) + expect(store.fcm.getDevicesByNamespace('default', ['ios'])[0].preferences).toEqual({ + ready: false, + permissionRequest: true, + inputRequest: false, + modelError: true + }) + + // Rejects malformed preference values. + const bad = await app.request('/api/devices/register', { + method: 'POST', + headers, + body: JSON.stringify({ + token: 'apns-pref-2', + platform: 'ios', + deviceId: 'iphone-pref', + pushKey, + preferences: { ready: 'no' } + }) + }) + expect(bad.status).toBe(400) + store.close() + }) }) diff --git a/hub/src/web/routes/devices.ts b/hub/src/web/routes/devices.ts index 11b9c15acba..b3bc09d72ba 100644 --- a/hub/src/web/routes/devices.ts +++ b/hub/src/web/routes/devices.ts @@ -19,6 +19,13 @@ function decodePushKey(pushKey: string): Buffer | null { return decoded.length === PUSH_KEY_BYTES ? decoded : null } +const pushPreferencesSchema = z.object({ + ready: z.boolean().optional(), + permissionRequest: z.boolean().optional(), + inputRequest: z.boolean().optional(), + modelError: z.boolean().optional() +}) + const registerSchema = z.object({ token: z.string().min(1), platform: z.enum(['phone', 'wear', 'ios']), @@ -27,7 +34,12 @@ const registerSchema = z.object({ * Base64 of 32 device-generated random bytes. Required for iOS; * optional for phone (old direct-FCM clients), ignored for Wear. */ - pushKey: z.string().optional() + pushKey: z.string().optional(), + /** + * Optional per-device push event filter. Omitted keys default to true; + * omitting the object entirely preserves any previously saved filter. + */ + preferences: pushPreferencesSchema.optional() }).superRefine((data, ctx) => { if (data.platform === 'wear' || (data.platform === 'phone' && data.pushKey === undefined)) { return @@ -45,7 +57,7 @@ const unregisterSchema = z.object({ token: z.string().min(1) }) -export function createDevicesRoutes(store: Store): Hono { +export function createDevicesRoutes(store: Store, hubId?: string): Hono { const app = new Hono() app.post('/devices/register', async (c) => { @@ -56,7 +68,7 @@ export function createDevicesRoutes(store: Store): Hono { } const namespace = c.get('namespace') - const { token, platform, deviceId, pushKey } = parsed.data + const { token, platform, deviceId, pushKey, preferences } = parsed.data if (platform !== 'wear' && pushKey !== undefined) { // Store the canonical re-encoding so the send path always // decodes cleanly regardless of the client's padding style. @@ -65,12 +77,13 @@ export function createDevicesRoutes(store: Store): Hono { token, platform, deviceId, - pushKey: decoded.toString('base64') + pushKey: decoded.toString('base64'), + preferences }) } else { - store.fcm.upsertDevice(namespace, { token, platform, deviceId }) + store.fcm.upsertDevice(namespace, { token, platform, deviceId, preferences }) } - return c.json({ ok: true }) + return c.json(hubId ? { ok: true, hubId } : { ok: true }) }) app.delete('/devices/register', async (c) => { diff --git a/hub/src/web/routes/localSessions/claudeResumeImport.test.ts b/hub/src/web/routes/localSessions/claudeResumeImport.test.ts index 7e0dc8bfe27..e07bb636cf4 100644 --- a/hub/src/web/routes/localSessions/claudeResumeImport.test.ts +++ b/hub/src/web/routes/localSessions/claudeResumeImport.test.ts @@ -88,6 +88,7 @@ function machine(): Machine { function harness() { const store = new Store(':memory:') const engine = { + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: () => {}, handleRealtimeEvent: () => {}, applySessionConfig: async () => {}, diff --git a/hub/src/web/routes/localSessions/createLocalSessionRoutes.test.ts b/hub/src/web/routes/localSessions/createLocalSessionRoutes.test.ts index 323ab278b21..7c5180d7a92 100644 --- a/hub/src/web/routes/localSessions/createLocalSessionRoutes.test.ts +++ b/hub/src/web/routes/localSessions/createLocalSessionRoutes.test.ts @@ -88,6 +88,7 @@ function harness(overrides: { : source } }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: () => {}, handleRealtimeEvent: () => {}, applySessionConfig: async (_sessionId: string, config: Record) => { diff --git a/hub/src/web/routes/localSessions/importLocalTranscript.test.ts b/hub/src/web/routes/localSessions/importLocalTranscript.test.ts index 57dc6d900ec..f3a5d7c1fb4 100644 --- a/hub/src/web/routes/localSessions/importLocalTranscript.test.ts +++ b/hub/src/web/routes/localSessions/importLocalTranscript.test.ts @@ -72,6 +72,7 @@ function harness() { const events: unknown[] = [] const appliedConfigs: Array> = [] const engine = { + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, diff --git a/hub/src/web/routes/localSessions/importLocalTranscript.ts b/hub/src/web/routes/localSessions/importLocalTranscript.ts index 42becaac9f0..50cc2e9a2a9 100644 --- a/hub/src/web/routes/localSessions/importLocalTranscript.ts +++ b/hub/src/web/routes/localSessions/importLocalTranscript.ts @@ -166,6 +166,7 @@ function emitImportedMessages(engine: SyncEngine, sessionId: string, messages: S localId: message.localId, content: message.content, createdAt: message.createdAt, + receivedAt: message.receivedAt, invokedAt: message.invokedAt } }) @@ -479,6 +480,9 @@ export function runLocalImportSync(options: { const activityAt = committed.appended.at(-1)?.createdAt ?? transcript.modifiedAt engine.recordSessionActivity(hapiSessionId, activityAt) emitImportedMessages(engine, hapiSessionId, committed.appended) + // Live ingestion stamped a footer per imported row; only the + // transcript as a whole can say whether it is still unanswered. + engine.reconcileNotifySignalAfterImport(hapiSessionId) engine.handleRealtimeEvent({ type: 'session-updated', sessionId: hapiSessionId }) return outcome } catch (error) { diff --git a/hub/src/web/routes/localSessions/piOpencodeGenericImport.test.ts b/hub/src/web/routes/localSessions/piOpencodeGenericImport.test.ts index 5d11611c342..ff29fc7e57d 100644 --- a/hub/src/web/routes/localSessions/piOpencodeGenericImport.test.ts +++ b/hub/src/web/routes/localSessions/piOpencodeGenericImport.test.ts @@ -110,6 +110,7 @@ function harness(overrides: { : summaries return { success: true, sessions: source } }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: () => {}, handleRealtimeEvent: () => {}, applySessionConfig: async (_sessionId: string, config: Record) => { @@ -369,6 +370,7 @@ describe('Pi sync import wrapper', () => { const store = new Store(':memory:') stores.push(store) const engine = { + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: () => {}, handleRealtimeEvent: () => {}, getSessionsByNamespace: () => [] diff --git a/hub/src/web/routes/opencodeSessions.test.ts b/hub/src/web/routes/opencodeSessions.test.ts index 77a65fd6fbc..e6ef991465a 100644 --- a/hub/src/web/routes/opencodeSessions.test.ts +++ b/hub/src/web/routes/opencodeSessions.test.ts @@ -67,6 +67,7 @@ describe('OpenCode session import', () => { stores.push(store) const events: unknown[] = [] const engine = { + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, @@ -143,6 +144,7 @@ describe('OpenCode session import', () => { expect(sessionIds).toEqual(['native-create']) return { success: true, sessions: transcripts } }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, @@ -319,6 +321,7 @@ describe('OpenCode session import', () => { applySessionConfig: async (sessionId: string, config: Record) => { applied.push({ sessionId, config }) }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, @@ -364,6 +367,7 @@ describe('OpenCode session import', () => { await firstRelease } }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, @@ -402,6 +406,7 @@ describe('OpenCode session import', () => { applySessionConfig: async () => { throw new Error('rpc timeout') }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, @@ -434,6 +439,7 @@ describe('OpenCode session import', () => { applySessionConfig: async (sessionId: string, config: Record) => { applied.push({ sessionId, config }) }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, @@ -497,6 +503,7 @@ describe('OpenCode session import', () => { sessions: [transcript('native-omit', [userMessage('native-omit', 'msg-1', 'one', 1_000)])] }), applySessionConfig: async () => { applyCalls += 1 }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, diff --git a/hub/src/web/routes/piSessions.test.ts b/hub/src/web/routes/piSessions.test.ts index 2d3561341a8..7228d46382b 100644 --- a/hub/src/web/routes/piSessions.test.ts +++ b/hub/src/web/routes/piSessions.test.ts @@ -92,6 +92,7 @@ describe('Pi session import', () => { stores.push(store) const events: unknown[] = [] const engine = { + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, @@ -152,6 +153,7 @@ describe('Pi session import', () => { requestedIds = sessionIds return { success: true, sessions: transcripts } }, + reconcileNotifySignalAfterImport: () => {}, recordSessionActivity: (sessionId: string, updatedAt: number) => { store.sessions.touchSessionUpdatedAt(sessionId, updatedAt, 'default') }, diff --git a/hub/src/web/routes/sessions.test.ts b/hub/src/web/routes/sessions.test.ts index f43ff78aedb..723d6b66ab6 100644 --- a/hub/src/web/routes/sessions.test.ts +++ b/hub/src/web/routes/sessions.test.ts @@ -5,6 +5,7 @@ import type { WebAppEnv } from '../middleware/auth' import { createSessionsRoutes } from './sessions' import { ArchiveCleanupError } from '../../sync/archiveCleanupError' import { RpcTargetMissingError } from '../../sync/rpcGateway' +import { BlockedAckMissingKeyError } from '../../sync/sessionCache' function createSession(overrides?: Partial): Session { const baseMetadata = { @@ -86,6 +87,7 @@ function createApp(session: Session, opts?: { allocateAttachedJobVersion?: SyncEngine['allocateAttachedJobVersion'] setSessionPinned?: (sessionId: string, pinned: boolean) => void setSessionPinMode?: (sessionId: string, mode: 'none' | 'project' | 'global') => void + acknowledgeSessionBlocked?: SyncEngine['acknowledgeSessionBlocked'] namespace?: string }) { const applySessionConfigCalls: Array<[string, Record]> = [] @@ -221,7 +223,8 @@ function createApp(session: Session, opts?: { renameSession: opts?.renameSession ?? (async () => {}), updateSessionSummary: opts?.updateSessionSummary ?? (async () => {}), getPrimaryAttachedJobsBySessionIds: opts?.getPrimaryAttachedJobsBySessionIds ?? (() => new Map()), - allocateAttachedJobVersion: opts?.allocateAttachedJobVersion ?? (() => Date.now()) + allocateAttachedJobVersion: opts?.allocateAttachedJobVersion ?? (() => Date.now()), + acknowledgeSessionBlocked: opts?.acknowledgeSessionBlocked ?? (() => ({ at: Date.now(), reason: 'handled' })) } as Partial const app = new Hono() @@ -583,6 +586,41 @@ describe('sessions routes', () => { expect(response.status).toBe(400) }) + it('rejects a reason-only blocked-ack once the session already has a keyed dismissal (#1717 cold-review round 37)', async () => { + // There is no honest way to resolve this at the route: reusing the + // stale key set would report success while dismissing nothing new. + const { app } = createApp(createSession(), { + acknowledgeSessionBlocked: () => { throw new BlockedAckMissingKeyError('session-1') } + }) + + const response = await app.request('/api/sessions/session-1/blocked-ack', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ reason: 'second, no key' }) + }) + + expect(response.status).toBe(400) + }) + + it('accepts a blocked-ack that supplies a key', async () => { + const calls: Array<[string, string, number | undefined, string | undefined]> = [] + const { app } = createApp(createSession(), { + acknowledgeSessionBlocked: (sessionId, reason, observedAt, observedKey) => { + calls.push([sessionId, reason, observedAt, observedKey]) + return { at: Date.now(), reason } + } + }) + + const response = await app.request('/api/sessions/session-1/blocked-ack', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ reason: 'handled', observedKey: 'request:r0' }) + }) + + expect(response.status).toBe(200) + expect(calls).toEqual([['session-1', 'handled', undefined, 'request:r0']]) + }) + it('uses session-scoped Codex model discovery for the fallback endpoint', async () => { const session = createSession({ metadata: { @@ -1165,6 +1203,57 @@ describe('sessions routes', () => { expect(applySessionConfigCalls).toEqual([]) }) + // The existing local-mode gate runs before the combined payload check, so a + // locally driven Codex session keeps its 409 even when effort is included. + it.each([null, 'high'])('rejects a model change with effort %s for a locally driven Codex session', async (effort) => { + const session = createSession({ + agentState: { + controlledByUser: true, + requests: {}, + completedRequests: {} + } + }) + const { app, applySessionConfigCalls } = createApp(session) + + const response = await app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model: 'gpt-5.5', effort }) + }) + + expect(response.status).toBe(409) + expect(await response.json()).toEqual({ + error: 'Model selection can only be changed for remote Codex sessions' + }) + expect(applySessionConfigCalls).toEqual([]) + }) + + // Claude allows effort with the model, so the local-mode gate is reached + // after the combined payload check and still returns the Claude 409. + it('rejects a model change with effort for a locally driven Claude session', async () => { + const session = createSession({ + metadata: { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + agentState: { + controlledByUser: true, + requests: {}, + completedRequests: {} + } + }) + const { app, applySessionConfigCalls } = createApp(session) + + const response = await app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model: 'haiku', effort: null }) + }) + + expect(response.status).toBe(409) + expect(await response.json()).toEqual({ + error: 'Model selection can only be changed for remote Claude sessions' + }) + expect(applySessionConfigCalls).toEqual([]) + }) + it('applies model changes for OpenCode sessions', async () => { const session = createSession({ metadata: { @@ -1295,6 +1384,107 @@ describe('sessions routes', () => { expect(applySessionConfigCalls).toEqual([]) }) + // A locally driven session's launcher only receives the model at spawn, so a + // later web switch is rejected before it is forwarded. concurrentClients (or + // a session that is not locally controlled) keeps the switch valid. + it.each([ + ['claude', 'haiku', 'Model selection can only be changed for remote Claude sessions'], + ['kimi', 'kimi-k2', 'Model selection can only be changed for remote Kimi sessions'], + ['opencode', 'ollama/exaone:4.5-33b-q8', 'Model selection can only be changed for remote OpenCode sessions'], + ['copilot', 'gpt-5.5', 'Model selection can only be changed for remote Copilot sessions'], + ] as const)('rejects local model changes for %s sessions and allows shared or remote switches', async (flavor, model, message) => { + const metadata = { path: '/tmp/project', host: 'localhost', flavor } + const local = createSession({ + metadata, + agentState: { controlledByUser: true, requests: {}, completedRequests: {} } + }) + const localApp = createApp(local) + const localResponse = await localApp.app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model }) + }) + expect(localResponse.status).toBe(409) + expect(await localResponse.json()).toEqual({ error: message }) + expect(localApp.applySessionConfigCalls).toEqual([]) + + const shared = createSession({ + metadata: { ...metadata, capabilities: { concurrentClients: true } }, + agentState: { controlledByUser: true, requests: {}, completedRequests: {} } + }) + const sharedApp = createApp(shared) + const sharedResponse = await sharedApp.app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model }) + }) + expect(sharedResponse.status).toBe(200) + expect(sharedApp.applySessionConfigCalls).toEqual([['session-1', { model }]]) + + const remoteApp = createApp(createSession({ metadata })) + const remoteResponse = await remoteApp.app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model }) + }) + expect(remoteResponse.status).toBe(200) + expect(remoteApp.applySessionConfigCalls).toEqual([['session-1', { model }]]) + }) + + // The effort flavor restriction is a payload check, so it is reported before + // the local-mode gate. An invalid combination keeps the 400 from a remote + // session, while a valid model-only switch still reaches the 409. + it.each([ + ['kimi', 'kimi-k2', 'Model selection can only be changed for remote Kimi sessions'], + ['opencode', 'ollama/exaone:4.5-33b-q8', 'Model selection can only be changed for remote OpenCode sessions'], + ['copilot', 'gpt-5.5', 'Model selection can only be changed for remote Copilot sessions'], + ] as const)('validates the model payload before the local-mode gate for %s', async (flavor, model, message) => { + const session = createSession({ + metadata: { path: '/tmp/project', host: 'localhost', flavor }, + agentState: { controlledByUser: true, requests: {}, completedRequests: {} } + }) + const { app, applySessionConfigCalls } = createApp(session) + + for (const effort of [null, 'high']) { + const invalid = await app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model, effort }) + }) + expect(invalid.status).toBe(400) + expect(await invalid.json()).toEqual({ + error: 'Effort can only be sent with a model change for Claude and Antigravity sessions' + }) + } + + const valid = await app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model }) + }) + expect(valid.status).toBe(409) + expect(await valid.json()).toEqual({ error: message }) + expect(applySessionConfigCalls).toEqual([]) + }) + + it('rejects local model changes when the session has no flavor (treated as Claude)', async () => { + const local = createSession({ + metadata: { path: '/tmp/project', host: 'localhost', flavor: undefined }, + agentState: { controlledByUser: true, requests: {}, completedRequests: {} } + }) + const { app, applySessionConfigCalls } = createApp(local) + + const response = await app.request('/api/sessions/session-1/model', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model: 'haiku' }) + }) + + expect(response.status).toBe(409) + expect(await response.json()).toEqual({ error: 'Model selection can only be changed for remote Claude sessions' }) + expect(applySessionConfigCalls).toEqual([]) + }) + it('rejects effort changes for non-Claude sessions', async () => { const { app, applySessionConfigCalls } = createApp(createSession()) @@ -1379,6 +1569,69 @@ describe('sessions routes', () => { expect(localApp.applySessionConfigCalls).toEqual([]) }) + // Effort mirrors model: a locally driven launcher never receives a later + // effort change, while shared or remote sessions keep applying it. + it.each([ + ['claude', 'max', 'Effort can only be changed for remote Claude sessions'], + ['kimi', 'high', 'Effort can only be changed for remote Kimi sessions'], + ['copilot', 'low', 'Effort can only be changed for remote Copilot sessions'], + ] as const)('rejects local effort changes for %s sessions and allows shared or remote changes', async (flavor, effort, message) => { + const metadata = { path: '/tmp/project', host: 'localhost', flavor } + const local = createSession({ + metadata, + agentState: { controlledByUser: true, requests: {}, completedRequests: {} } + }) + const localApp = createApp(local) + const localResponse = await localApp.app.request('/api/sessions/session-1/effort', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ effort }) + }) + expect(localResponse.status).toBe(409) + expect(await localResponse.json()).toEqual({ error: message }) + expect(localApp.applySessionConfigCalls).toEqual([]) + + const shared = createSession({ + metadata: { ...metadata, capabilities: { concurrentClients: true } }, + agentState: { controlledByUser: true, requests: {}, completedRequests: {} } + }) + const sharedApp = createApp(shared) + const sharedResponse = await sharedApp.app.request('/api/sessions/session-1/effort', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ effort }) + }) + expect(sharedResponse.status).toBe(200) + expect(sharedApp.applySessionConfigCalls).toEqual([['session-1', { effort }]]) + + const remoteApp = createApp(createSession({ metadata })) + const remoteResponse = await remoteApp.app.request('/api/sessions/session-1/effort', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ effort }) + }) + expect(remoteResponse.status).toBe(200) + expect(remoteApp.applySessionConfigCalls).toEqual([['session-1', { effort }]]) + }) + + it('rejects local effort changes when the session has no flavor (treated as Claude)', async () => { + const local = createSession({ + metadata: { path: '/tmp/project', host: 'localhost', flavor: undefined }, + agentState: { controlledByUser: true, requests: {}, completedRequests: {} } + }) + const { app, applySessionConfigCalls } = createApp(local) + + const response = await app.request('/api/sessions/session-1/effort', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ effort: 'high' }) + }) + + expect(response.status).toBe(409) + expect(await response.json()).toEqual({ error: 'Effort can only be changed for remote Claude sessions' }) + expect(applySessionConfigCalls).toEqual([]) + }) + it('returns OpenCode reasoning effort options for active OpenCode sessions', async () => { const session = createSession({ metadata: { path: '/tmp/project', host: 'localhost', flavor: 'opencode' } @@ -2372,6 +2625,30 @@ describe('sessions routes', () => { expect(unlimitedBody.sessions).toHaveLength(3) }) + it('carries the engine\'s hubGeneration on GET /sessions (#1717 cold-review round 29)', async () => { + const engine = { + getSessionsByNamespace: () => [], + getFutureScheduledMessageCounts: () => new Map(), + getNextScheduledAtBySessionIds: () => new Map(), + getPrimaryAttachedJobsBySessionIds: () => new Map(), + allocateAttachedJobVersion: () => Date.now(), + resolveSessionAccess: () => ({ ok: false, reason: 'not-found' as const }), + hubGeneration: 'generation-under-test' + } as unknown as Partial + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createSessionsRoutes(() => engine as SyncEngine)) + + const response = await app.request('/api/sessions') + expect(response.status).toBe(200) + const body = await response.json() as { hubGeneration?: string } + expect(body.hubGeneration).toBe('generation-under-test') + }) + it('searches message content only through the explicit content endpoint', async () => { const session = createSession({ id: 'content-session' }) const engine = { @@ -2878,7 +3155,17 @@ describe('per-flavor model and effort config gates', () => { const MODEL_LOCAL_MESSAGES: Record = { codex: 'Model selection can only be changed for remote Codex sessions', cursor: 'Model selection can only be changed for remote Cursor sessions', - grok: 'Model selection can only be changed for remote Grok sessions' + grok: 'Model selection can only be changed for remote Grok sessions', + claude: 'Model selection can only be changed for remote Claude sessions', + kimi: 'Model selection can only be changed for remote Kimi sessions', + opencode: 'Model selection can only be changed for remote OpenCode sessions', + copilot: 'Model selection can only be changed for remote Copilot sessions' + } + const EFFORT_LOCAL_MESSAGES: Record = { + claude: 'Effort can only be changed for remote Claude sessions', + kimi: 'Effort can only be changed for remote Kimi sessions', + copilot: 'Effort can only be changed for remote Copilot sessions', + grok: 'Effort can only be changed for remote Grok sessions' } function expected(flavor: string | null, op: ConfigOp, state: SessionState): Expected { @@ -2886,7 +3173,8 @@ describe('per-flavor model and effort config gates', () => { const local = state === 'local' if (op === 'model') { if (!MODEL_CHANGE.has(flavor)) return { status: 400, error: 'Model selection is not supported for this session' } - const message = local ? MODEL_LOCAL_MESSAGES[flavor ?? ''] : undefined + // A session without a flavor is treated as Claude, so the Claude gate applies. + const message = local ? MODEL_LOCAL_MESSAGES[flavor ?? 'claude'] : undefined return message ? { status: 409, error: message } : { status: 200 } } if (op === 'modelReasoningEffort') { @@ -2896,9 +3184,8 @@ describe('per-flavor model and effort config gates', () => { : { status: 200 } } if (!EFFORT.has(flavor)) return { status: 400, error: 'Effort selection is not supported for this session type' } - return local && flavor === 'grok' - ? { status: 409, error: 'Effort can only be changed for remote Grok sessions' } - : { status: 200 } + const effortMessage = local ? EFFORT_LOCAL_MESSAGES[flavor ?? 'claude'] : undefined + return effortMessage ? { status: 409, error: effortMessage } : { status: 200 } } function makeSession(flavor: string | null, state: SessionState): Session { diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index 9d607e5241d..4a475108d46 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -39,6 +39,7 @@ import { UpdateSessionSummaryRequestSchema, supportsModelChange, supportsEffort, + SetSessionBlockedAckRequestSchema, usesEffortWithModelChange, usesModelReasoningEffort, toSessionSummary, @@ -62,6 +63,7 @@ import { serializeContentSearchSessionIds } from '../../store/messageContentSearch' import { ArchiveCleanupError } from '../../sync/archiveCleanupError' +import { BlockedAckMissingKeyError } from '../../sync/sessionCache' import { requireSessionFromParam, requireSyncEngine } from './guards' const MAX_UPLOAD_BYTES = 50 * 1024 * 1024 @@ -274,7 +276,7 @@ export function createSessionsRoutes( } }) - return c.json({ sessions, serverTime: Date.now() }) + return c.json({ sessions, serverTime: Date.now(), hubGeneration: engine.hubGeneration }) }) app.get('/sessions/scratchlist-status', (c) => { @@ -1524,6 +1526,7 @@ export function createSessionsRoutes( if (!supportsModelChange(flavor)) { return c.json({ error: 'Model selection is not supported for this session' }, 400) } + if (sessionResult.session.agentState?.controlledByUser === true && !sessionResult.session.metadata?.capabilities?.concurrentClients) { if (flavor === 'codex') { return c.json({ error: 'Model selection can only be changed for remote Codex sessions' }, 409) @@ -1543,6 +1546,21 @@ export function createSessionsRoutes( return c.json({ error: 'Effort can only be sent with a model change for Claude and Antigravity sessions' }, 400) } + if (sessionResult.session.agentState?.controlledByUser === true && !sessionResult.session.metadata?.capabilities?.concurrentClients) { + if (flavor === 'claude') { + return c.json({ error: 'Model selection can only be changed for remote Claude sessions' }, 409) + } + if (flavor === 'kimi') { + return c.json({ error: 'Model selection can only be changed for remote Kimi sessions' }, 409) + } + if (flavor === 'opencode') { + return c.json({ error: 'Model selection can only be changed for remote OpenCode sessions' }, 409) + } + if (flavor === 'copilot') { + return c.json({ error: 'Model selection can only be changed for remote Copilot sessions' }, 409) + } + } + try { await engine.applySessionConfig(sessionResult.sessionId, effort === undefined ? { model } : { model, effort }) return c.json({ ok: true }) @@ -1609,8 +1627,19 @@ export function createSessionsRoutes( if (!supportsEffort(flavor)) { return c.json({ error: 'Effort selection is not supported for this session type' }, 400) } - if (flavor === 'grok' && sessionResult.session.agentState?.controlledByUser === true && !sessionResult.session.metadata?.capabilities?.concurrentClients) { - return c.json({ error: 'Effort can only be changed for remote Grok sessions' }, 409) + if (sessionResult.session.agentState?.controlledByUser === true && !sessionResult.session.metadata?.capabilities?.concurrentClients) { + if (flavor === 'claude') { + return c.json({ error: 'Effort can only be changed for remote Claude sessions' }, 409) + } + if (flavor === 'kimi') { + return c.json({ error: 'Effort can only be changed for remote Kimi sessions' }, 409) + } + if (flavor === 'copilot') { + return c.json({ error: 'Effort can only be changed for remote Copilot sessions' }, 409) + } + if (flavor === 'grok') { + return c.json({ error: 'Effort can only be changed for remote Grok sessions' }, 409) + } } try { @@ -1764,6 +1793,41 @@ export function createSessionsRoutes( return c.json({ ok: true }) }) + // #1717: manual unblock. Reason is required by the schema — a dismissal + // with no rationale is exactly what this endpoint exists to prevent. + app.put('/sessions/:id/blocked-ack', async (c) => { + const engine = requireSyncEngine(c, getSyncEngine) + if (engine instanceof Response) return engine + + const sessionResult = requireSessionFromParam(c, engine) + if (sessionResult instanceof Response) return sessionResult + + const body = await c.req.json().catch(() => null) + const parsed = SetSessionBlockedAckRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid body: reason is required' }, 400) + } + + let ack: ReturnType + try { + ack = engine.acknowledgeSessionBlocked( + sessionResult.sessionId, + parsed.data.reason, + parsed.data.observedAt, + parsed.data.observedKey + ) + } catch (error) { + if (error instanceof BlockedAckMissingKeyError) { + return c.json({ error: error.message }, 400) + } + throw error + } + if (!ack) { + return c.json({ error: 'Failed to acknowledge' }, 500) + } + return c.json({ ok: true, blockedAck: ack }) + }) + app.delete('/sessions/:id', async (c) => { const engine = requireSyncEngine(c, getSyncEngine) if (engine instanceof Response) { diff --git a/hub/src/web/server.ts b/hub/src/web/server.ts index 73a8b3a82a7..39bb6736a01 100644 --- a/hub/src/web/server.ts +++ b/hub/src/web/server.ts @@ -321,6 +321,7 @@ export function createWebApp(options: { distDir?: string relayMode?: boolean officialWebUrl?: string + hubId?: string }): Hono { const app = new Hono() @@ -372,6 +373,7 @@ export function createWebApp(options: { app.get('/health', (c) => c.json({ status: 'ok', protocolVersion: PROTOCOL_VERSION, + ...(options.hubId ? { hubId: options.hubId } : {}), capabilities: { workGraph: true, titleSuggestion: readTitleProviderConfig() !== null @@ -426,7 +428,7 @@ export function createWebApp(options: { getSyncEngine: options.getSyncEngine })) app.route('/api', createPushRoutes(options.store, options.vapidPublicKey)) - app.route('/api', createDevicesRoutes(options.store)) + app.route('/api', createDevicesRoutes(options.store, options.hubId)) app.route('/api', createVoiceRoutes({ dataDir: configuration.dataDir })) // Path is intentionally NOT `/api/events` — that route is the SSE stream. app.route('/api', createWorkGraphRoutes(options.store)) @@ -585,6 +587,7 @@ export async function startWebServer(options: { corsOrigins?: string[] relayMode?: boolean officialWebUrl?: string + hubId?: string }): Promise> { const isCompiled = isBunCompiled() const embeddedAssetMap = isCompiled ? await loadEmbeddedAssetMap() : null @@ -598,7 +601,8 @@ export async function startWebServer(options: { corsOrigins: options.corsOrigins, embeddedAssetMap, relayMode: options.relayMode, - officialWebUrl: options.officialWebUrl + officialWebUrl: options.officialWebUrl, + hubId: options.hubId }) const configuration = getConfiguration() diff --git a/ios/Hapi.xcodeproj/project.pbxproj b/ios/Hapi.xcodeproj/project.pbxproj index d195e0f48c3..4b58438c701 100644 --- a/ios/Hapi.xcodeproj/project.pbxproj +++ b/ios/Hapi.xcodeproj/project.pbxproj @@ -412,7 +412,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 0.37.0; + MARKETING_VERSION = 0.37.1; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTS_MACCATALYST = YES; @@ -447,7 +447,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 0.37.0; + MARKETING_VERSION = 0.37.1; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTS_MACCATALYST = YES; @@ -475,7 +475,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.37.0; + MARKETING_VERSION = 0.37.1; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app.HapiNotificationService; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; @@ -504,7 +504,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.37.0; + MARKETING_VERSION = 0.37.1; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app.HapiNotificationService; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; diff --git a/ios/Hapi/Features/Chat/Blocks/ChatBlockCard.swift b/ios/Hapi/Features/Chat/Blocks/ChatBlockCard.swift index 626faef0751..2668c97173e 100644 --- a/ios/Hapi/Features/Chat/Blocks/ChatBlockCard.swift +++ b/ios/Hapi/Features/Chat/Blocks/ChatBlockCard.swift @@ -64,13 +64,14 @@ extension EnvironmentValues { struct ChatBlockCard: View { let block: VisibleChatBlock let basePath: String? + var isStreaming: Bool = false var body: some View { switch block { case .toolGroup(let group): ToolGroupBlockView(presentation: ToolGroupPresentation(group)) case .block(let chatBlock): - ChatSubBlockView(block: chatBlock, basePath: basePath) + ChatSubBlockView(block: chatBlock, basePath: basePath, isStreaming: isStreaming) } } } @@ -80,15 +81,16 @@ struct ChatBlockCard: View { struct ChatSubBlockView: View { let block: ChatBlock let basePath: String? + var isStreaming: Bool = false var body: some View { switch block { case .userText(let value): UserTextBlockView(block: value) case .agentText(let value): - AgentTextBlockView(block: value) + AgentTextBlockView(block: value, isStreaming: isStreaming) case .agentReasoning(let value): - AgentReasoningBlockView(block: value) + AgentReasoningBlockView(block: value, isStreaming: isStreaming) case .agentEvent(let value): AgentEventBlockView(block: value) case .cliOutput(let value): diff --git a/ios/Hapi/Features/Chat/Blocks/GeneratedImageBlockView.swift b/ios/Hapi/Features/Chat/Blocks/GeneratedImageBlockView.swift index 7d5bf0dfc6e..5afe8a9ca6a 100644 --- a/ios/Hapi/Features/Chat/Blocks/GeneratedImageBlockView.swift +++ b/ios/Hapi/Features/Chat/Blocks/GeneratedImageBlockView.swift @@ -1,6 +1,7 @@ import AVKit import Combine import HapiProtocol +import HapiUI import QuickLook import SwiftUI import UIKit @@ -78,7 +79,7 @@ private struct GeneratedMediaCard: View { if phase != .active { content.pause() } } .fullScreenCover(isPresented: $imageOpen) { - ImageViewer(image: content.image, title: content.block.fileName) + HapiImageViewer(image: content.image, title: content.block.fileName) } .sheet(isPresented: $previewOpen) { if let file = content.file { @@ -188,33 +189,3 @@ private struct GeneratedMediaPreview: UIViewControllerRepresentable { } func updateUIViewController(_ controller: QLPreviewController, context: Context) {} } - -/// Minimal full-screen image viewer; keep the existing tap-to-dismiss behavior. -private struct ImageViewer: View { - let image: UIImage? - let title: String - @Environment(\.dismiss) private var dismiss - - var body: some View { - ZStack(alignment: .topTrailing) { - Color.black.ignoresSafeArea() - if let image { - Image(uiImage: image) - .resizable() - .scaledToFit() - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(8) - } else { - Text(verbatim: title).foregroundStyle(.white) - } - Button { dismiss() } label: { - Image(systemName: "xmark.circle.fill") - .font(.title2) - .foregroundStyle(.white.opacity(0.8)) - .padding(16) - } - .accessibilityLabel("Close") - } - .onTapGesture { dismiss() } - } -} diff --git a/ios/Hapi/Features/Chat/Blocks/PermissionActionViews.swift b/ios/Hapi/Features/Chat/Blocks/PermissionActionViews.swift index 14e598408b0..5aaaf30c567 100644 --- a/ios/Hapi/Features/Chat/Blocks/PermissionActionViews.swift +++ b/ios/Hapi/Features/Chat/Blocks/PermissionActionViews.swift @@ -134,13 +134,19 @@ struct PermissionActionsRow: View { @ViewBuilder private func buttons(horizontal: Bool) -> some View { - Button { submit(.allow) } label: { + Button { + HapiHaptics.success() + submit(.allow) + } label: { Text("Allow").fixedSize(horizontal: horizontal, vertical: true) } .buttonStyle(ChatActionButtonStyle(emphasis: .primary)) .accessibilityIdentifier("permission-allow-\(requestId)") - Button { submit(options.denyAction) } label: { + Button { + HapiHaptics.warning() + submit(options.denyAction) + } label: { Text(options.denyAction == .abort ? LocalizedStringKey("Abort") : LocalizedStringKey("Deny")) .fixedSize(horizontal: horizontal, vertical: true) } @@ -150,10 +156,16 @@ struct PermissionActionsRow: View { if options.hasMore { Menu { if options.canAllowForSession { - Button("Allow for this session") { submit(.allowForSession) } + Button("Allow for this session") { + HapiHaptics.success() + submit(.allowForSession) + } } if options.canAllowAllEdits { - Button("Allow all edits") { submit(.allowAllEdits) } + Button("Allow all edits") { + HapiHaptics.success() + submit(.allowAllEdits) + } } } label: { if horizontal { diff --git a/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift b/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift index 1e65e58667d..cfa38c264bc 100644 --- a/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift +++ b/ios/Hapi/Features/Chat/Blocks/TextBlockViews.swift @@ -137,9 +137,10 @@ struct UserTextBlockView: View { /// Assistant prose: full-width markdown through the shared M2e renderer. struct AgentTextBlockView: View { let block: AgentTextBlock + var isStreaming: Bool = false var body: some View { - CachedMarkdownView(markdown: block.text) + CachedMarkdownView(markdown: block.text, isStreaming: isStreaming) .frame(maxWidth: .infinity, alignment: .leading) } } @@ -148,11 +149,14 @@ struct AgentTextBlockView: View { /// the full reasoning markdown (still subdued — it is meta-content). struct AgentReasoningBlockView: View { let block: AgentReasoningBlock + let isStreaming: Bool @ChatStoredState private var expanded: Bool - init(block: AgentReasoningBlock) { + init(block: AgentReasoningBlock, isStreaming: Bool = false) { self.block = block - _expanded = ChatStoredState(wrappedValue: false, id: block.id, field: "expanded") + self.isStreaming = isStreaming + let defaultExpanded = UserDefaults.standard.bool(forKey: ReadingPrefs.autoExpandReasoningKey) + _expanded = ChatStoredState(wrappedValue: defaultExpanded, id: block.id, field: "expanded") } var body: some View { @@ -171,7 +175,7 @@ struct AgentReasoningBlockView: View { } .buttonStyle(.plain) if expanded { - CachedMarkdownView(markdown: block.text) + CachedMarkdownView(markdown: block.text, isStreaming: isStreaming) .opacity(0.75) .padding(.leading, 8) } diff --git a/ios/Hapi/Features/Chat/ChatContentSearchSheet.swift b/ios/Hapi/Features/Chat/ChatContentSearchSheet.swift new file mode 100644 index 00000000000..ae2ffcc50ae --- /dev/null +++ b/ios/Hapi/Features/Chat/ChatContentSearchSheet.swift @@ -0,0 +1,156 @@ +import HapiClient +import HapiProtocol +import HapiUI +import SwiftUI + +/// In-conversation full-text search sheet backed by +/// `GET /api/sessions/:id/content-search`. +struct ChatContentSearchSheet: View { + let api: APIClient + let sessionId: String + + @Environment(\.dismiss) private var dismiss + @Environment(\.hapiPasteboard) private var pasteboard + @State private var query = "" + @State private var matches: [SessionContentMatch] = [] + @State private var total = 0 + @State private var isLoading = false + @State private var hasSearched = false + @State private var errorMessage: String? + @State private var copiedId: String? + + private var trimmedQuery: String { + query.trimmingCharacters(in: .whitespacesAndNewlines) + } + + var body: some View { + NavigationStack { + Group { + if trimmedQuery.isEmpty { + ContentUnavailableView( + "Search Conversation", + systemImage: "magnifyingglass", + description: Text("Find messages across the entire conversation history.") + ) + } else if isLoading && matches.isEmpty { + ProgressView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let errorMessage { + ContentUnavailableView( + "Search Failed", + systemImage: "exclamationmark.triangle", + description: Text(errorMessage) + ) + } else if hasSearched && matches.isEmpty { + ContentUnavailableView.search(text: trimmedQuery) + } else { + List { + Section { + ForEach(matches) { match in + matchRow(match) + } + } header: { + Text("\(total, specifier: "%lld") matches") + } + } + .listStyle(.plain) + } + } + .navigationTitle("Find in Conversation") + .navigationBarTitleDisplayMode(.inline) + .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Search messages…")) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + .task(id: trimmedQuery) { + await runSearch(for: trimmedQuery) + } + } + .presentationDetents([.medium, .large]) + } + + private func matchRow(_ match: SessionContentMatch) -> some View { + Button { + pasteboard.copy(match.snippet) + copiedId = match.id + Task { + try? await Task.sleep(for: .seconds(1.2)) + if copiedId == match.id { copiedId = nil } + } + } label: { + VStack(alignment: .leading, spacing: 5) { + HStack(spacing: 6) { + Text(match.role == "user" ? String(localized: "You") : String(localized: "Agent")) + .font(.caption.weight(.semibold)) + .foregroundStyle(match.role == "user" ? Color.accentColor : Color.secondary) + Text(Date(timeIntervalSince1970: Double(match.createdAt) / 1000.0) + .formatted(.relative(presentation: .named))) + .font(.caption2) + .foregroundStyle(.secondary) + Spacer() + if copiedId == match.id { + Label("Copied", systemImage: "checkmark") + .font(.caption2.weight(.medium)) + .foregroundStyle(.green) + } else { + Text(verbatim: "#\(match.seq)") + .font(.caption2.monospacedDigit()) + .foregroundStyle(.tertiary) + } + } + Text(highlightedSnippet(match.snippet, query: trimmedQuery)) + .font(.subheadline) + .foregroundStyle(.primary) + .lineLimit(4) + .fixedSize(horizontal: false, vertical: true) + } + .padding(.vertical, 3) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + private func runSearch(for term: String) async { + guard !term.isEmpty else { + matches = [] + total = 0 + hasSearched = false + errorMessage = nil + isLoading = false + return + } + try? await Task.sleep(for: .milliseconds(250)) + guard !Task.isCancelled else { return } + isLoading = true + errorMessage = nil + do { + let response = try await api.searchSessionContent(sessionId: sessionId, query: term, limit: 100) + guard !Task.isCancelled else { return } + matches = response.matches + total = response.total + hasSearched = true + isLoading = false + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { return } + errorMessage = error.localizedDescription + isLoading = false + } + } + + private func highlightedSnippet(_ snippet: String, query: String) -> AttributedString { + var attributed = AttributedString(snippet) + guard !query.isEmpty else { return attributed } + var searchStart = attributed.startIndex + while searchStart < attributed.endIndex, + let range = attributed[searchStart...].range(of: query, options: [.caseInsensitive, .diacriticInsensitive]) { + attributed[range].backgroundColor = Color.accentColor.opacity(0.22) + attributed[range].inlinePresentationIntent = .stronglyEmphasized + searchStart = range.upperBound + } + return attributed + } +} diff --git a/ios/Hapi/Features/Chat/ChatModel.swift b/ios/Hapi/Features/Chat/ChatModel.swift index 5131a88c45b..65b56eafb85 100644 --- a/ios/Hapi/Features/Chat/ChatModel.swift +++ b/ios/Hapi/Features/Chat/ChatModel.swift @@ -53,6 +53,29 @@ final class ChatModel { private(set) var loadFailed = false /// Tail-sync warning — the degraded banner. private(set) var warning: String? + /// Active streaming agent text/reasoning block IDs at the live tail (used to + /// defer syntax highlighting inside unclosed code fences until settled). + private(set) var streamingBlockIds: Set = [] + /// Epoch ms when the current active turn started (drives the live elapsed timer). + private(set) var activeTurnStartedAtMs: Int? + /// Context window token metrics derived from the reducer's latest usage. + private(set) var contextMetrics: ContextWindowMetrics? + /// Current session todo checklist (`Session.todos`). + private(set) var todos: [TodoItem] = [] + /// Best-effort uncommitted git diff totals for the composer track bar. + private(set) var gitDiffStats: SessionGitDiffStats? + /// Skills reported by `GET /api/sessions/:id/skills` for the composer picker. + private(set) var skills: [SkillSummary] = [] + /// Primary linked GitHub PR status chip (`GET /api/sessions/:id/external-refs`). + private(set) var primaryPr: PrChipDisplay? + /// Spawned peer sessions whose `groupLeaderId` points to this session. + var groupMembers: [SessionSummary] { + hub.sessionStore.sessions.filter { $0.metadata?.groupLeaderId == sessionId } + } + /// Aggregated status counts across `groupMembers`. + var groupStatus: SessionGroupStatus { + SessionGroups.summarizeMembers(groupMembers, isUnread: { _ in false }) + } /// Bumps on tail-side content changes. private(set) var tailRevision = 0 private(set) var readThroughRevision: Int? @@ -160,6 +183,31 @@ final class ChatModel { ?? hub.sessionStore.sessions.first { $0.id == sessionId }?.active } + /// Machine hosting this session, used to scope the context-sheet quotas card. + var sessionMachineId: String? { + hub.sessionStore.detail(for: sessionId)?.metadata?.machineId + ?? hub.sessionStore.sessions.first { $0.id == sessionId }?.metadata?.machineId + } + + /// Interactive shell terminal support (mirrors web `isRemoteTerminalSupported` + /// gated on an active session). + var canOpenShellTerminal: Bool { + guard sessionIsActive == true else { return false } + return hub.sessionStore.detail(for: sessionId)?.metadata?.capabilities?.terminal ?? true + } + + /// Live Agent PTY terminal support (active PTY sessions only; mirrors web + /// `SessionChat`'s `metadata?.startingMode === 'pty' && session.active`). + var canViewAgentTerminal: Bool { + guard sessionIsActive == true else { return false } + return hub.sessionStore.detail(for: sessionId)?.metadata?.startingMode == .pty + } + + /// Whether the Terminal action should be offered for this session. + var canOpenTerminal: Bool { + canOpenShellTerminal || canViewAgentTerminal + } + // MARK: Wiring private let hub: HubSession @@ -187,6 +235,10 @@ final class ChatModel { /// The hub's scratchlist store, for the toolbar-badge sheet (A-M4b). var scratchlist: ScratchlistStore { hub.scratchlist } @ObservationIgnored private var noticeTask: Task? + @ObservationIgnored private var gitDiffTask: Task? + @ObservationIgnored private var skillsTask: Task? + @ObservationIgnored private var externalRefsTask: Task? + @ObservationIgnored private var fallbackThinkingStartedAtMs: Int? @ObservationIgnored private var windowState: MessageWindowState? @ObservationIgnored private var detailLoadFailed = false @@ -318,6 +370,12 @@ final class ChatModel { switch event { case .transcribed(let text): self.interactor.appendDictatedText(text) + case .transcribedAndSend(let text): + self.interactor.appendDictatedText(text) + if self.interactor.composerDestination == .chat, + !self.interactor.composerText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + self.interactor.sendMessage() + } case .noProvider: self.showNotice(String(localized: "No transcription provider configured on hub")) case .error(let message): @@ -350,6 +408,9 @@ final class ChatModel { } } await self.loadDetail() + self.refreshGitDiffStats() + self.refreshSkills() + self.refreshExternalRefs() } } @@ -362,6 +423,12 @@ final class ChatModel { statesTask = nil pipelineTask?.cancel() pipelineTask = nil + gitDiffTask?.cancel() + gitDiffTask = nil + skillsTask?.cancel() + skillsTask = nil + externalRefsTask?.cancel() + externalRefsTask = nil cancelHistory() jumpTask?.cancel() jumpTask = nil @@ -380,6 +447,59 @@ final class ChatModel { chat.stop() } + func refreshGitDiffStats() { + guard sessionIsActive != false else { return } + gitDiffTask?.cancel() + let api = hub.api + let id = sessionId + gitDiffTask = Task { [weak self] in + async let unstagedResult = try? api.gitDiffNumstat(sessionId: id, staged: false) + async let stagedResult = try? api.gitDiffNumstat(sessionId: id, staged: true) + let (unstagedResponse, stagedResponse) = await (unstagedResult, stagedResult) + guard !Task.isCancelled, let self else { return } + let unstagedOk = unstagedResponse?.success == true + let stagedOk = stagedResponse?.success == true + guard unstagedOk || stagedOk else { return } + let unstaged = NumstatParser.parse(unstagedOk ? (unstagedResponse?.stdout ?? "") : "") + let staged = NumstatParser.parse(stagedOk ? (stagedResponse?.stdout ?? "") : "") + let combined = SessionGitDiffStats.combine(unstaged: unstaged, staged: staged) + self.gitDiffStats = combined.hasChanges ? combined : nil + } + } + + private func refreshSkills() { + skillsTask?.cancel() + let api = hub.api + let id = sessionId + skillsTask = Task { [weak self] in + guard let response = try? await api.skills(sessionId: id), + !Task.isCancelled, + let self, + response.success else { return } + let loaded = (response.skills ?? []).sorted { + $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending + } + if self.skills != loaded { + self.skills = loaded + } + } + } + + func refreshExternalRefs() { + externalRefsTask?.cancel() + let api = hub.api + let id = sessionId + externalRefsTask = Task { [weak self] in + guard let refs = try? await api.sessionExternalRefs(sessionId: id), + !Task.isCancelled, + let self else { return } + let next = PrChipDisplay.primary(from: refs) + if self.primaryPr != next { + self.primaryPr = next + } + } + } + private func showNotice(_ message: String) { notice = message noticeTask?.cancel() @@ -609,14 +729,37 @@ final class ChatModel { let detail = hub.sessionStore.detail(for: sessionId) let summary = hub.sessionStore.sessions.first { $0.id == sessionId } let machines = hub.machineStore.machines - let visible = await pipeline.run( + let output = await pipeline.runWithUsage( messages: window.messages, agentState: detail?.agentState, hasMoreMessages: window.hasMore, directSendLocalIds: interactor.directSendLocalIds ) - let sources = Set(visible.flatMap { block -> [String] in - guard case .block(let value) = block else { return [] } + let visible = output.blocks + let isThinking = detail?.thinking ?? summary?.thinking ?? false + var streamingIds = Set() + var streamingEntries: [MarkdownRenderCache.StreamingEntry] = [] + if isThinking { + for block in visible.reversed() { + guard case .block(let value) = block else { break } + switch value { + case .agentText(let text): + streamingIds.insert(block.stableId) + streamingEntries.append(.init(id: block.stableId, text: text.text)) + case .agentReasoning(let text): + streamingIds.insert(block.stableId) + streamingEntries.append(.init(id: block.stableId, text: text.text)) + default: + break + } + if case .agentText = value { continue } + if case .agentReasoning = value { continue } + break + } + } + let settledSources = Set(visible.flatMap { block -> [String] in + guard !streamingIds.contains(block.stableId), + case .block(let value) = block else { return [] } switch value { case .agentText(let text): return [text.text] case .agentReasoning(let text): return [text.text] @@ -624,10 +767,21 @@ final class ChatModel { default: return [] } }) - await markdownCache.prepare(Array(sources.subtracting(previousMarkdownSources))) - previousMarkdownSources = sources + await markdownCache.prepare( + settled: Array(settledSources.subtracting(previousMarkdownSources)), + streaming: streamingEntries + ) + previousMarkdownSources = settledSources guard !Task.isCancelled else { return } - apply(visible, window: window, detail: detail, summary: summary, machines: machines) + apply( + visible, + latestUsage: output.latestUsage, + window: window, + detail: detail, + summary: summary, + machines: machines, + streamingIds: streamingIds + ) } // No suspension between this check and parking, so a concurrent // scheduleRecompute either lands before it (loop again) or finds @@ -642,12 +796,18 @@ final class ChatModel { private func apply( _ visible: [VisibleChatBlock], + latestUsage: LatestUsage?, window: MessageWindowState, detail: Session?, summary: SessionSummary?, - machines: [Machine] + machines: [Machine], + streamingIds: Set ) { guard !chat.isRemoved else { return } + let wasThinking = header.thinking + if streamingBlockIds != streamingIds { + streamingBlockIds = streamingIds + } if let previousEpoch = lastEpoch, let epoch = window.epoch, previousEpoch != epoch { cancelHistory() jumpToLatestToken += 1 @@ -684,6 +844,38 @@ final class ChatModel { summary: summary, machines: machines ) + if header.thinking { + let serverStart = detail?.activeTurnStartedAt + ?? (detail?.thinkingAt ?? 0 > 0 ? detail?.thinkingAt : nil) + if let serverStart, serverStart > 0 { + fallbackThinkingStartedAtMs = serverStart + activeTurnStartedAtMs = serverStart + } else { + if fallbackThinkingStartedAtMs == nil { + fallbackThinkingStartedAtMs = Int(Date().timeIntervalSince1970 * 1000) + } + activeTurnStartedAtMs = fallbackThinkingStartedAtMs + } + } else { + fallbackThinkingStartedAtMs = nil + activeTurnStartedAtMs = nil + if wasThinking { + refreshGitDiffStats() + refreshExternalRefs() + } + } + let nextMetrics = ContextWindowMetrics.resolve( + usage: latestUsage, + sessionModel: detail?.model ?? summary?.model, + flavor: header.flavor + ) + if contextMetrics != nextMetrics { + contextMetrics = nextMetrics + } + let nextTodos = detail?.todos ?? [] + if todos != nextTodos { + todos = nextTodos + } basePath = detail?.metadata?.path ?? summary?.metadata?.path hasMore = window.hasMore historyPaging.refreshAvailability(hasMore: hasMore) diff --git a/ios/Hapi/Features/Chat/ChatTranscriptView.swift b/ios/Hapi/Features/Chat/ChatTranscriptView.swift index 5afa51c293a..a7b0174026d 100644 --- a/ios/Hapi/Features/Chat/ChatTranscriptView.swift +++ b/ios/Hapi/Features/Chat/ChatTranscriptView.swift @@ -6,29 +6,35 @@ import SwiftUI /// Tool groups contribute only their displayed summary to transcript diffs. enum TranscriptRow: Identifiable, Equatable { case history(ChatHistoryPagingState.Phase, Bool) - case message(VisibleChatBlock) + case message(VisibleChatBlock, isStreaming: Bool = false) case group(ToolGroupPresentation) + /// Live working indicator & elapsed wall-clock timer pinned at the end of + /// the transcript while a turn is running. + case thinking(startedAtMs: Int?) /// A message or group row closed by its copy / share / details / time /// actions. Same identity and rhythm as the wrapped row, so the action /// row never changes the transcript's item count or anchors. indirect case withActions(TranscriptRow, MessageFooter) static let historyID = "chat-history-control" + static let thinkingID = "chat-thinking-footer" var role: TranscriptRowRole { switch self { case .history: .history + case .thinking: .content case .withActions(let row, _): row.role case .group: .tool - case .message(.toolGroup): .tool - case .message(.block(.userText)): .user - case .message(.block(.toolCall)): .tool + case .message(.toolGroup, _): .tool + case .message(.block(.userText), _): .user + case .message(.block(.toolCall), _): .tool default: .content } } var id: String { switch self { case .history: Self.historyID - case .message(let block): block.stableId + case .thinking: Self.thinkingID + case .message(let block, _): block.stableId case .group(let group): group.id case .withActions(let row, _): row.id } @@ -48,14 +54,18 @@ struct ChatTranscriptView: View { // One action row closes each agent response, under its last block // (web card join). let footers = buildMessageFooters(model.blocks) + let streamingIds = model.streamingBlockIds for block in model.blocks { let row: TranscriptRow = if case .toolGroup(let group) = block { .group(ToolGroupPresentation(group)) } else { - .message(block) + .message(block, isStreaming: streamingIds.contains(block.stableId)) } rows.append(footers[block.stableId].map { TranscriptRow.withActions(row, $0) } ?? row) } + if model.header.thinking { + rows.append(.thinking(startedAtMs: model.activeTurnStartedAtMs)) + } return rows } @@ -138,13 +148,49 @@ struct ChatTranscriptView: View { .buttonStyle(.plain) .disabled(!hasMore || model.isLoadingOlder || model.isSyncingTail) .accessibilityIdentifier("chat-history") - case .message(let block): - ChatBlockCard(block: block, basePath: model.basePath) + case .message(let block, let isStreaming): + ChatBlockCard(block: block, basePath: model.basePath, isStreaming: isStreaming) case .group(let presentation): ToolGroupBlockView(presentation: presentation) + case .thinking(let startedAtMs): + ActiveTurnFooterView(startedAtMs: startedAtMs) case .withActions: // Unwrapped by `rowView`; rows are never nested twice. EmptyView() } } } + +/// Fixed-height active-turn indicator with live elapsed wall-clock duration. +private struct ActiveTurnFooterView: View { + let startedAtMs: Int? + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + var body: some View { + HStack(spacing: 8) { + if reduceMotion { + Image(systemName: "ellipsis.circle") + .font(.caption) + .foregroundStyle(.secondary) + } else { + ProgressView() + .controlSize(.mini) + } + Text("Working") + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + if let startedAtMs { + TimelineView(.periodic(from: .now, by: 1.0)) { context in + let nowMs = Int(context.date.timeIntervalSince1970 * 1000) + Text(verbatim: ContextWindowMetrics.formatElapsed(sinceMs: startedAtMs, nowMs: nowMs)) + .font(.caption.monospacedDigit()) + .foregroundStyle(.tertiary) + } + } + Spacer(minLength: 0) + } + .frame(minHeight: 24, alignment: .leading) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("chat-thinking-footer") + } +} diff --git a/ios/Hapi/Features/Chat/ChatView.swift b/ios/Hapi/Features/Chat/ChatView.swift index 4e13e597b06..2363fa9108d 100644 --- a/ios/Hapi/Features/Chat/ChatView.swift +++ b/ios/Hapi/Features/Chat/ChatView.swift @@ -19,6 +19,8 @@ struct ChatView: View { @State private var configOpen = false /// Files browser push (toolbar folder, A-M4a). @State private var filesOpen = false + /// Native CoreText remote terminal push. + @State private var terminalOpen = false /// File viewer push for `hapi-file://` chat citations (A-M4a). @State private var viewerRoute: FileViewerRoute? /// Full inventory; the compact drawer lives with the composer below. @@ -30,10 +32,17 @@ struct ChatView: View { @State private var deleteOpen = false @State private var forkConfirmOpen = false @State private var historyOpen = false + @State private var contextDetailsOpen = false + @State private var todosSheetOpen = false + @State private var groupMembersSheetOpen = false + @State private var contentSearchOpen = false + @Environment(\.openURL) private var openURL /// Resume/reopen handed back a superseding session id — the host swaps /// its navigation entry (HomeView replaces the path element). private let onNavigateToSession: ((String) -> Void)? + /// User tapped a `/sessions/` citation inside the transcript. + private let onOpenLinkedSession: ((String) -> Void)? /// Kept for the files/viewer pushes (the model owns its own reference). private let session: HubSession @@ -57,16 +66,27 @@ struct ChatView: View { init( session: HubSession, sessionId: String, + onOpenLinkedSession: ((String) -> Void)? = nil, onNavigateToSession: ((String) -> Void)? = nil ) { - self.init(session: session, model: ChatModel(session: session, sessionId: sessionId), - onNavigateToSession: onNavigateToSession) + self.init( + session: session, + model: ChatModel(session: session, sessionId: sessionId), + onOpenLinkedSession: onOpenLinkedSession, + onNavigateToSession: onNavigateToSession + ) } - init(session: HubSession, model: ChatModel, onNavigateToSession: ((String) -> Void)? = nil) { + init( + session: HubSession, + model: ChatModel, + onOpenLinkedSession: ((String) -> Void)? = nil, + onNavigateToSession: ((String) -> Void)? = nil + ) { _model = State(initialValue: model) self.session = session self.sessionId = model.sessionId + self.onOpenLinkedSession = onOpenLinkedSession self.onNavigateToSession = onNavigateToSession } @@ -102,11 +122,25 @@ struct ChatView: View { } .safeAreaInset(edge: .bottom, spacing: 0) { VStack(spacing: 0) { + ComposerTrackBarView( + todos: model.todos, + groupMembers: model.groupMembers, + groupStatus: model.groupStatus, + diffStats: model.gitDiffStats, + primaryPr: model.primaryPr, + onOpenTodos: { todosSheetOpen = true }, + onOpenGroupMembers: { groupMembersSheetOpen = true }, + onOpenDiff: { filesOpen = true }, + onOpenPr: { url in openURL(url) } + ) QueuedMessagesBarView(interactor: model.interactor) ChatComposerView( interactor: model.interactor, dictation: model.dictation, - hugsBottomEdge: isFoldedOuterScreen + hugsBottomEdge: isFoldedOuterScreen, + contextMetrics: model.contextMetrics, + onOpenContextDetails: { contextDetailsOpen = true }, + skills: model.skills ) { entry, editing in scratchlistEntry = entry scratchlistStartsEditing = editing @@ -139,11 +173,23 @@ struct ChatView: View { } ToolbarItem(placement: .topBarTrailing) { Menu { + Button { + contentSearchOpen = true + } label: { + Label("Find in Conversation…", systemImage: "magnifyingglass") + } Button { filesOpen = true } label: { Label("Session files", systemImage: "folder") } + if model.canOpenTerminal { + Button { + terminalOpen = true + } label: { + Label("Terminal", systemImage: "terminal") + } + } Button { model.interactor.setComposerDestination(.scratchlist) } label: { @@ -226,6 +272,7 @@ struct ChatView: View { .focusedSceneValue(\.chatCommands, ChatCommandActions( openSessionSettings: { configOpen = true }, openFiles: { filesOpen = true }, + openTerminal: model.canOpenTerminal ? { terminalOpen = true } : nil, rename: { renameText = model.header.title renameOpen = true @@ -233,26 +280,73 @@ struct ChatView: View { export: model.isExporting ? nil : { model.exportConversation() }, stop: model.interactor.composer.canSteer ? { model.interactor.abortSession() } : nil )) + .navigationDestination(isPresented: $terminalOpen) { + TerminalScreenView( + hub: session, + sessionId: sessionId, + canViewAgentTerminal: model.canViewAgentTerminal, + canOpenShellTerminal: model.canOpenShellTerminal, + onSendExcerptToChat: { formatted in + model.interactor.setComposerDestination(.chat) + model.interactor.insertComposerText(formatted) + model.interactor.focusComposer() + } + ) + } .navigationDestination(isPresented: $filesOpen) { - FilesView(session: session, sessionId: sessionId) + FilesView(session: session, sessionId: sessionId) { prompt in + model.interactor.sendPromptText(prompt) + filesOpen = false + viewerRoute = nil + } + } + .onChange(of: filesOpen) { _, isOpen in + if !isOpen { model.refreshGitDiffStats() } + } + .sheet(isPresented: $contextDetailsOpen) { + if let metrics = model.contextMetrics { + ContextWindowDetailSheet( + metrics: metrics, + api: session.api, + preferredMachineId: model.sessionMachineId + ) + } + } + .sheet(isPresented: $contentSearchOpen) { + ChatContentSearchSheet(api: session.api, sessionId: sessionId) + } + .sheet(isPresented: $todosSheetOpen) { + SessionTodosSheet(todos: model.todos) + } + .sheet(isPresented: $groupMembersSheetOpen) { + SessionGroupMembersSheet(members: model.groupMembers) { memberId in + onOpenLinkedSession?(memberId) + } } .navigationDestination(item: $viewerRoute) { route in // A replaced route value must rebuild the screen's @State model // (HomeView's chat-push precedent). - FileViewerView(session: session, route: route) - .id(route) + FileViewerView(session: session, route: route) { prompt in + model.interactor.sendPromptText(prompt) + viewerRoute = nil + filesOpen = false + } + .id(route) } // Chat markdown citations open the real viewer in full mode with the // cited line as a hint chip (replaces the root placeholder alert for // this subtree; the destinations above inherit the handler too). - .handlesHapiLinks { link in - viewerRoute = FileViewerRoute( - sessionId: sessionId, - path: link.path, - mode: .file, - line: link.line - ) - } + .handlesHapiLinks( + openWorkspaceFile: { link in + viewerRoute = FileViewerRoute( + sessionId: sessionId, + path: link.path, + mode: .file, + line: link.line + ) + }, + openSession: onOpenLinkedSession + ) .sheet(isPresented: $scratchlistOpen) { ScratchlistView( store: model.scratchlist, diff --git a/ios/Hapi/Features/Chat/Composer/AVAudioRecorderDictation.swift b/ios/Hapi/Features/Chat/Composer/AVAudioRecorderDictation.swift index e46612d531a..af5d2e96bee 100644 --- a/ios/Hapi/Features/Chat/Composer/AVAudioRecorderDictation.swift +++ b/ios/Hapi/Features/Chat/Composer/AVAudioRecorderDictation.swift @@ -17,6 +17,8 @@ final class AVAudioRecorderDictation: DictationRecorder { private var recorder: AVAudioRecorder? private var output: URL? + private var interruptionObserver: NSObjectProtocol? + private var interruptionHandler: (@MainActor () -> Void)? enum RecorderError: LocalizedError { case alreadyRecording @@ -32,10 +34,37 @@ final class AVAudioRecorderDictation: DictationRecorder { } } + deinit { + if let observer = interruptionObserver { + NotificationCenter.default.removeObserver(observer) + } + } + + func setInterruptionHandler(_ handler: (@MainActor () -> Void)?) { + interruptionHandler = handler + } + + func currentAudioLevel() -> Float { + guard let audioRecorder = recorder, audioRecorder.isRecording else { return 0 } + audioRecorder.updateMeters() + let power = audioRecorder.averagePower(forChannel: 0) + // Map -55 dB ... -5 dB onto 0 ... 1 with a slight curve so normal speech + // visibly animates without pinning at 100%. + let minDb: Float = -55 + let maxDb: Float = -5 + let clamped = min(max(power, minDb), maxDb) + let normalized = (clamped - minDb) / (maxDb - minDb) + return pow(normalized, 1.3) + } + func start() throws { guard recorder == nil else { throw RecorderError.alreadyRecording } let session = AVAudioSession.sharedInstance() - try session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker]) + try session.setCategory( + .playAndRecord, + mode: .default, + options: [.defaultToSpeaker, .allowBluetoothHFP, .allowBluetoothA2DP] + ) try session.setActive(true) let url = FileManager.default.temporaryDirectory @@ -48,11 +77,13 @@ final class AVAudioRecorderDictation: DictationRecorder { ] do { let audioRecorder = try AVAudioRecorder(url: url, settings: settings) + audioRecorder.isMeteringEnabled = true guard audioRecorder.record() else { throw RecorderError.couldNotStart } recorder = audioRecorder output = url + installInterruptionObserver() } catch { try? FileManager.default.removeItem(at: url) deactivateSession() @@ -61,6 +92,7 @@ final class AVAudioRecorderDictation: DictationRecorder { } func stop() throws -> Data? { + removeInterruptionObserver() guard let audioRecorder = recorder, let url = output else { return nil } recorder = nil output = nil @@ -74,6 +106,7 @@ final class AVAudioRecorderDictation: DictationRecorder { } func cancel() { + removeInterruptionObserver() guard let audioRecorder = recorder else { return } recorder = nil audioRecorder.stop() @@ -85,7 +118,37 @@ final class AVAudioRecorderDictation: DictationRecorder { deactivateSession() } + private func installInterruptionObserver() { + removeInterruptionObserver() + interruptionObserver = NotificationCenter.default.addObserver( + forName: AVAudioSession.interruptionNotification, + object: AVAudioSession.sharedInstance(), + queue: .main + ) { [weak self] notification in + guard let raw = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt, + AVAudioSession.InterruptionType(rawValue: raw) == .began else { + return + } + MainActor.assumeIsolated { + guard let self, self.recorder != nil else { return } + self.cancel() + self.interruptionHandler?() + } + } + } + + private func removeInterruptionObserver() { + if let observer = interruptionObserver { + NotificationCenter.default.removeObserver(observer) + interruptionObserver = nil + } + } + private func deactivateSession() { - try? AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation]) + let session = AVAudioSession.sharedInstance() + try? session.setActive(false, options: [.notifyOthersOnDeactivation]) + // Reset back to ambient + mixWithOthers so returning to the app later + // does not silently pause the user's background music or podcasts. + try? session.setCategory(.ambient, options: [.mixWithOthers]) } } diff --git a/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift b/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift index da8a4e01901..34c72dd09ae 100644 --- a/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift +++ b/ios/Hapi/Features/Chat/Composer/ChatComposerView.swift @@ -22,6 +22,11 @@ struct ChatComposerView: View { /// Folded iPhone Duo: the short outer screen keeps more transcript by /// letting the composer sit closer to the home indicator. var hugsBottomEdge = false + /// Context-window token metrics for the circular progress meter; nil hides it. + var contextMetrics: ContextWindowMetrics? = nil + var onOpenContextDetails: (() -> Void)? = nil + /// Available session skills for the composer skills picker button. + var skills: [SkillSummary] = [] var onOpenScratchlist: (ScratchlistEntry?, Bool) -> Void = { _, _ in } // Attachment pickers (the launchers live here; policy + upload live in @@ -36,6 +41,13 @@ struct ChatComposerView: View { @State private var isComposing = false @State private var preparingAttachment = false @State private var schedulePickerOpen = false + @State private var fullscreenEditorOpen = false + @State private var skillsPickerOpen = false + @State private var hardwareKeyboard = HardwareKeyboardObserver() + @State private var promptRecall = ComposerPromptRecall() + @State private var applyingRecall = false + @State private var highlightedSuggestionIndex = 0 + @State private var dismissedPopupKey: String? = nil // Secondary tools are bare symbols; only the primary action is a filled // circle (Messages / ChatGPT / Claude). Both follow Dynamic Type. @ScaledMetric(relativeTo: .body) private var toolGlyphSize: CGFloat = 20 @@ -49,7 +61,12 @@ struct ChatComposerView: View { private var text: Binding { Binding( get: { interactor.composerText }, - set: { interactor.setComposerText($0) } + set: { newValue in + if !applyingRecall { + promptRecall.reset() + } + interactor.setComposerText(newValue) + } ) } @@ -73,12 +90,30 @@ struct ChatComposerView: View { var body: some View { let composer = interactor.composer let attachments = interactor.attachments.items - let slashSuggestions = interactor.slashSuggestions - let mentionSuggestions = mentionRequest == nil ? [] : interactor.mentionSuggestions(selection: textSelection) + let rawSlashSuggestions = interactor.slashSuggestions + let rawMentionSuggestions = mentionRequest == nil ? [] : interactor.mentionSuggestions(selection: textSelection) + let popupKey: String? = if !rawMentionSuggestions.isEmpty { + "m:\(mentionRequest?.query ?? "")" + } else if !rawSlashSuggestions.isEmpty { + "s:\(interactor.composerText)" + } else { + nil + } + let popupDismissed = popupKey != nil && popupKey == dismissedPopupKey + let mentionSuggestions = popupDismissed ? [] : rawMentionSuggestions + let slashSuggestions = popupDismissed ? [] : rawSlashSuggestions + let activeSuggestionCount = !mentionSuggestions.isEmpty ? mentionSuggestions.count : slashSuggestions.count + let activeHighlight: Int? = (hardwareKeyboard.isConnected && activeSuggestionCount > 0) + ? min(highlightedSuggestionIndex, activeSuggestionCount - 1) + : nil let collapsed = isCollapsed(composer, attachments: attachments) VStack(spacing: 0) { if !mentionSuggestions.isEmpty { - ComposerMentionList(suggestions: mentionSuggestions, surface: composerSurfaceColor) { suggestion in + ComposerMentionList( + suggestions: mentionSuggestions, + surface: composerSurfaceColor, + highlightedIndex: activeHighlight + ) { suggestion in if let selection = interactor.selectMention(suggestion, selection: textSelection) { textSelection = selection textFocused = true @@ -86,7 +121,11 @@ struct ChatComposerView: View { } .padding(.bottom, 6) } else if !slashSuggestions.isEmpty { - SlashCommandList(commands: slashSuggestions, surface: composerSurfaceColor) { command in + SlashCommandList( + commands: slashSuggestions, + surface: composerSurfaceColor, + highlightedIndex: activeHighlight + ) { command in interactor.selectSlashCommand(command) } .padding(.bottom, 6) @@ -115,14 +154,30 @@ struct ChatComposerView: View { .padding(.top, 8) } if let dictation, case .recording(let startedAtMs) = dictation.state { - RecordingChipView(startedAtMs: startedAtMs) { - dictation.cancel() - } + RecordingChipView( + startedAtMs: startedAtMs, + audioLevels: dictation.audioLevels, + allowSend: !scratchlistMode, + onCancel: { dictation.cancel() }, + onInsert: { dictation.stopAndInsert() }, + onSend: { dictation.stopAndSend() } + ) + .padding(.horizontal, 12) + .padding(.top, 8) + } else if let dictation, let failedTake = dictation.failedTake { + DictationRetryBanner( + message: failedTake.message, + onRetry: { dictation.retryFailedTranscription() }, + onDismiss: { dictation.discardFailedTranscription() } + ) .padding(.horizontal, 12) .padding(.top, 8) } // The field keeps one structural identity across the compact // and expanded layouts so focus survives the switch. + let showExpandButton = !collapsed && ( + interactor.composerText.contains("\n") || interactor.composerText.count >= 80 + ) HStack(spacing: 0) { if collapsed { addAttachmentButton } ZStack(alignment: .topLeading) { @@ -142,12 +197,47 @@ struct ChatComposerView: View { handleReturn(composer, attachments: attachments, mentions: mentionSuggestions, slashCommands: slashSuggestions) }, + onArrowUp: { + handleArrow(delta: -1, mentions: mentionSuggestions, slashCommands: slashSuggestions) + }, + onArrowDown: { + handleArrow(delta: 1, mentions: mentionSuggestions, slashCommands: slashSuggestions) + }, + onEscape: { + guard let popupKey, !popupDismissed else { return false } + dismissedPopupKey = popupKey + return true + }, onPasteItems: ingest) } - .padding(.horizontal, collapsed ? 2 : 14) + .padding(.leading, collapsed ? 2 : 14) + .padding(.trailing, collapsed ? 2 : (showExpandButton ? 36 : 14)) .padding(.top, collapsed ? 0 : 12) .padding(.bottom, collapsed ? 0 : 4) - if collapsed { trailingActions(composer, attachments: attachments) } + .overlay(alignment: .topTrailing) { + if showExpandButton { + Button { + textFocused = false + fullscreenEditorOpen = true + } label: { + Image(systemName: "arrow.up.left.and.arrow.down.right") + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + .frame(width: 28, height: 28) + .background(.fill.tertiary, in: Circle()) + } + .buttonStyle(.plain) + .padding(.top, 8) + .padding(.trailing, 8) + .accessibilityLabel("Expand editor") + } + } + if collapsed { + if !hugsBottomEdge, let contextMetrics, let onOpenContextDetails { + ContextWindowRingButton(metrics: contextMetrics, onTap: onOpenContextDetails) + } + trailingActions(composer, attachments: attachments) + } } .padding(.horizontal, collapsed ? 4 : 0) .padding(.vertical, collapsed ? 4 : 0) @@ -156,6 +246,10 @@ struct ChatComposerView: View { addAttachmentButton if interactor.scratchlist != nil { scratchlistButton } if !scratchlistMode { scheduleButton(hasAttachments: !attachments.isEmpty) } + if !scratchlistMode, !skills.isEmpty { skillsButton } + if let contextMetrics, let onOpenContextDetails { + ContextWindowRingButton(metrics: contextMetrics, onTap: onOpenContextDetails) + } Spacer() trailingActions(composer, attachments: attachments) } @@ -180,6 +274,12 @@ struct ChatComposerView: View { .onChange(of: interactor.composerFocusRequest) { textFocused = true } + .onChange(of: popupKey) { _, next in + highlightedSuggestionIndex = 0 + if next != dismissedPopupKey { + dismissedPopupKey = nil + } + } // Hardware keyboard: ⌘↩ sends, matching the Send button's gate. .background { Button("Send") { interactor.sendMessage() } @@ -207,6 +307,33 @@ struct ChatComposerView: View { interactor.setPendingSchedule(.at(Int(date.timeIntervalSince1970 * 1000))) } } + .sheet(isPresented: $skillsPickerOpen) { + SessionSkillsSheet(skills: skills) { skill in + interactor.appendDictatedText("$\(skill.name)") + if !interactor.composerText.hasSuffix(" ") { + interactor.setComposerText(interactor.composerText + " ") + } + textFocused = true + } + } + .sheet(isPresented: $fullscreenEditorOpen) { + FullscreenComposerSheet( + text: text, + scratchlistMode: scratchlistMode, + attachmentCount: attachments.count, + canSend: scratchlistMode + ? (interactor.hasComposerDraft && !interactor.scratchlistBusy && !interactor.isSending && !interactor.attachments.hasUnsettled && !preparingAttachment) + : primaryAction(composer, attachments: attachments).canSend, + onSubmit: { + HapiHaptics.medium() + if scratchlistMode { + interactor.parkComposerDraft() + } else { + interactor.sendMessage() + } + } + ) + } .task(id: dictation.map { ObjectIdentifier($0) }) { await dictation?.refreshAvailability() } @@ -387,6 +514,18 @@ struct ChatComposerView: View { .accessibilityIdentifier("chat.add-attachment") } + private var skillsButton: some View { + Button { + skillsPickerOpen = true + } label: { + toolGlyph("sparkles") + } + .buttonStyle(.plain) + .disabled(interactor.scratchlistBusy) + .accessibilityLabel("Skills") + .accessibilityIdentifier("chat.skills") + } + private var scratchlistButton: some View { Button { interactor.setComposerDestination(scratchlistMode ? .chat : .scratchlist) @@ -456,11 +595,13 @@ struct ChatComposerView: View { private func toggleDictation(_ dictation: DictationController) { // Stopping never needs the permission; starting checks + requests it. guard dictation.state == .idle else { + HapiHaptics.light() dictation.toggle() return } switch AVAudioApplication.shared.recordPermission { case .granted: + HapiHaptics.light() dictation.toggle() case .denied: interactor.postNotice(String(localized: "Microphone access is disabled — allow it in Settings to dictate")) @@ -468,12 +609,14 @@ struct ChatComposerView: View { Task { let granted = await AVAudioApplication.requestRecordPermission() if granted { + HapiHaptics.light() dictation.toggle() } else { interactor.postNotice(String(localized: "Microphone permission is needed for dictation")) } } @unknown default: + HapiHaptics.light() dictation.toggle() } } @@ -484,12 +627,13 @@ struct ChatComposerView: View { /// action) instead of the field above a tool row. Anything in flight — /// a draft, chips, a schedule, recording, the scratchlist — expands it. private func isCollapsed(_ composer: ComposerState, attachments: [ComposerAttachmentUI]) -> Bool { - let recording: Bool = { - if let dictation, case .recording = dictation.state { return true } - return false + let dictationActive: Bool = { + guard let dictation else { return false } + if case .recording = dictation.state { return true } + return dictation.failedTake != nil }() return !textFocused && !scratchlistMode && composer.text.isEmpty && attachments.isEmpty - && interactor.pendingSchedule == nil && interactor.scratchlistError == nil && !recording + && interactor.pendingSchedule == nil && interactor.scratchlistError == nil && !dictationActive } @ViewBuilder @@ -508,27 +652,57 @@ struct ChatComposerView: View { else { primaryActionButton(composer, attachments: attachments) } } - /// Mac Return: picks the first visible suggestion, otherwise sends when - /// the Send button would. Scratchlist drafts keep Return as a newline. + /// Hardware Return (Mac Catalyst + iPad/iPhone external keyboard): picks the + /// highlighted suggestion, otherwise sends when the Send button would. + /// Scratchlist drafts keep Return as a newline. private func handleReturn(_ composer: ComposerState, attachments: [ComposerAttachmentUI], mentions: [ComposerMentionSuggestion], slashCommands: [SlashCommand]) -> Bool { - if let suggestion = mentions.first { - if let selection = interactor.selectMention(suggestion, selection: textSelection) { + if !mentions.isEmpty { + let idx = min(max(0, highlightedSuggestionIndex), mentions.count - 1) + if let selection = interactor.selectMention(mentions[idx], selection: textSelection) { textSelection = selection } + highlightedSuggestionIndex = 0 return true } - if let command = slashCommands.first { - interactor.selectSlashCommand(command) + if !slashCommands.isEmpty { + let idx = min(max(0, highlightedSuggestionIndex), slashCommands.count - 1) + interactor.selectSlashCommand(slashCommands[idx]) + highlightedSuggestionIndex = 0 return true } guard !scratchlistMode else { return false } if primaryAction(composer, attachments: attachments).canSend { + promptRecall.reset() interactor.sendMessage() } return true } + private func handleArrow( + delta: Int, + mentions: [ComposerMentionSuggestion], + slashCommands: [SlashCommand] + ) -> Bool { + let count = !mentions.isEmpty ? mentions.count : slashCommands.count + if count > 0 { + let current = min(max(0, highlightedSuggestionIndex), count - 1) + highlightedSuggestionIndex = (current + delta + count) % count + return true + } + guard !scratchlistMode else { return false } + let history = interactor.sentUserPrompts + let recalled: String? = delta < 0 + ? promptRecall.stepUp(currentText: interactor.composerText, history: history) + : promptRecall.stepDown(history: history) + guard let recalled else { return false } + applyingRecall = true + interactor.setComposerText(recalled) + textSelection = NSRange(location: recalled.utf16.count, length: 0) + applyingRecall = false + return true + } + private func primaryAction(_ composer: ComposerState, attachments: [ComposerAttachmentUI]) -> ComposerPrimaryAction { let hasText = !composer.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty let hasDraft = hasText || !attachments.isEmpty @@ -570,6 +744,7 @@ struct ChatComposerView: View { .accessibilityLabel("Send") case .stop: Button { + HapiHaptics.medium() interactor.abortSession() } label: { actionCircle( @@ -586,6 +761,7 @@ struct ChatComposerView: View { let label = sendLabel(enabled: enabled) if scheduled { Button { + HapiHaptics.medium() interactor.sendMessage() } label: { label @@ -597,16 +773,19 @@ struct ChatComposerView: View { // Tap sends (hub default, else queue); long-press picks one explicitly. Menu { Button("Send & steer into current turn") { + HapiHaptics.medium() interactor.sendMessage(as: .steer) } if interactor.followUpDefault != nil { Button("Send & queue until the turn ends") { + HapiHaptics.medium() interactor.sendMessage(as: .queue) } } } label: { label } primaryAction: { + HapiHaptics.medium() interactor.sendMessage() } .menuStyle(.button) @@ -614,6 +793,7 @@ struct ChatComposerView: View { .accessibilityLabel("Send — long-press to steer") } else { Button { + HapiHaptics.medium() interactor.sendMessage() } label: { label @@ -708,17 +888,24 @@ private enum ComposerPrimaryAction { private struct SlashCommandList: View { let commands: [SlashCommand] let surface: Color + var highlightedIndex: Int? = nil let onSelect: (SlashCommand) -> Void var body: some View { - Group { - if commands.count > 4 { - ScrollView { + ScrollViewReader { proxy in + Group { + if commands.count > 4 { + ScrollView { + rows + } + .frame(height: 220) + } else { rows } - .frame(height: 220) - } else { - rows + } + .onChange(of: highlightedIndex) { _, next in + guard let next, commands.indices.contains(next) else { return } + proxy.scrollTo(commands[next].name, anchor: .center) } } .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(surface)) @@ -733,6 +920,7 @@ private struct SlashCommandList: View { if index > 0 { Divider().padding(.leading, 12) } + let isHighlighted = highlightedIndex == index Button { onSelect(command) } label: { @@ -750,9 +938,11 @@ private struct SlashCommandList: View { .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) .padding(.horizontal, 12) .padding(.vertical, 4) + .background(isHighlighted ? Color.accentColor.opacity(0.14) : Color.clear) .contentShape(Rectangle()) } .buttonStyle(.plain) + .id(command.name) .accessibilityIdentifier("composer.slash.\(command.name)") } } @@ -967,26 +1157,69 @@ func formatChipSize(_ bytes: Int) -> String { // MARK: - Recording chip -/// Elapsed-time recording chip with a cancel affordance (discards the take). +/// Live-waveform recording chip with Cancel, Insert (edit), and Send controls. private struct RecordingChipView: View { let startedAtMs: Int + let audioLevels: [Float] + let allowSend: Bool let onCancel: () -> Void + let onInsert: () -> Void + let onSend: () -> Void var body: some View { TimelineView(.periodic(from: .now, by: 0.25)) { context in HStack(spacing: 8) { - Text("● Recording… \(formatElapsed(elapsedSeconds(at: context.date)))") - .font(.caption.weight(.medium)) - Spacer(minLength: 8) - Button("Cancel") { - onCancel() + Circle() + .fill(.red) + .frame(width: 7, height: 7) + Text(formatElapsed(elapsedSeconds(at: context.date))) + .font(.caption.weight(.semibold)) + .monospacedDigit() + .foregroundStyle(.red) + HStack(alignment: .center, spacing: 2) { + ForEach(Array(audioLevels.suffix(12).enumerated()), id: \.offset) { _, level in + Capsule() + .fill(.red.opacity(0.78)) + .frame(width: 2.5, height: max(4, CGFloat(level) * 18)) + } + } + .frame(height: 18) + .animation(.linear(duration: 0.08), value: audioLevels) + .accessibilityHidden(true) + Spacer(minLength: 4) + Button(action: onCancel) { + Image(systemName: "xmark") + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + .frame(width: 28, height: 28) + .background(.fill.tertiary, in: Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Cancel recording") + Button(action: onInsert) { + Image(systemName: "pencil") + .font(.caption.weight(.semibold)) + .foregroundStyle(.primary) + .frame(width: 28, height: 28) + .background(.fill.secondary, in: Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Transcribe to composer") + if allowSend { + Button(action: onSend) { + Image(systemName: "arrow.up") + .font(.caption.weight(.bold)) + .foregroundStyle(.white) + .frame(width: 28, height: 28) + .background(.tint, in: Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Transcribe and send") } - .font(.caption.weight(.semibold)) } - .padding(.horizontal, 12) + .padding(.horizontal, 10) .padding(.vertical, 6) - .background(.red.opacity(0.12), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) - .foregroundStyle(.red) + .background(.red.opacity(0.11), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) } } @@ -995,11 +1228,102 @@ private struct RecordingChipView: View { } } +/// Inline recovery chip when transcription upload failed while audio is retained. +private struct DictationRetryBanner: View { + let message: String + let onRetry: () -> Void + let onDismiss: () -> Void + + var body: some View { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .font(.caption) + .foregroundStyle(.orange) + Text(message) + .font(.caption) + .foregroundStyle(.primary) + .lineLimit(2) + Spacer(minLength: 4) + Button("Retry", action: onRetry) + .font(.caption.weight(.semibold)) + Button(action: onDismiss) { + Image(systemName: "xmark") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.secondary) + .padding(4) + } + .buttonStyle(.plain) + .accessibilityLabel("Dismiss") + } + .padding(.horizontal, 10) + .padding(.vertical, 7) + .background(.orange.opacity(0.12), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + } +} + /// `m:ss` elapsed-time label for the recording chip. func formatElapsed(_ totalSeconds: Int) -> String { String(format: "%d:%02d", totalSeconds / 60, totalSeconds % 60) } +/// Full-height prompt editor for long multi-line drafts. +private struct FullscreenComposerSheet: View { + @Binding var text: String + let scratchlistMode: Bool + let attachmentCount: Int + let canSend: Bool + let onSubmit: () -> Void + + @Environment(\.dismiss) private var dismiss + @FocusState private var focused: Bool + + var body: some View { + NavigationStack { + VStack(spacing: 0) { + TextEditor(text: $text) + .focused($focused) + .font(.body) + .padding(.horizontal, 12) + .padding(.vertical, 8) + Divider() + HStack(spacing: 12) { + if attachmentCount > 0 { + Label("\(attachmentCount, specifier: "%lld")", systemImage: "paperclip") + .font(.caption) + .foregroundStyle(.secondary) + } + Text("\(text.count, specifier: "%lld") chars") + .font(.caption) + .monospacedDigit() + .foregroundStyle(.secondary) + Spacer() + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + } + .navigationTitle(scratchlistMode ? "Edit Draft" : "Compose Message") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Done") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button(scratchlistMode ? "Save draft" : "Send") { + onSubmit() + dismiss() + } + .fontWeight(.semibold) + .disabled(!canSend) + } + } + .onAppear { + focused = true + } + } + .presentationDetents([.large]) + } +} + // MARK: - Video import /// Photo-picker videos land as a temp file (`FileRepresentation`) so the diff --git a/ios/Hapi/Features/Chat/Composer/ComposerMentionList.swift b/ios/Hapi/Features/Chat/Composer/ComposerMentionList.swift index 5b0bdbd7aa3..ffb3a3ffc93 100644 --- a/ios/Hapi/Features/Chat/Composer/ComposerMentionList.swift +++ b/ios/Hapi/Features/Chat/Composer/ComposerMentionList.swift @@ -4,45 +4,55 @@ import SwiftUI struct ComposerMentionList: View { let suggestions: [ComposerMentionSuggestion] let surface: Color + var highlightedIndex: Int? = nil let onSelect: (ComposerMentionSuggestion) -> Void @ScaledMetric(relativeTo: .body) private var rowHeight: CGFloat = 58 var body: some View { - ScrollView { - LazyVStack(alignment: .leading, spacing: 0) { - ForEach(suggestions) { suggestion in - Button { onSelect(suggestion) } label: { - HStack(spacing: 10) { - Image(systemName: suggestion.source == .file ? "doc" : "bubble.left.and.bubble.right") - .foregroundStyle(.secondary) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - Text(verbatim: suggestion.label) - .font(.body) - .foregroundStyle(.primary) - .lineLimit(1) - HStack(spacing: 4) { - if case .session(let active) = suggestion.source { - Text("Session") - Text(verbatim: "·") - if active { Text("Active"); Text(verbatim: "·") } + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(Array(suggestions.enumerated()), id: \.element.id) { index, suggestion in + let isHighlighted = highlightedIndex == index + Button { onSelect(suggestion) } label: { + HStack(spacing: 10) { + Image(systemName: suggestion.source == .file ? "doc" : "bubble.left.and.bubble.right") + .foregroundStyle(.secondary) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: suggestion.label) + .font(.body) + .foregroundStyle(.primary) + .lineLimit(1) + HStack(spacing: 4) { + if case .session(let active) = suggestion.source { + Text("Session") + Text(verbatim: "·") + if active { Text("Active"); Text(verbatim: "·") } + } + Text(verbatim: suggestion.detail) } - Text(verbatim: suggestion.detail) + .font(.footnote) + .foregroundStyle(.secondary) + .lineLimit(1) } - .font(.footnote) - .foregroundStyle(.secondary) - .lineLimit(1) + Spacer(minLength: 0) } - Spacer(minLength: 0) + .frame(maxWidth: .infinity, minHeight: rowHeight, alignment: .leading) + .padding(.horizontal, 12) + .background(isHighlighted ? Color.accentColor.opacity(0.14) : Color.clear) + .contentShape(Rectangle()) } - .frame(maxWidth: .infinity, minHeight: rowHeight, alignment: .leading) - .padding(.horizontal, 12) - .contentShape(Rectangle()) + .buttonStyle(.plain) + .id(suggestion.id) + .accessibilityIdentifier("composer.mention.\(suggestion.id)") } - .buttonStyle(.plain) - .accessibilityIdentifier("composer.mention.\(suggestion.id)") } } + .onChange(of: highlightedIndex) { _, next in + guard let next, suggestions.indices.contains(next) else { return } + proxy.scrollTo(suggestions[next].id, anchor: .center) + } } .frame(height: min(CGFloat(suggestions.count), 4) * rowHeight) .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(surface)) diff --git a/ios/Hapi/Features/Chat/Composer/ComposerTextView.swift b/ios/Hapi/Features/Chat/Composer/ComposerTextView.swift index 315b408f348..ec2e9390759 100644 --- a/ios/Hapi/Features/Chat/Composer/ComposerTextView.swift +++ b/ios/Hapi/Features/Chat/Composer/ComposerTextView.swift @@ -11,9 +11,16 @@ struct ComposerTextView: UIViewRepresentable { @Binding var isComposing: Bool let font: UIFont let accessibilityLabel: String - /// Mac: a bare Return submits through this handler (true = consumed); - /// Shift/Option-Return and IME commits still edit the text. + /// Hardware keyboard (Mac Catalyst, iPad, iPhone with external keyboard): + /// bare Return submits or confirms the active suggestion (true = consumed). + /// Shift/Option-Return, software keyboard Return, and IME commits still edit text. var onReturn: (() -> Bool)? = nil + /// Hardware keyboard `↑` (suggestion navigation or empty-draft prompt recall). + var onArrowUp: (() -> Bool)? = nil + /// Hardware keyboard `↓` (suggestion navigation or prompt recall). + var onArrowDown: (() -> Bool)? = nil + /// Hardware keyboard `Escape` (dismisses open `/` or `@` suggestions). + var onEscape: (() -> Bool)? = nil /// Pasted images and copied files become attachments instead of text. var onPasteItems: (([NSItemProvider]) -> Void)? = nil @@ -67,6 +74,9 @@ struct ComposerTextView: UIViewRepresentable { } } view.onReturn = onReturn + view.onArrowUp = onArrowUp + view.onArrowDown = onArrowDown + view.onEscape = onEscape view.onPasteItems = onPasteItems view.wantsFocus = isFocused view.updateFocus() @@ -88,6 +98,9 @@ struct ComposerTextView: UIViewRepresentable { final class NativeTextView: UITextView { var wantsFocus = false var onReturn: (() -> Bool)? + var onArrowUp: (() -> Bool)? + var onArrowDown: (() -> Bool)? + var onEscape: (() -> Bool)? var onPasteItems: (([NSItemProvider]) -> Void)? /// Only image-only clipboards and copied files; anything with text @@ -111,17 +124,27 @@ struct ComposerTextView: UIViewRepresentable { super.paste(sender) } - #if targetEnvironment(macCatalyst) override func pressesBegan(_ presses: Set, with event: UIPressesEvent?) { + // Only physical hardware keyboards deliver UIPress events here; + // on-screen software Return routes through insertText("\n") instead. + // Never intercept while IME composition (markedTextRange) is active. if markedTextRange == nil, let key = presses.first?.key, - key.keyCode == .keyboardReturnOrEnter || key.keyCode == .keypadEnter, - key.modifierFlags.isDisjoint(with: [.shift, .alternate, .command, .control]), - onReturn?() == true { - return + key.modifierFlags.isDisjoint(with: [.shift, .alternate, .command, .control]) { + switch key.keyCode { + case .keyboardReturnOrEnter, .keypadEnter: + if onReturn?() == true { return } + case .keyboardUpArrow: + if onArrowUp?() == true { return } + case .keyboardDownArrow: + if onArrowDown?() == true { return } + case .keyboardEscape: + if onEscape?() == true { return } + default: + break + } } super.pressesBegan(presses, with: event) } - #endif override func didMoveToWindow() { super.didMoveToWindow() diff --git a/ios/Hapi/Features/Chat/Composer/ComposerTrackBarView.swift b/ios/Hapi/Features/Chat/Composer/ComposerTrackBarView.swift new file mode 100644 index 00000000000..60fd3294260 --- /dev/null +++ b/ios/Hapi/Features/Chat/Composer/ComposerTrackBarView.swift @@ -0,0 +1,330 @@ +import HapiClient +import HapiProtocol +import SwiftUI + +/// Single-row horizontal pill rail floating directly above the chat composer: +/// consolidates Todo progress (`2/7 tasks`), spawned peer group members +/// (`2 members · 1 waiting`), and uncommitted Git diff stats (`+42 -18`) +/// without consuming vertical transcript space. Collapses to empty when none apply. +struct ComposerTrackBarView: View { + let todos: [TodoItem] + let groupMembers: [SessionSummary] + let groupStatus: SessionGroupStatus + let diffStats: SessionGitDiffStats? + var primaryPr: PrChipDisplay? = nil + let onOpenTodos: () -> Void + let onOpenGroupMembers: () -> Void + let onOpenDiff: () -> Void + var onOpenPr: ((URL) -> Void)? = nil + + private var hasAnyPill: Bool { + !todos.isEmpty || !groupMembers.isEmpty || (diffStats?.hasChanges == true) || primaryPr != nil + } + + var body: some View { + if hasAnyPill { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + if !todos.isEmpty { + todoPill + } + if !groupMembers.isEmpty { + groupMembersPill + } + if let diffStats, diffStats.hasChanges { + diffPill(diffStats) + } + if let primaryPr { + prPill(primaryPr) + } + } + .padding(.vertical, 2) + } + .hapiReadingColumn() + .padding(.top, 4) + .accessibilityIdentifier("composer.track-bar") + } + } + + private var todoPill: some View { + let completed = todos.filter { $0.status == .completed }.count + let inProgress = todos.contains { $0.status == .inProgress } + let allDone = completed == todos.count + let tint: Color = allDone ? .green : (inProgress ? .accentColor : .secondary) + return Button(action: onOpenTodos) { + HStack(spacing: 5) { + Image(systemName: allDone ? "checkmark.circle.fill" : "checklist") + .foregroundStyle(tint) + Text(String(format: String(localized: "%lld/%lld tasks"), Int64(completed), Int64(todos.count))) + .monospacedDigit() + .foregroundStyle(.primary) + } + .font(.caption.weight(.medium)) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .modifier(TrackPillSurface()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("composer.track.todos") + } + + private var groupMembersPill: some View { + let tint: Color = groupStatus.waiting > 0 + ? .orange + : (groupStatus.working > 0 ? .accentColor : .secondary) + var parts = [ + groupMembers.count == 1 + ? String(localized: "1 member") + : String(format: String(localized: "%lld members"), Int64(groupMembers.count)) + ] + if groupStatus.waiting > 0 { + parts.append(String(format: String(localized: "%lld waiting"), Int64(groupStatus.waiting))) + } + if groupStatus.working > 0 { + parts.append(String(format: String(localized: "%lld working"), Int64(groupStatus.working))) + } + return Button(action: onOpenGroupMembers) { + HStack(spacing: 5) { + Image(systemName: "person.2") + .foregroundStyle(tint) + Text(verbatim: parts.joined(separator: " · ")) + .monospacedDigit() + .foregroundStyle(.primary) + } + .font(.caption.weight(.medium)) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .modifier(TrackPillSurface()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("composer.track.members") + } + + private func diffPill(_ stats: SessionGitDiffStats) -> some View { + Button(action: onOpenDiff) { + HStack(spacing: 4) { + Image(systemName: "plus.forwardslash.minus") + .foregroundStyle(.secondary) + if stats.insertions > 0 || stats.deletions > 0 { + if stats.insertions > 0 { + Text(verbatim: "+\(stats.insertions)") + .foregroundStyle(.green) + } + if stats.deletions > 0 { + Text(verbatim: "-\(stats.deletions)") + .foregroundStyle(.red) + } + } else { + Text( + stats.changedFiles == 1 + ? String(localized: "1 file") + : String(format: String(localized: "%lld files"), Int64(stats.changedFiles)) + ) + .foregroundStyle(.primary) + } + } + .font(.caption.weight(.medium).monospacedDigit()) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .modifier(TrackPillSurface()) + } + .buttonStyle(.plain) + .accessibilityLabel( + String( + format: String(localized: "Uncommitted changes: +%lld -%lld across %lld files"), + Int64(stats.insertions), + Int64(stats.deletions), + Int64(stats.changedFiles) + ) + ) + .accessibilityIdentifier("composer.track.diff") + } + + private func prPill(_ pr: PrChipDisplay) -> some View { + let tint: Color = switch pr.tone { + case .ok: .green + case .pending: .orange + case .needsWork: .red + case .merged: .purple + case .muted, .unknown: .secondary + } + let symbol: String = switch pr.tone { + case .ok: "checkmark.circle.fill" + case .pending: "clock.fill" + case .needsWork: "exclamationmark.circle.fill" + case .merged: "arrow.triangle.merge" + case .muted, .unknown: "arrow.triangle.pull" + } + return Button { + if let url = URL(string: pr.url) { + onOpenPr?(url) + } + } label: { + HStack(spacing: 5) { + Image(systemName: symbol) + .foregroundStyle(tint) + Text(verbatim: "PR #\(pr.number)") + .monospacedDigit() + .foregroundStyle(.primary) + if let label = pr.label, !label.isEmpty { + Text(verbatim: pr.stale ? "\(label) ?" : label) + .foregroundStyle(tint) + } + } + .font(.caption.weight(.medium)) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .modifier(TrackPillSurface()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("composer.track.pr") + } +} + +private struct TrackPillSurface: ViewModifier { + func body(content: Content) -> some View { + let shape = Capsule() + if #available(iOS 26.0, *) { + content + .glassEffect(.regular, in: shape) + } else { + content + .background(.regularMaterial, in: shape) + .overlay(shape.strokeBorder(Color(uiColor: .separator), lineWidth: 0.5)) + } + } +} + +// MARK: - Todo detail sheet + +struct SessionTodosSheet: View { + let todos: [TodoItem] + @Environment(\.dismiss) private var dismiss + + var body: some View { + NavigationStack { + List { + ForEach(Array(todos.enumerated()), id: \.offset) { _, item in + HStack(alignment: .top, spacing: 10) { + statusIcon(for: item.status) + .padding(.top, 2) + VStack(alignment: .leading, spacing: 3) { + let label = (item.status == .inProgress ? item.activeForm : nil) ?? item.content + Text(verbatim: label) + .font(.body) + .strikethrough(item.status == .completed) + .foregroundStyle(item.status == .completed ? .secondary : .primary) + if item.status == .inProgress, let active = item.activeForm, + !active.isEmpty, active != item.content { + Text(verbatim: item.content) + .font(.caption) + .foregroundStyle(.secondary) + } + } + Spacer(minLength: 0) + if item.priority == .high && item.status != .completed { + Text("High") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Color.orange.opacity(0.16), in: Capsule()) + .foregroundStyle(.orange) + } + } + } + } + .navigationTitle("Tasks") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + } + .presentationDetents([.medium, .large]) + } + + @ViewBuilder + private func statusIcon(for status: TodoItem.Status) -> some View { + switch status { + case .completed: + Image(systemName: "checkmark.circle.fill") + .foregroundStyle(.green) + case .inProgress: + Image(systemName: "circle.dotted.circle") + .foregroundStyle(Color.accentColor) + case .pending: + Image(systemName: "circle") + .foregroundStyle(.secondary) + } + } +} + +// MARK: - Group members sheet + +struct SessionGroupMembersSheet: View { + let members: [SessionSummary] + let onSelect: (String) -> Void + @Environment(\.dismiss) private var dismiss + + var body: some View { + NavigationStack { + List { + ForEach(members, id: \.id) { member in + Button { + dismiss() + onSelect(member.id) + } label: { + HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 3) { + Text(verbatim: SessionListModel.sessionTitle(member)) + .font(.body) + .foregroundStyle(.primary) + .lineLimit(1) + HStack(spacing: 6) { + if let flavor = member.metadata?.flavor { + Text(verbatim: flavorLabel(forFlavor: flavor)) + } + statusBadge(for: member) + } + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer(minLength: 0) + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(.tertiary) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + .navigationTitle("Group Members") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + } + .presentationDetents([.medium, .large]) + } + + @ViewBuilder + private func statusBadge(for member: SessionSummary) -> some View { + if member.active && member.pendingRequestsCount > 0 { + Text("Waiting") + .foregroundStyle(.orange) + } else if member.active && (member.thinking || member.backgroundTaskCount > 0) { + Text("Working") + .foregroundStyle(Color.accentColor) + } else if member.active { + Text("Online") + .foregroundStyle(.green) + } else { + Text("Inactive") + .foregroundStyle(.secondary) + } + } +} diff --git a/ios/Hapi/Features/Chat/Composer/ContextWindowMeterView.swift b/ios/Hapi/Features/Chat/Composer/ContextWindowMeterView.swift new file mode 100644 index 00000000000..6a0fbeb0f8e --- /dev/null +++ b/ios/Hapi/Features/Chat/Composer/ContextWindowMeterView.swift @@ -0,0 +1,157 @@ +import HapiClient +import HapiProtocol +import SwiftUI + +/// Compact 18pt circular context-window meter button placed in the composer. +/// Tapping opens `ContextWindowDetailSheet` with token breakdown and CLI quotas. +struct ContextWindowRingButton: View { + let metrics: ContextWindowMetrics + let onTap: () -> Void + + private var ringColor: Color { + switch metrics.severity { + case .normal: .secondary + case .warning: .orange + case .danger: .red + } + } + + private var progress: Double { + metrics.fractionUsed ?? 0.35 + } + + private var accessibilityText: String { + if let pct = metrics.usedPercent, let max = metrics.maxContextSize { + return String( + format: String(localized: "Context %lld%% used, %@ of %@ tokens"), + Int64(pct), + ContextWindowMetrics.formatTokens(metrics.contextSize), + ContextWindowMetrics.formatTokens(max) + ) + } + return String( + format: String(localized: "Context %@ tokens used"), + ContextWindowMetrics.formatTokens(metrics.contextSize) + ) + } + + var body: some View { + Button(action: onTap) { + ZStack { + Circle() + .stroke(ringColor.opacity(0.22), lineWidth: 2.5) + Circle() + .trim(from: 0, to: max(0.05, progress)) + .stroke(ringColor, style: StrokeStyle(lineWidth: 2.5, lineCap: .round)) + .rotationEffect(.degrees(-90)) + } + .frame(width: 18, height: 18) + .frame(minWidth: 44, minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(accessibilityText) + .accessibilityIdentifier("composer.context-meter") + } +} + +/// Sheet presenting the active session's context window breakdown alongside the +/// hub's live CLI account quotas (with manual refresh). +struct ContextWindowDetailSheet: View { + let metrics: ContextWindowMetrics + let api: APIClient + var preferredMachineId: String? = nil + @Environment(\.dismiss) private var dismiss + + private var progressTint: Color { + switch metrics.severity { + case .normal: .accentColor + case .warning: .orange + case .danger: .red + } + } + + var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + contextCard + UsageQuotasSection(api: api, preferredMachineId: preferredMachineId) + } + .padding(16) + } + .background(Color(uiColor: .systemGroupedBackground)) + .navigationTitle("Context & Quotas") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + } + .presentationDetents([.medium, .large]) + } + + private var contextCard: some View { + DashboardCard { + HStack(alignment: .firstTextBaseline) { + Text("Context window") + .font(.subheadline.weight(.semibold)) + Spacer() + if let usedPercent = metrics.usedPercent { + Text(verbatim: "\(usedPercent)%") + .font(.subheadline.weight(.semibold).monospacedDigit()) + .foregroundStyle(progressTint) + } + } + + if let fraction = metrics.fractionUsed { + ProgressView(value: fraction, total: 1) + .tint(progressTint) + .accessibilityHidden(true) + } + + VStack(alignment: .leading, spacing: 8) { + if let maxContext = metrics.maxContextSize { + metricRow( + label: "Used", + value: "\(ContextWindowMetrics.formatTokens(metrics.contextSize)) / \(ContextWindowMetrics.formatTokens(maxContext))" + ) + if let remaining = metrics.remainingPercent { + metricRow(label: "Remaining", value: "\(remaining)%") + } + } else { + metricRow(label: "Used", value: ContextWindowMetrics.formatTokens(metrics.contextSize)) + } + if metrics.cacheRead > 0 { + metricRow(label: "Cache read", value: ContextWindowMetrics.formatTokens(metrics.cacheRead)) + } + if metrics.cacheCreation > 0 { + metricRow(label: "Cache write", value: ContextWindowMetrics.formatTokens(metrics.cacheCreation)) + } + if metrics.inputTokens > 0 || metrics.outputTokens > 0 { + metricRow( + label: "Last turn", + value: "↑ \(ContextWindowMetrics.formatTokens(metrics.inputTokens)) · ↓ \(ContextWindowMetrics.formatTokens(metrics.outputTokens))" + ) + } + if let model = metrics.model, !model.isEmpty { + metricRow(label: "Model", value: model) + } + } + .font(.subheadline) + } + } + + private func metricRow(label: LocalizedStringKey, value: String) -> some View { + HStack(alignment: .firstTextBaseline) { + Text(label) + .foregroundStyle(.secondary) + Spacer(minLength: 12) + Text(verbatim: value) + .monospacedDigit() + .lineLimit(1) + .truncationMode(.middle) + } + } +} diff --git a/ios/Hapi/Features/Chat/Composer/HardwareKeyboardObserver.swift b/ios/Hapi/Features/Chat/Composer/HardwareKeyboardObserver.swift new file mode 100644 index 00000000000..ad61df79f97 --- /dev/null +++ b/ios/Hapi/Features/Chat/Composer/HardwareKeyboardObserver.swift @@ -0,0 +1,49 @@ +import Foundation +#if canImport(GameController) +import GameController +#endif +import Observation + +/// Tracks whether a physical hardware keyboard is currently connected via +/// `GCKeyboard.coalesced` (always `true` on Mac Catalyst). +@MainActor @Observable +final class HardwareKeyboardObserver { + private(set) var isConnected: Bool + + #if canImport(GameController) && !targetEnvironment(macCatalyst) + @ObservationIgnored private var connectToken: (any NSObjectProtocol)? + @ObservationIgnored private var disconnectToken: (any NSObjectProtocol)? + #endif + + init() { + #if targetEnvironment(macCatalyst) + self.isConnected = true + #elseif canImport(GameController) + self.isConnected = GCKeyboard.coalesced != nil + let center = NotificationCenter.default + connectToken = center.addObserver( + forName: .GCKeyboardDidConnect, + object: nil, + queue: .main + ) { [weak self] _ in + Task { @MainActor in self?.isConnected = true } + } + disconnectToken = center.addObserver( + forName: .GCKeyboardDidDisconnect, + object: nil, + queue: .main + ) { [weak self] _ in + Task { @MainActor in self?.isConnected = GCKeyboard.coalesced != nil } + } + #else + self.isConnected = false + #endif + } + + deinit { + #if canImport(GameController) && !targetEnvironment(macCatalyst) + if let connectToken { NotificationCenter.default.removeObserver(connectToken) } + if let disconnectToken { NotificationCenter.default.removeObserver(disconnectToken) } + #endif + } +} diff --git a/ios/Hapi/Features/Chat/Composer/SessionSkillsSheet.swift b/ios/Hapi/Features/Chat/Composer/SessionSkillsSheet.swift new file mode 100644 index 00000000000..7b642b07954 --- /dev/null +++ b/ios/Hapi/Features/Chat/Composer/SessionSkillsSheet.swift @@ -0,0 +1,66 @@ +import HapiProtocol +import SwiftUI + +/// Searchable skill selector sheet invoked from the chat composer toolbar. +/// Selecting a skill inserts `$skillName ` into the composer, matching Web's +/// skill invocation syntax (`HappyComposer.tsx`). +struct SessionSkillsSheet: View { + let skills: [SkillSummary] + let onSelect: (SkillSummary) -> Void + + @Environment(\.dismiss) private var dismiss + @State private var query = "" + + private var filtered: [SkillSummary] { + let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return skills } + return skills.filter { skill in + skill.name.localizedCaseInsensitiveContains(trimmed) + || (skill.description?.localizedCaseInsensitiveContains(trimmed) == true) + } + } + + var body: some View { + NavigationStack { + List { + if filtered.isEmpty { + ContentUnavailableView.search(text: query) + } else { + ForEach(filtered, id: \.name) { skill in + Button { + HapiHaptics.light() + onSelect(skill) + dismiss() + } label: { + VStack(alignment: .leading, spacing: 3) { + Text(verbatim: "$\(skill.name)") + .font(.subheadline.monospaced().weight(.semibold)) + .foregroundStyle(.primary) + if let description = skill.description, !description.isEmpty { + Text(description) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(3) + } + } + .padding(.vertical, 2) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + } + .listStyle(.plain) + .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Filter skills…")) + .navigationTitle("Skills") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + } + .presentationDetents([.medium, .large]) + } +} diff --git a/ios/Hapi/Features/Chat/HapiHaptics.swift b/ios/Hapi/Features/Chat/HapiHaptics.swift new file mode 100644 index 00000000000..0ba10382332 --- /dev/null +++ b/ios/Hapi/Features/Chat/HapiHaptics.swift @@ -0,0 +1,31 @@ +#if canImport(UIKit) +import UIKit +#endif + +/// Lightweight tactile feedback helper for primary chat & approval gestures. +@MainActor +enum HapiHaptics { + static func light() { + #if canImport(UIKit) && !targetEnvironment(macCatalyst) + UIImpactFeedbackGenerator(style: .light).impactOccurred() + #endif + } + + static func medium() { + #if canImport(UIKit) && !targetEnvironment(macCatalyst) + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + #endif + } + + static func success() { + #if canImport(UIKit) && !targetEnvironment(macCatalyst) + UINotificationFeedbackGenerator().notificationOccurred(.success) + #endif + } + + static func warning() { + #if canImport(UIKit) && !targetEnvironment(macCatalyst) + UINotificationFeedbackGenerator().notificationOccurred(.warning) + #endif + } +} diff --git a/ios/Hapi/Features/Chat/SearchableModelPickerSheet.swift b/ios/Hapi/Features/Chat/SearchableModelPickerSheet.swift new file mode 100644 index 00000000000..3e9a9ad7907 --- /dev/null +++ b/ios/Hapi/Features/Chat/SearchableModelPickerSheet.swift @@ -0,0 +1,95 @@ +import SwiftUI + +/// Single selectable option inside `SearchableModelPickerSheet`. +struct ModelPickerOption: Identifiable, Equatable { + let id: String + /// `nil` represents the agent/hub default choice. + let value: String? + let label: String + /// Optional raw identifier shown beneath `label` when distinct. + let detail: String? + + init(value: String?, label: String, detail: String? = nil) { + self.id = value ?? "__default__" + self.value = value + self.label = label + if let detail, !detail.isEmpty, detail != label { + self.detail = detail + } else if let value, !value.isEmpty, value != label { + self.detail = value + } else { + self.detail = nil + } + } +} + +/// Searchable modal picker for large model catalogs (Claude, Codex, OpenCode, Pi, etc.), +/// shared between `SessionConfigView` and `NewSessionView`. +struct SearchableModelPickerSheet: View { + let title: LocalizedStringKey + let options: [ModelPickerOption] + let selectedValue: String? + let onSelect: (String?) -> Void + + @Environment(\.dismiss) private var dismiss + @State private var query = "" + + private var filtered: [ModelPickerOption] { + let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return options } + return options.filter { option in + option.label.localizedCaseInsensitiveContains(trimmed) + || (option.detail?.localizedCaseInsensitiveContains(trimmed) == true) + || (option.value?.localizedCaseInsensitiveContains(trimmed) == true) + } + } + + var body: some View { + NavigationStack { + List { + if filtered.isEmpty { + ContentUnavailableView.search(text: query) + } else { + ForEach(filtered) { option in + Button { + onSelect(option.value) + dismiss() + } label: { + HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: option.label) + .font(.body) + .foregroundStyle(.primary) + if let detail = option.detail { + Text(verbatim: detail) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + } + } + Spacer(minLength: 8) + if option.value == selectedValue { + Image(systemName: "checkmark") + .font(.body.weight(.semibold)) + .foregroundStyle(.tint) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("session-config-model-\(option.value ?? "default")") + } + } + } + .listStyle(.plain) + .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Search models…")) + .navigationTitle(title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + } + } + .presentationDetents([.medium, .large]) + } +} diff --git a/ios/Hapi/Features/Chat/SessionConfigModel.swift b/ios/Hapi/Features/Chat/SessionConfigModel.swift index ab2bcdaf6a5..bd7f108bb82 100644 --- a/ios/Hapi/Features/Chat/SessionConfigModel.swift +++ b/ios/Hapi/Features/Chat/SessionConfigModel.swift @@ -87,4 +87,36 @@ final class SessionConfigModel { func loadModels() { interactor.loadModelOptions() } + + /// Sequentially applies a local `AgentProfile`'s model, effort, and permission + /// mode when each field differs and is supported by the active session. + func applyProfile(_ profile: AgentProfile) { + Task { @MainActor in + if let modelValue = profile.model, + config.modelOptions?.contains(where: { $0.value == modelValue }) == true, + modelValue != currentModel { + await waitUntilIdle() + selectModel(modelValue) + } + if let effortValue = profile.effort, + canSelectEffort(effortValue), + effortValue != currentEffort { + await waitUntilIdle() + selectEffort(effortValue) + } + if let mode = profile.permissionMode, + config.permissionModes.contains(where: { $0.mode == mode }), + mode != permission { + await waitUntilIdle() + selectPermission(mode) + } + } + } + + private func waitUntilIdle() async { + for _ in 0..<40 { + if !isApplying { return } + try? await Task.sleep(for: .milliseconds(50)) + } + } } diff --git a/ios/Hapi/Features/Chat/SessionConfigView.swift b/ios/Hapi/Features/Chat/SessionConfigView.swift index 34391ab8915..3bb2ab6229d 100644 --- a/ios/Hapi/Features/Chat/SessionConfigView.swift +++ b/ios/Hapi/Features/Chat/SessionConfigView.swift @@ -45,6 +45,10 @@ struct SessionConfigButton: View { struct SessionConfigView: View { @State private var model: SessionConfigModel @State private var detent: PresentationDetent = .medium + @State private var modelPickerOpen = false + @State private var saveProfileAlertOpen = false + @State private var newProfileName = "" + private let profileStore: AgentProfileStore = .shared let notice: String? @Environment(\.dismiss) private var dismiss @@ -64,7 +68,10 @@ struct SessionConfigView: View { settingsForm .navigationTitle("Session Settings") .navigationBarTitleDisplayMode(.inline) - .toolbar { doneButton } + .toolbar { + profilesButton + doneButton + } } .safeAreaInset(edge: .bottom, spacing: 0) { feedback } .presentationDetents( @@ -75,6 +82,37 @@ struct SessionConfigView: View { ) ) .onAppear { model.loadModels() } + .sheet(isPresented: $modelPickerOpen) { + let options = (model.config.modelOptions ?? []).map { + ModelPickerOption(value: $0.value, label: $0.label) + } + SearchableModelPickerSheet( + title: "Model", + options: options, + selectedValue: model.currentModel + ) { chosen in + model.selectModel(chosen) + } + } + .alert("Save Profile", isPresented: $saveProfileAlertOpen) { + TextField("Profile name", text: $newProfileName) + Button("Cancel", role: .cancel) {} + Button("Save") { + if let flavor = model.config.flavor { + profileStore.save(AgentProfile( + name: newProfileName, + flavor: flavor, + model: model.currentModel, + effort: model.currentEffort, + permissionMode: model.config.permissionModes.isEmpty ? nil : model.permission + )) + } + newProfileName = "" + } + .disabled(newProfileName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } message: { + Text("Save the current model, effort, and permission mode for quick reuse.") + } } private var settingsForm: some View { @@ -181,23 +219,22 @@ struct SessionConfigView: View { } private var modelRow: some View { - VStack(alignment: .leading, spacing: 8) { - SessionConfigMenu(title: "Model", value: Text(verbatim: model.modelLabel)) { - Picker("Model", selection: Binding( - get: { model.currentModel }, set: { model.selectModel($0) } - )) { - if let current = model.unlistedModelOption { - Text(verbatim: current.label).tag(current.value).disabled(true) - } - ForEach(model.config.modelOptions ?? [], id: \.value) { option in - Text(verbatim: option.label) - .tag(option.value) - .accessibilityIdentifier("session-config-model-\(option.value ?? "default")") - } + let modelDisabled = model.config.modelOptionsLoading || model.modelLoadFailed || model.config.modelOptions?.isEmpty != false + return VStack(alignment: .leading, spacing: 8) { + Button { + modelPickerOpen = true + } label: { + HStack(spacing: 8) { + SessionConfigSummaryRow(title: "Model", value: Text(verbatim: model.modelLabel)) + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(.tertiary) + .accessibilityHidden(true) } - .pickerStyle(.inline) + .contentShape(Rectangle()) } - .disabled(model.config.modelOptionsLoading || model.modelLoadFailed || model.config.modelOptions?.isEmpty != false) + .buttonStyle(.plain) + .disabled(modelDisabled) .accessibilityIdentifier("session-config-model") if model.config.modelOptionsLoading { @@ -218,6 +255,54 @@ struct SessionConfigView: View { } } + @ToolbarContentBuilder + private var profilesButton: some ToolbarContent { + if let flavor = model.config.flavor, model.hasSettings { + let matching = profileStore.profiles(forFlavor: flavor) + ToolbarItem(placement: .topBarLeading) { + Menu { + if !matching.isEmpty { + Section("Profiles") { + ForEach(matching) { profile in + Button { + HapiHaptics.light() + model.applyProfile(profile) + } label: { + Text(verbatim: profile.name) + if !profile.summaryText.isEmpty { + Text(verbatim: profile.summaryText) + } + } + } + } + Menu { + ForEach(matching) { profile in + Button(role: .destructive) { + profileStore.delete(id: profile.id) + } label: { + Label(profile.name, systemImage: "trash") + } + } + } label: { + Label("Delete Profile", systemImage: "trash") + } + Divider() + } + Button { + newProfileName = "" + saveProfileAlertOpen = true + } label: { + Label("Save Current as Profile…", systemImage: "plus.circle") + } + } label: { + Label("Profiles", systemImage: "bookmark") + } + .disabled(model.isApplying) + .accessibilityIdentifier("session-config-profiles") + } + } + } + @ToolbarContentBuilder private var doneButton: some ToolbarContent { ToolbarItem(placement: .confirmationAction) { diff --git a/ios/Hapi/Features/Files/DiffReviewViews.swift b/ios/Hapi/Features/Files/DiffReviewViews.swift new file mode 100644 index 00000000000..2ec482cac53 --- /dev/null +++ b/ios/Hapi/Features/Files/DiffReviewViews.swift @@ -0,0 +1,339 @@ +import HapiClient +import HapiUI +import SwiftUI + +// MARK: - Inline Diff Review Comment Sheet + +/// Modal sheet to add, edit, or remove an inline code review comment on a diff line. +struct DiffReviewCommentSheet: View { + let selection: DiffLineSelection + let path: String + let staged: Bool + let existing: DiffReviewComment? + let onSave: (String) -> Void + let onDelete: (() -> Void)? + + @Environment(\.dismiss) private var dismiss + @State private var text: String + @FocusState private var editorFocused: Bool + + init( + selection: DiffLineSelection, + path: String, + staged: Bool, + existing: DiffReviewComment?, + onSave: @escaping (String) -> Void, + onDelete: (() -> Void)? + ) { + self.selection = selection + self.path = path + self.staged = staged + self.existing = existing + self.onSave = onSave + self.onDelete = onDelete + _text = State(initialValue: existing?.comment ?? "") + } + + private var trimmed: String { + text.trimmingCharacters(in: .whitespacesAndNewlines) + } + + var body: some View { + NavigationStack { + VStack(alignment: .leading, spacing: 12) { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + Text(path) + .font(.caption.monospaced().weight(.medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 4) + Text("Line \(selection.lineNumber, specifier: "%lld")") + .font(.caption.monospaced().weight(.semibold)) + .foregroundStyle(.tint) + } + ScrollView(.horizontal, showsIndicators: false) { + Text(selection.snippet) + .font(.caption.monospaced()) + .foregroundStyle(.primary) + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + } + .background(.fill.tertiary, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + } + + VStack(alignment: .leading, spacing: 6) { + Text("Review comment") + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + TextEditor(text: $text) + .focused($editorFocused) + .font(.body) + .frame(minHeight: 110) + .padding(6) + .background(.fill.quaternary, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .stroke(.separator, lineWidth: 0.5) + ) + } + + if existing != nil, let onDelete { + Button(role: .destructive) { + onDelete() + dismiss() + } label: { + Label("Delete Comment", systemImage: "trash") + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + } + + Spacer(minLength: 0) + } + .padding(16) + .navigationTitle(existing == nil ? "Add Comment" : "Edit Comment") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + onSave(trimmed) + dismiss() + } + .fontWeight(.semibold) + .disabled(trimmed.isEmpty) + } + } + .onAppear { + editorFocused = true + } + } + .presentationDetents([.medium, .large]) + } +} + +// MARK: - Floating Review Drafts Bar & Summary Sheet + +/// Sticky bottom bar shown across Files and File Viewer whenever inline diff +/// review comments are queued for the session. +struct DiffReviewBar: View { + let comments: [DiffReviewComment] + let onSend: () -> Void + let onDelete: (String) -> Void + let onClearAll: () -> Void + + @State private var summaryOpen = false + + var body: some View { + HStack(spacing: 10) { + Button { + summaryOpen = true + } label: { + HStack(spacing: 6) { + Image(systemName: "text.bubble.fill") + .foregroundStyle(.tint) + Text("\(comments.count, specifier: "%lld") review comments") + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) + } + .padding(.vertical, 6) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + Spacer(minLength: 8) + + Button { + onSend() + } label: { + Label("Send", systemImage: "paperplane.fill") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.white) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(.tint, in: Capsule()) + } + .buttonStyle(.plain) + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .background(.regularMaterial) + .overlay(alignment: .top) { Divider() } + .sheet(isPresented: $summaryOpen) { + DiffReviewSummarySheet( + comments: comments, + onDelete: onDelete, + onClearAll: onClearAll, + onSend: { + summaryOpen = false + onSend() + } + ) + } + } +} + +private struct DiffReviewSummarySheet: View { + let comments: [DiffReviewComment] + let onDelete: (String) -> Void + let onClearAll: () -> Void + let onSend: () -> Void + + @Environment(\.dismiss) private var dismiss + + var body: some View { + NavigationStack { + List { + ForEach(comments) { item in + VStack(alignment: .leading, spacing: 6) { + HStack { + Text(item.path) + .font(.caption.monospaced().weight(.semibold)) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + Spacer() + Text("Line \(item.lineNumber, specifier: "%lld")") + .font(.caption.monospaced()) + .foregroundStyle(.tint) + } + Text(item.comment) + .font(.subheadline) + .fixedSize(horizontal: false, vertical: true) + } + .padding(.vertical, 2) + .swipeActions(edge: .trailing) { + Button("Delete", role: .destructive) { + onDelete(item.id) + } + } + } + } + .navigationTitle("Review Comments") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Clear All", role: .destructive) { + onClearAll() + dismiss() + } + .disabled(comments.isEmpty) + } + ToolbarItem(placement: .confirmationAction) { + Button("Send") { + onSend() + } + .fontWeight(.semibold) + .disabled(comments.isEmpty) + } + } + } + .presentationDetents([.medium, .large]) + } +} + +// MARK: - Line-Numbered Focusable Code File View + +/// Line-numbered, syntax-highlighted code viewer used when a citation specifies +/// `focusLine`, enabling `ScrollViewReader` to scroll straight to and highlight +/// the target line. +struct FocusedCodeFileView: View { + let language: String? + let code: String + let focusLine: Int + + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography + @Environment(\.hapiSyntaxHighlighter) private var highlighter + @State private var highlightedLines: [AttributedString]? + + private var rawLines: [String] { + code.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + } + + private var gutterDigits: Int { + max(2, String(max(1, rawLines.count)).count) + } + + private var highlightID: String { + "\(language ?? "text")|\(theme.isDark ? "d" : "l")|\(code.count)|\(code.hashValue)" + } + + var body: some View { + let lines = rawLines + let digits = gutterDigits + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(Array(lines.enumerated()), id: \.offset) { index, rawLine in + let lineNumber = index + 1 + let isFocused = lineNumber == focusLine + HStack(alignment: .firstTextBaseline, spacing: 10) { + Text(paddedNumber(lineNumber, width: digits)) + .font(typography.captionMonoFont) + .foregroundStyle(isFocused ? theme.link : theme.textHint) + .fixedSize() + Group { + if let highlightedLines, index < highlightedLines.count { + Text(highlightedLines[index]) + } else { + Text(rawLine) + .foregroundStyle(theme.textPrimary) + } + } + .font(typography.codeFont) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + Spacer(minLength: 0) + } + .padding(.horizontal, 12) + .padding(.vertical, max(2, typography.codeLineSpacing / 2)) + .background(isFocused ? theme.link.opacity(0.16) : Color.clear) + .overlay(alignment: .leading) { + if isFocused { + Rectangle() + .fill(theme.link) + .frame(width: 3) + } + } + .id(lineNumber) + } + } + .padding(.vertical, 8) + .background(theme.codeBackground) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .task(id: highlightID) { + guard let full = await highlighter.highlightAsync(code, language: language, dark: theme.isDark) else { + highlightedLines = nil + return + } + let split = Self.splitAttributedLines(full) + highlightedLines = split.count == rawLines.count ? split : nil + } + } + + private func paddedNumber(_ number: Int, width: Int) -> String { + let digits = String(number) + if digits.count >= width { return digits } + return String(repeating: " ", count: width - digits.count) + digits + } + + private static func splitAttributedLines(_ attributed: AttributedString) -> [AttributedString] { + var result: [AttributedString] = [] + var lineStart = attributed.startIndex + var cursor = attributed.startIndex + while cursor < attributed.endIndex { + if attributed.characters[cursor] == "\n" { + result.append(AttributedString(attributed[lineStart.. Void)? @State private var model: FileViewerModel + @State private var selectedDiffLine: DiffLineSelection? + @State private var scrollToFocusTrigger = 0 + @Environment(\.dismiss) private var dismiss - init(session: HubSession, route: FileViewerRoute) { + init( + session: HubSession, + route: FileViewerRoute, + onSendReviewPrompt: ((String) -> Void)? = nil + ) { + self.session = session + self.sessionId = route.sessionId + self.onSendReviewPrompt = onSendReviewPrompt _model = State(initialValue: FileViewerModel( sessionId: route.sessionId, path: route.path, @@ -30,20 +39,64 @@ struct FileViewerView: View { )) } + private var sessionReviewComments: [DiffReviewComment] { + session.diffReview.comments(forSession: sessionId) + } + + private var fileCommentedLineKeys: Set { + session.diffReview.commentedLineKeys( + forSession: sessionId, + path: model.path, + staged: model.staged + ) + } + var body: some View { - ScrollView { - VStack(alignment: .leading, spacing: 8) { - modeToggleRow - switch model.mode { - case .diff: - diffContent - case .file: - fileContent + ScrollViewReader { proxy in + ScrollView { + VStack(alignment: .leading, spacing: 8) { + modeToggleRow + switch model.mode { + case .diff: + diffContent + case .file: + fileContent + } } + .padding(.horizontal, 12) + .padding(.vertical, 8) + .frame(maxWidth: .infinity, alignment: .leading) + } + .onChange(of: isTextReadyForFocus) { _, ready in + if ready, let line = model.focusLine { + DispatchQueue.main.async { + withAnimation(.easeInOut(duration: 0.2)) { + proxy.scrollTo(line, anchor: .center) + } + } + } + } + .onChange(of: scrollToFocusTrigger) { + if let line = model.focusLine { + withAnimation(.easeInOut(duration: 0.2)) { + proxy.scrollTo(line, anchor: .center) + } + } + } + } + .safeAreaInset(edge: .bottom, spacing: 0) { + if !sessionReviewComments.isEmpty { + DiffReviewBar( + comments: sessionReviewComments, + onSend: sendReviewComments, + onDelete: { id in + session.diffReview.delete(id: id, sessionId: sessionId) + }, + onClearAll: { + session.diffReview.clear(sessionId: sessionId) + } + ) } - .padding(.horizontal, 12) - .padding(.vertical, 8) - .frame(maxWidth: .infinity, alignment: .leading) } .navigationBarTitleDisplayMode(.inline) .toolbar { @@ -63,11 +116,78 @@ struct FileViewerView: View { actionsMenu } } + .sheet(item: $selectedDiffLine) { selection in + let kind = reviewLineKind(for: selection.line.kind) + let existing = session.diffReview.comment( + forSession: sessionId, + path: model.path, + staged: model.staged, + lineNumber: selection.lineNumber, + lineKind: kind + ) + DiffReviewCommentSheet( + selection: selection, + path: model.path, + staged: model.staged, + existing: existing, + onSave: { commentText in + session.diffReview.upsert( + DiffReviewComment( + id: existing?.id ?? UUID().uuidString, + path: model.path, + staged: model.staged, + lineNumber: selection.lineNumber, + lineKind: kind, + hunkHeader: selection.hunkHeader, + snippet: selection.snippet, + comment: commentText + ), + sessionId: sessionId + ) + }, + onDelete: existing.map { existingComment in + { + session.diffReview.delete(id: existingComment.id, sessionId: sessionId) + } + } + ) + } .onAppear { model.start() } } + private var isTextReadyForFocus: Bool { + guard model.mode == .file, model.focusLine != nil, !model.markdownPreview else { return false } + if case .text = model.content { return true } + return false + } + + private func reviewLineKind(for kind: DiffLine.Kind) -> DiffReviewLineKind { + switch kind { + case .addition: .addition + case .deletion: .deletion + case .context, .noNewlineMarker: .context + } + } + + private func sendReviewComments() { + let comments = sessionReviewComments + let prompt = DiffReviewStore.formatReviewPrompt(comments) + guard !prompt.isEmpty else { return } + session.diffReview.clear(sessionId: sessionId) + if let onSendReviewPrompt { + onSendReviewPrompt(prompt) + } else { + let api = session.api + let sessionId = self.sessionId + Task { + _ = try? await api.sendMessage(sessionId: sessionId, text: prompt) + } + dismiss() + } + } + // MARK: - Chrome private var actionsMenu: some View { @@ -96,7 +216,7 @@ struct FileViewerView: View { } /// Diff ⇄ File chips, the staged side toggle, the markdown - /// Source/Preview toggle, and the citation line hint — only the + /// Source/Preview toggle, and the tappable citation line chip — only the /// applicable controls show (Android `ModeToggleRow` parity). @ViewBuilder private var modeToggleRow: some View { @@ -133,10 +253,19 @@ struct FileViewerView: View { } } if let line = model.focusLine { - Text("Line \(line, specifier: "%lld")") - .font(.caption2) - .foregroundStyle(.secondary) - .padding(.leading, 4) + Button { + if model.mode != .file { model.setMode(.file) } + if model.markdownPreview { model.setMarkdownPreview(false) } + scrollToFocusTrigger += 1 + } label: { + Text("Line \(line, specifier: "%lld")") + .font(.caption2.weight(.medium)) + .foregroundStyle(.tint) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(.tint.opacity(0.12), in: Capsule()) + } + .buttonStyle(.plain) } Spacer(minLength: 0) } @@ -165,7 +294,19 @@ struct FileViewerView: View { case .failed(let message): HintBlock(text: LocalizedNoticeMapper.map(message)) case .ready(let unifiedDiff): - ParsedDiffView(unifiedDiff: unifiedDiff) + VStack(alignment: .leading, spacing: 6) { + Text("Tap any line to add a review comment") + .font(.caption2) + .foregroundStyle(.secondary) + .padding(.horizontal, 4) + ParsedDiffView( + unifiedDiff: unifiedDiff, + commentedLineKeys: fileCommentedLineKeys, + onSelectLine: { selection in + selectedDiffLine = selection + } + ) + } } } @@ -196,6 +337,9 @@ struct FileViewerView: View { MarkdownView(markdown: text) // The outer viewer already supplies 12pt on each side. .hapiReadingColumn(horizontalInset: 4) + } else if let focusLine = model.focusLine { + FocusedCodeFileView(language: language, code: text, focusLine: focusLine) + .frame(maxWidth: .infinity, alignment: .leading) } else { CodeBlockView(language: language, code: text) .frame(maxWidth: .infinity, alignment: .leading) @@ -208,12 +352,18 @@ struct FileViewerView: View { /// `DiffTextView`. private struct ParsedDiffView: View { let unifiedDiff: String + let commentedLineKeys: Set + let onSelectLine: (DiffLineSelection) -> Void @State private var files: [DiffFile]? var body: some View { Group { if let files { - DiffTextView(files: files) + DiffTextView( + files: files, + commentedLineKeys: commentedLineKeys, + onSelectLine: onSelectLine + ) } else { LoadingBlock() } diff --git a/ios/Hapi/Features/Files/FilesView.swift b/ios/Hapi/Features/Files/FilesView.swift index b65e7ee9ae7..a5f2180ead6 100644 --- a/ios/Hapi/Features/Files/FilesView.swift +++ b/ios/Hapi/Features/Files/FilesView.swift @@ -13,16 +13,27 @@ import SwiftUI struct FilesView: View { private let session: HubSession private let sessionId: String + private let onSendReviewPrompt: ((String) -> Void)? @State private var model: FilesModel @State private var tab: FilesTab = .changes @State private var viewerRoute: FileViewerRoute? + @Environment(\.dismiss) private var dismiss - init(session: HubSession, sessionId: String) { + init( + session: HubSession, + sessionId: String, + onSendReviewPrompt: ((String) -> Void)? = nil + ) { self.session = session self.sessionId = sessionId + self.onSendReviewPrompt = onSendReviewPrompt _model = State(initialValue: FilesModel(sessionId: sessionId, requester: session.api)) } + private var sessionReviewComments: [DiffReviewComment] { + session.diffReview.comments(forSession: sessionId) + } + private enum FilesTab: String, CaseIterable, Identifiable { case changes = "Changes" case browse = "Browse" @@ -90,11 +101,41 @@ struct FilesView: View { .accessibilityLabel("Refresh") } } + .safeAreaInset(edge: .bottom, spacing: 0) { + if !sessionReviewComments.isEmpty { + DiffReviewBar( + comments: sessionReviewComments, + onSend: { + let prompt = DiffReviewStore.formatReviewPrompt(sessionReviewComments) + guard !prompt.isEmpty else { return } + session.diffReview.clear(sessionId: sessionId) + if let onSendReviewPrompt { + onSendReviewPrompt(prompt) + } else { + let api = session.api + let id = sessionId + Task { _ = try? await api.sendMessage(sessionId: id, text: prompt) } + dismiss() + } + }, + onDelete: { id in + session.diffReview.delete(id: id, sessionId: sessionId) + }, + onClearAll: { + session.diffReview.clear(sessionId: sessionId) + } + ) + } + } .navigationDestination(item: $viewerRoute) { route in // A replaced route value must rebuild the screen's @State model // (HomeView's chat-push precedent). - FileViewerView(session: session, route: route) - .id(route) + FileViewerView( + session: session, + route: route, + onSendReviewPrompt: onSendReviewPrompt + ) + .id(route) } .onAppear { model.start() @@ -390,15 +431,44 @@ private struct SearchTabView: View { private struct ErrorBanner: View { let message: String + @State private var isExpanded = false var body: some View { - Text(message) - .font(.caption) - .foregroundStyle(.red) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 16) - .padding(.vertical, 8) - .background(.red.opacity(0.12)) + let concise = ConciseErrorSummary.concise(message, maxLength: 140) + let expandable = ConciseErrorSummary.hasExtraDetail(raw: message, concise: concise) + Group { + if expandable { + Button { + withAnimation(.easeInOut(duration: 0.18)) { + isExpanded.toggle() + } + } label: { + HStack(alignment: .top, spacing: 8) { + Text(verbatim: isExpanded ? message : concise) + .font(.caption) + .foregroundStyle(.red) + .lineLimit(isExpanded ? nil : 2) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + Image(systemName: isExpanded ? "chevron.up" : "chevron.down") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.red.opacity(0.8)) + .padding(.top, 2) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } else { + Text(verbatim: concise.isEmpty ? message : concise) + .font(.caption) + .foregroundStyle(.red) + .lineLimit(2) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(.red.opacity(0.12)) } } diff --git a/ios/Hapi/Features/Home/AppCommands.swift b/ios/Hapi/Features/Home/AppCommands.swift index f0ac6c17c8a..bffe944955b 100644 --- a/ios/Hapi/Features/Home/AppCommands.swift +++ b/ios/Hapi/Features/Home/AppCommands.swift @@ -15,6 +15,7 @@ struct HomeCommandActions { struct ChatCommandActions { var openSessionSettings: () -> Void var openFiles: () -> Void + var openTerminal: (() -> Void)? var rename: () -> Void var export: (() -> Void)? /// Nil unless the agent is mid-turn. @@ -82,6 +83,9 @@ struct HapiCommands: Commands { Button("Session Files") { chat?.openFiles() } .keyboardShortcut("o", modifiers: [.command, .shift]) .disabled(chat == nil) + Button("Terminal") { chat?.openTerminal?() } + .keyboardShortcut("t", modifiers: [.command, .shift]) + .disabled(chat?.openTerminal == nil) Divider() Button("Rename…") { chat?.rename() } .disabled(chat == nil) diff --git a/ios/Hapi/Features/Home/HomeView.swift b/ios/Hapi/Features/Home/HomeView.swift index fb6a57c11e8..48821251ec1 100644 --- a/ios/Hapi/Features/Home/HomeView.swift +++ b/ios/Hapi/Features/Home/HomeView.swift @@ -16,6 +16,7 @@ struct HomeView: View { @Environment(\.horizontalSizeClass) private var horizontalSizeClass @State private var listModel: SessionListModel @State private var showNewSession = false + @State private var showImportSession = false @State private var showSettings = false @State private var path: [String] = [] @State private var tabletNavigation = SessionNavigationState() @@ -93,13 +94,26 @@ struct HomeView: View { .macSheetSizing() } .sheet(isPresented: $showNewSession) { - NewSessionView(session: session) { sessionId in + NewSessionView( + session: session, + onImportLocalSession: { + showNewSession = false + showImportSession = true + } + ) { sessionId in // Navigate-replace: drop the sheet, push the fresh chat. showNewSession = false openSession(sessionId) } .macSheetSizing() } + .sheet(isPresented: $showImportSession) { + ImportLocalSessionSheet(session: session) { sessionId in + showImportSession = false + openSession(sessionId) + } + .macSheetSizing() + } .sheet(isPresented: $showSettings) { SettingsView(session: session) .macSheetSizing() @@ -116,9 +130,9 @@ struct HomeView: View { tabletNavigation.columnVisibility = tabletNavigation.columnVisibility == .detailOnly ? .all : .detailOnly } - /// Steps through the list as shown (filters and search applied). + /// Steps through the list as shown (filters, search and expanded groups applied). private func selectAdjacentSession(_ offset: Int) { - let ids = listModel.rows.map(\.id) + let ids = listModel.displayedSessionIds guard !ids.isEmpty else { return } let target: Int if let current = tabletNavigation.selectedSessionId, let index = ids.firstIndex(of: current) { @@ -220,13 +234,21 @@ struct HomeView: View { private func openSession(_ sessionId: String) { if usesSplitNavigation { tabletNavigation.open(sessionId) - } else if path.last != sessionId { - path.append(sessionId) + } else { + listModel.openMemberListIfNeeded(forSessionId: sessionId) + if path.last != sessionId { + path.append(sessionId) + } } } private func chat(_ sessionId: String) -> some View { - ChatView(session: session, sessionId: sessionId) { superseding in + ChatView( + session: session, + sessionId: sessionId, + onOpenLinkedSession: openSession + ) { superseding in + listModel.moveLeaderState(from: sessionId, to: superseding) if usesSplitNavigation { tabletNavigation.supersede(sessionId, with: superseding) } else if let last = path.indices.last, path[last] == sessionId { diff --git a/ios/Hapi/Features/Links/LinkOpenHandling.swift b/ios/Hapi/Features/Links/LinkOpenHandling.swift index 8a4f07a1339..c01f7556ef0 100644 --- a/ios/Hapi/Features/Links/LinkOpenHandling.swift +++ b/ios/Hapi/Features/Links/LinkOpenHandling.swift @@ -21,6 +21,8 @@ struct LinkOpenHandling: ViewModifier { /// Routes workspace-file citations to a real destination; nil shows the /// informational alert (the root fallback outside any session). var openWorkspaceFile: ((FilePathLink) -> Void)? + /// Routes `/sessions/` citations to that session's chat. + var openSession: ((String) -> Void)? @State private var safariURL: IdentifiedURL? @State private var confirmURL: IdentifiedURL? @@ -88,6 +90,10 @@ struct LinkOpenHandling: ViewModifier { @MainActor private func handle(_ url: URL) { + if let sessionLink = SessionPathLink(url: url) { + openSession?(sessionLink.sessionId) + return + } if let fileLink = FilePathLink(url: url) { if let openWorkspaceFile { openWorkspaceFile(fileLink) @@ -127,8 +133,11 @@ extension View { /// surfaces) for this subtree. Pass `openWorkspaceFile` to route /// `hapi-file://` citations into a real viewer instead of the fallback /// alert. - func handlesHapiLinks(openWorkspaceFile: ((FilePathLink) -> Void)? = nil) -> some View { - modifier(LinkOpenHandling(openWorkspaceFile: openWorkspaceFile)) + func handlesHapiLinks( + openWorkspaceFile: ((FilePathLink) -> Void)? = nil, + openSession: ((String) -> Void)? = nil + ) -> some View { + modifier(LinkOpenHandling(openWorkspaceFile: openWorkspaceFile, openSession: openSession)) } } diff --git a/ios/Hapi/Features/NewSession/ImportLocalSessionSheet.swift b/ios/Hapi/Features/NewSession/ImportLocalSessionSheet.swift new file mode 100644 index 00000000000..e1da642a3d0 --- /dev/null +++ b/ios/Hapi/Features/NewSession/ImportLocalSessionSheet.swift @@ -0,0 +1,257 @@ +import HapiClient +import HapiProtocol +import SwiftUI + +/// Browse and import local CLI transcripts (Claude, Codex, Cursor, OpenCode, Pi) +/// from an online runner machine into HAPI, then jump straight into the session. +struct ImportLocalSessionSheet: View { + let session: HubSession + let onImported: (String) -> Void + + @Environment(\.dismiss) private var dismiss + @State private var selectedSource: LocalSessionSource = .claude + @State private var selectedMachineId: String? + @State private var query = "" + @State private var sessions: [LocalSessionSummaryItem] = [] + @State private var isLoading = false + @State private var importingId: String? + @State private var errorMessage: String? + + private var onlineMachines: [Machine] { + session.machineStore.machines.filter(\.active) + } + + private var filteredSessions: [LocalSessionSummaryItem] { + let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines) + let sorted = sessions.sorted { $0.modifiedAt > $1.modifiedAt } + guard !trimmed.isEmpty else { return sorted } + return sorted.filter { item in + item.displayTitle.localizedCaseInsensitiveContains(trimmed) + || (item.cwd?.localizedCaseInsensitiveContains(trimmed) == true) + || (item.lastUserMessage?.localizedCaseInsensitiveContains(trimmed) == true) + } + } + + var body: some View { + NavigationStack { + VStack(spacing: 0) { + controlsBar + Divider() + content + } + .navigationTitle("Import Local Session") + .navigationBarTitleDisplayMode(.inline) + .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: Text("Filter local sessions…")) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .topBarTrailing) { + Button { + Task { await loadSessions() } + } label: { + Image(systemName: "arrow.clockwise") + } + .disabled(isLoading || onlineMachines.isEmpty) + .accessibilityLabel("Refresh") + } + } + .onAppear { + if selectedMachineId == nil { + selectedMachineId = onlineMachines.first?.id + } + } + .task(id: "\(selectedSource.rawValue)|\(selectedMachineId ?? "")") { + await loadSessions() + } + } + .presentationDetents([.large]) + } + + private var controlsBar: some View { + VStack(spacing: 8) { + Picker("Agent", selection: $selectedSource) { + ForEach(LocalSessionSource.allCases) { source in + Text(verbatim: source.displayName).tag(source) + } + } + .pickerStyle(.segmented) + + if onlineMachines.count > 1 { + HStack { + Text("Machine") + .font(.caption) + .foregroundStyle(.secondary) + Spacer() + Picker("Machine", selection: Binding( + get: { selectedMachineId ?? onlineMachines.first?.id ?? "" }, + set: { selectedMachineId = $0 } + )) { + ForEach(onlineMachines, id: \.id) { machine in + Text(verbatim: machineLabel(machine)).tag(machine.id) + } + } + .pickerStyle(.menu) + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + } + + @ViewBuilder + private var content: some View { + if onlineMachines.isEmpty { + ContentUnavailableView( + "No Online Machines", + systemImage: "desktopcomputer.trianglebadge.exclamationmark", + description: Text("Connect a runner machine to browse and import local CLI sessions.") + ) + } else if isLoading && sessions.isEmpty { + ProgressView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let errorMessage, sessions.isEmpty { + ContentUnavailableView( + "Unavailable", + systemImage: "exclamationmark.triangle", + description: Text(errorMessage) + ) + } else if filteredSessions.isEmpty { + ContentUnavailableView( + "No Local Sessions", + systemImage: "tray", + description: Text("No local \(selectedSource.displayName) sessions were found on this machine.") + ) + } else { + List { + if let errorMessage { + Section { + Text(errorMessage) + .font(.caption) + .foregroundStyle(.red) + } + } + ForEach(filteredSessions) { item in + sessionRow(item) + } + } + .listStyle(.plain) + } + } + + private func sessionRow(_ item: LocalSessionSummaryItem) -> some View { + let isImporting = importingId == item.id + return Button { + importItem(item) + } label: { + HStack(alignment: .center, spacing: 10) { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + Text(verbatim: item.displayTitle) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) + .lineLimit(2) + if item.hapiSessionId != nil { + Text("Imported") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(.tint.opacity(0.14), in: Capsule()) + .foregroundStyle(.tint) + } + } + HStack(spacing: 6) { + if let dir = item.directoryName { + Text(verbatim: dir) + .lineLimit(1) + } + if let count = item.messageCount { + Text(verbatim: "·") + Text("\(count, specifier: "%lld") msgs") + } + Text(verbatim: "·") + Text(item.modifiedDate.formatted(.relative(presentation: .named))) + } + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer(minLength: 4) + if isImporting { + ProgressView().controlSize(.small) + } else { + Image(systemName: item.hapiSessionId == nil ? "square.and.arrow.down" : "arrow.right.circle") + .foregroundStyle(.tint) + } + } + .padding(.vertical, 3) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(importingId != nil) + } + + private func machineLabel(_ machine: Machine) -> String { + if let name = machine.metadata?.displayName?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty { + return name + } + return machine.metadata?.host ?? String(machine.id.prefix(8)) + } + + private func loadSessions() async { + guard !onlineMachines.isEmpty else { + sessions = [] + return + } + let machineId = selectedMachineId ?? onlineMachines.first?.id + isLoading = true + errorMessage = nil + do { + let response = try await session.api.listLocalSessions(source: selectedSource, machineId: machineId) + guard !Task.isCancelled else { return } + if response.success { + sessions = response.sessions ?? [] + errorMessage = nil + } else { + sessions = [] + errorMessage = response.error ?? String(localized: "Failed to load local sessions") + } + isLoading = false + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { return } + sessions = [] + errorMessage = error.localizedDescription + isLoading = false + } + } + + private func importItem(_ item: LocalSessionSummaryItem) { + guard importingId == nil else { return } + importingId = item.id + errorMessage = nil + let source = selectedSource + let machineId = selectedMachineId ?? onlineMachines.first?.id + Task { + defer { importingId = nil } + do { + let response = try await session.api.importLocalSessions( + source: source, + sessionIds: [item.id], + machineId: machineId, + cwd: item.cwd + ) + if let targetId = response.firstImportedSessionId ?? item.hapiSessionId { + HapiHaptics.success() + try? await session.sessionStore.refresh() + dismiss() + onImported(targetId) + } else { + errorMessage = response.firstErrorMessage ?? String(localized: "Failed to import session") + } + } catch { + errorMessage = error.localizedDescription + } + } + } +} diff --git a/ios/Hapi/Features/NewSession/NewSessionView.swift b/ios/Hapi/Features/NewSession/NewSessionView.swift index e65bf9ba267..efec6a75601 100644 --- a/ios/Hapi/Features/NewSession/NewSessionView.swift +++ b/ios/Hapi/Features/NewSession/NewSessionView.swift @@ -9,12 +9,22 @@ import SwiftUI /// dismisses the sheet and pushes the chat — navigate-replace). struct NewSessionView: View { @State private var model: NewSessionModel + @State private var modelPickerOpen = false + @State private var saveProfileAlertOpen = false + @State private var newProfileName = "" + private let profileStore: AgentProfileStore = .shared @Environment(\.dismiss) private var dismiss private let session: HubSession + private let onImportLocalSession: (() -> Void)? - init(session: HubSession, onCreated: @escaping @MainActor (String) -> Void) { + init( + session: HubSession, + onImportLocalSession: (() -> Void)? = nil, + onCreated: @escaping @MainActor (String) -> Void + ) { _model = State(initialValue: NewSessionModel(session: session, onCreated: onCreated)) self.session = session + self.onImportLocalSession = onImportLocalSession } var body: some View { @@ -35,6 +45,16 @@ struct NewSessionView: View { dismiss() } } + if let onImportLocalSession { + ToolbarItem(placement: .topBarTrailing) { + Button { + onImportLocalSession() + } label: { + Label("Import…", systemImage: "square.and.arrow.down") + } + .accessibilityIdentifier("new-session.import-local") + } + } } .task { await model.start() @@ -54,6 +74,43 @@ struct NewSessionView: View { ) .macSheetSizing() } + .sheet(isPresented: $modelPickerOpen) { + let options = (model.modelOptions ?? []).map { + ModelPickerOption(value: $0.value.isEmpty ? nil : $0.value, label: $0.label) + } + let selected = model.form.model.isEmpty ? nil : model.form.model + SearchableModelPickerSheet( + title: "Model", + options: options, + selectedValue: selected + ) { chosen in + model.setModel(chosen ?? "") + } + } + .alert("Save Profile", isPresented: $saveProfileAlertOpen) { + TextField("Profile name", text: $newProfileName) + Button("Cancel", role: .cancel) {} + Button("Save") { + let effortValue: String? = if !model.form.effort.isEmpty { + model.form.effort + } else if !model.form.modelReasoningEffort.isEmpty { + model.form.modelReasoningEffort + } else { + nil + } + profileStore.save(AgentProfile( + name: newProfileName, + flavor: model.form.agent.rawValue, + model: model.form.model.isEmpty ? nil : model.form.model, + effort: effortValue, + permissionMode: model.form.permissionMode + )) + newProfileName = "" + } + .disabled(newProfileName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } message: { + Text("Save the current model, effort, and permission mode for quick reuse.") + } .onDisappear { model.stopDirectoryWork() } @@ -327,13 +384,54 @@ struct NewSessionView: View { @ViewBuilder private var optionsSection: some View { + let matchingProfiles = profileStore.profiles(forFlavor: model.form.agent.rawValue) + if !matchingProfiles.isEmpty || model.modelOptions != nil { + Section("Profiles") { + if !matchingProfiles.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(matchingProfiles) { profile in + FilterChip(label: profile.name, selected: false) { + HapiHaptics.light() + applyProfile(profile) + } + } + } + .padding(.vertical, 2) + } + } + Button { + newProfileName = "" + saveProfileAlertOpen = true + } label: { + Label("Save Current as Profile…", systemImage: "plus.circle") + .font(.subheadline) + } + } + .disabled(model.isSpawning) + } + Section("Options") { if let options = model.modelOptions { - optionPicker( - "Model", - options: options, - selection: Binding(get: { model.form.model }, set: { model.setModel($0) }) - ) + let selectedLabel = options.first { $0.value == model.form.model }?.label + ?? (model.form.model.isEmpty ? String(localized: "Default") : model.form.model) + Button { + modelPickerOpen = true + } label: { + HStack { + Text("Model") + .foregroundStyle(.primary) + Spacer() + Text(verbatim: selectedLabel) + .foregroundStyle(.secondary) + .lineLimit(1) + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(.tertiary) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) .disabled(model.modelsLoading || model.modelsError != nil) if model.modelsLoading { Text("Loading…") @@ -464,6 +562,23 @@ struct NewSessionView: View { ) } + private func applyProfile(_ profile: AgentProfile) { + if let modelValue = profile.model { + model.setModel(modelValue) + } + if let effortValue = profile.effort { + if model.effortOptions != nil { + model.setEffort(effortValue) + } + if model.reasoningEffortOptions != nil { + model.setModelReasoningEffort(effortValue) + } + } + if let permissionMode = profile.permissionMode { + model.setPermissionMode(permissionMode) + } + } + private func optionPicker( _ title: LocalizedStringKey, options: [NewSessionOption], diff --git a/ios/Hapi/Features/Scratchlist/ScratchlistView.swift b/ios/Hapi/Features/Scratchlist/ScratchlistView.swift index 92f3dfa7879..62e8c8ed3db 100644 --- a/ios/Hapi/Features/Scratchlist/ScratchlistView.swift +++ b/ios/Hapi/Features/Scratchlist/ScratchlistView.swift @@ -570,38 +570,13 @@ struct ScratchlistAttachmentViewer: View { let attachment: ScratchlistAttachment let loader: ScratchlistAttachmentLoader - @Environment(\.dismiss) private var dismiss @State private var image: UIImage? var body: some View { - ZStack(alignment: .topTrailing) { - Color.black.ignoresSafeArea() - if let image { - Image(uiImage: image) - .resizable() - .scaledToFit() - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(8) - } else { - Text(attachment.filename) - .foregroundStyle(.white) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - Button { - dismiss() - } label: { - Image(systemName: "xmark.circle.fill") - .font(.title2) - .foregroundStyle(.white.opacity(0.8)) - .padding(16) + HapiImageViewer(image: image, title: attachment.filename) + .task { + guard attachment.mimeType.hasPrefix("image/") else { return } + image = await loader.image(for: attachment.id) } - } - .onTapGesture { - dismiss() - } - .task { - guard attachment.mimeType.hasPrefix("image/") else { return } - image = await loader.image(for: attachment.id) - } } } diff --git a/ios/Hapi/Features/Sessions/SessionListModel.swift b/ios/Hapi/Features/Sessions/SessionListModel.swift index 5e6e4baa858..556c77ebc1d 100644 --- a/ios/Hapi/Features/Sessions/SessionListModel.swift +++ b/ios/Hapi/Features/Sessions/SessionListModel.swift @@ -11,18 +11,139 @@ struct SessionRowUI: Identifiable, Equatable { let summary: SessionSummary /// `getSessionTitle` port: name → summary text → path tail → id prefix. let title: String - /// Short project name only. Paths, machine/worktree details and the - /// conversation summary stay out of the compact home row. + /// Short project name only. Paths, machine details and the conversation + /// summary stay out of the compact home row; `worktree` follows it. let project: String? /// Raw flavor id (`claude`, `codex`, …); labels resolve via the catalog. let flavor: String? let unread: Bool + /// Set inside a project section whose header already names this row's + /// project (see `detailSubtitle(hasGroup:)`). + var projectImplied = false var id: String { summary.id } var status: SessionRowStatus? { SessionRowStatus(summary: summary) } var presence: SessionPresence { SessionPresence(summary: summary) } /// Only a running job is shown; finished ones leave no trace on the row. var runningJob: AttachedJob? { summary.runningAttachedJob } + /// Worktree checkout name (web `getWorktreeSessionLabel`): its name, else + /// the last segment of its path. Shown after the project. + var worktree: String? { + guard let worktree = summary.metadata?.worktree else { return nil } + let name = worktree.name.trimmingCharacters(in: .whitespacesAndNewlines) + if !name.isEmpty { return name } + let path = worktree.worktreePath ?? summary.metadata?.path ?? "" + return path.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) + } + /// The row's detail text: project, then worktree when there is one. + var subtitle: String? { + let parts = [project, worktree].compactMap { $0 }.filter { !$0.isEmpty } + return parts.isEmpty ? nil : parts.joined(separator: " · ") + } + /// The detail-line text. Under a header that already names the project, + /// the project only fills the line when nothing more specific (a worktree + /// or a group summary) does, so it never crowds those out. + func detailSubtitle(hasGroup: Bool) -> String? { + guard projectImplied, worktree != nil || hasGroup else { return subtitle } + return worktree + } +} + +/// Member summary shown on a group leader's own detail line +/// (`2 members · 1 working ›`); tapping it folds or unfolds the members. +struct SessionGroupSummaryUI: Equatable { + let memberCount: Int + /// False when every member is globally pinned or filtered out: the + /// summary still says the session leads a group, without a fold toggle. + let isExpandable: Bool + let isExpanded: Bool + let status: SessionGroupStatus + let isDissolving: Bool +} + +/// One nested member row displayed beneath an expanded group leader. +struct SessionMemberRowUI: Identifiable, Equatable { + let row: SessionRowUI + let leaderId: String + /// The group's last member draws the separator that closes the group. + var isLast = false + + var id: String { row.id } +} + +/// Typed item rendered inside the session list's Pinned / Recent sections. +enum SessionListItem: Identifiable, Equatable { + /// `group` is set on a leader row. `canDissolve` is precomputed with the + /// snapshot: the context menu is built eagerly for every row, so it must + /// not rescan all sessions per row. + case session(SessionRowUI, group: SessionGroupSummaryUI?, canDissolve: Bool) + case groupMember(SessionMemberRowUI) + + var id: String { + switch self { + case .session(let row, _, _): return row.id + case .groupMember(let member): return member.id + } + } + + var sessionId: String? { id } +} + +/// Non-pinned sessions grouped under one `(machine, workspace directory)` pair. +struct SessionProjectSection: Identifiable, Equatable { + let id: String + let title: String + let machineLabel: String? + let isCollapsed: Bool + let sessionCount: Int + let hasUnread: Bool + let hasAttention: Bool + let items: [SessionListItem] +} + +/// Frozen or live snapshot of the rendered session list sections. +struct SessionListSnapshot: Equatable { + let pinnedItems: [SessionListItem] + let recentItems: [SessionListItem] + let projectSections: [SessionProjectSection] + + init( + pinnedItems: [SessionListItem], + recentItems: [SessionListItem], + projectSections: [SessionProjectSection] = [] + ) { + self.pinnedItems = pinnedItems + self.recentItems = recentItems + self.projectSections = projectSections + } + + var isEmpty: Bool { pinnedItems.isEmpty && recentItems.isEmpty } + + var displayedSessionIds: [String] { + let body: [SessionListItem] = projectSections.isEmpty + ? recentItems + : projectSections.flatMap { $0.isCollapsed ? [] : $0.items } + return (pinnedItems + body).compactMap(\.sessionId) + } +} + +/// Confirmation prompt payload for dissolving a session group. +struct GroupDissolvePrompt: Identifiable, Equatable { + let leaderId: String + let leaderTitle: String + let count: Int + let impact: GroupDissolveImpact + let description: String + + var id: String { leaderId } +} + +/// Injectable network operations for dissolving a group (`APIClient` in production, +/// store-backed or scripted fakes in tests). +struct SessionGroupDissolveOperations { + let archiveSession: @Sendable (String) async throws -> Void + let fetchSessions: @Sendable () async throws -> [SessionSummary] + let refreshSessions: @MainActor @Sendable () async -> Void } extension SessionSummary { @@ -45,9 +166,9 @@ enum SessionPresence: Equatable { init(summary: SessionSummary) { // Same precedence as web: background-only before an attached job. - if summary.active && !summary.thinking && summary.backgroundTaskCount > 0 { + if summary.active && !summary.thinking && summary.derivedToolWork != true && summary.backgroundTaskCount > 0 { self = .background - } else if (summary.active && summary.thinking) || summary.runningAttachedJob != nil { + } else if (summary.active && (summary.thinking || summary.derivedToolWork == true)) || summary.runningAttachedJob != nil { self = .working } else if summary.active { self = .waiting @@ -166,17 +287,46 @@ final class SessionListModel { private let machineStore: any MachineListStoring private let lastSeenStore: LastSeenStore private let orderPrefs: SessionListOrderPrefs + private let openGroupStore: SessionGroupOpenStore + private let projectCollapseStore: ProjectGroupCollapseStore + private let dissolveStore: SessionGroupDissolveStore + private let dissolveOps: SessionGroupDissolveOperations + private let nowMs: @MainActor @Sendable () -> Int private let hubUrl: String /// Reopen follows a superseding id with the composer draft (web /// `transferComposerDraftThenNavigate`). private let drafts: (any ChatDrafts)? + /// Cross-session full-text message search seam (`GET /api/sessions/content-search`). + private let contentSearch: (@Sendable (String) async throws -> SessionsContentSearchResponse)? /// Not persisted: a new home / hub starts with all sessions. private(set) var filters = SessionListFilters() /// Text search (`.searchable`); ranks by relevance while non-blank. - var searchQuery = "" - /// The split detail's session stays listed under the unread lens. - var selectedSessionId: String? + var searchQuery = "" { + didSet { + reconcileFilterMemberOverrides() + if searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).count < 2 { + contentSearchResults = [] + isSearchingContent = false + } + } + } + /// Full-text message matches returned by the hub for `searchQuery`. + private(set) var contentSearchResults: [SessionContentSearchHit] = [] + private(set) var isSearchingContent = false + /// The split detail's session stays listed under the unread lens and opens its group. + var selectedSessionId: String? { + didSet { + guard selectedSessionId != oldValue, let id = selectedSessionId else { return } + revealSelectedMemberIfNeeded(sessionId: id) + } + } + /// Explicit in-memory member list overrides for the non-filtered view. + private var memberListOverrides: [String: Bool] = [:] + /// Transient fold overrides made while search/unread/machine filtering is active. + private var filterMemberListOverrides: [String: Bool] = [:] + /// Leaders whose group dissolve is currently running. + private(set) var dissolvingLeaderIds: Set = [] private(set) var isRefreshing = false /// Last refresh failed — show the offline state over snapshot data. private(set) var isOffline = false @@ -186,31 +336,91 @@ final class SessionListModel { @ObservationIgnored private var hasAttemptedRefresh = false /// Transient row-action failure for an alert. var actionError: String? + /// Custom title for `actionError` (defaults to "Action failed" when nil). + var actionErrorTitle: String? convenience init(session: HubSession) { + let scope = session.groupStateScope + let api = session.api + let sessionStore = session.sessionStore self.init( - sessionStore: session.sessionStore, machineStore: session.machineStore, - lastSeenStore: session.lastSeenStore, orderPrefs: .shared, hubUrl: session.hubUrl, - drafts: UserDefaultsChatDrafts(scope: session.hubUrl) + sessionStore: sessionStore, + machineStore: session.machineStore, + lastSeenStore: session.lastSeenStore, + orderPrefs: .shared, + openGroupStore: SessionGroupOpenStore(scope: scope), + projectCollapseStore: ProjectGroupCollapseStore(scope: scope), + dissolveStore: SessionGroupDissolveStore(scope: scope), + dissolveOps: SessionGroupDissolveOperations( + archiveSession: { id in try await api.archiveSession(id: id) }, + fetchSessions: { try await api.listSessions() }, + refreshSessions: { try? await sessionStore.refresh() } + ), + hubUrl: session.hubUrl, + drafts: UserDefaultsChatDrafts(scope: session.hubUrl), + contentSearch: { query in + try await api.searchSessionsContent(query: query, limit: 30) + } ) } - /// Without `orderPrefs` the order is in memory only, so tests never read - /// or write the host app's stored choice. + /// Without `orderPrefs` / group stores the preferences stay in memory only, + /// so tests never read or write the host app's stored choices. init( sessionStore: any SessionListStoring, machineStore: any MachineListStoring, lastSeenStore: LastSeenStore, orderPrefs: SessionListOrderPrefs? = nil, + openGroupStore: SessionGroupOpenStore? = nil, + projectCollapseStore: ProjectGroupCollapseStore? = nil, + dissolveStore: SessionGroupDissolveStore? = nil, + dissolveOps: SessionGroupDissolveOperations? = nil, + nowMs: (@MainActor @Sendable () -> Int)? = nil, hubUrl: String, - drafts: (any ChatDrafts)? = nil + drafts: (any ChatDrafts)? = nil, + contentSearch: (@Sendable (String) async throws -> SessionsContentSearchResponse)? = nil ) { self.sessionStore = sessionStore self.machineStore = machineStore self.lastSeenStore = lastSeenStore self.orderPrefs = orderPrefs ?? SessionListOrderPrefs(defaults: nil) + self.openGroupStore = openGroupStore ?? SessionGroupOpenStore(scope: hubUrl, defaults: nil) + self.projectCollapseStore = projectCollapseStore ?? ProjectGroupCollapseStore(scope: hubUrl, defaults: nil) + self.dissolveStore = dissolveStore ?? SessionGroupDissolveStore(scope: hubUrl, defaults: nil) + self.dissolveOps = dissolveOps ?? SessionGroupDissolveOperations( + archiveSession: { @MainActor id in try await sessionStore.archiveSession(sessionId: id) }, + fetchSessions: { @MainActor in + try await sessionStore.refresh() + return sessionStore.sessions + }, + refreshSessions: { try? await sessionStore.refresh() } + ) + self.nowMs = nowMs ?? { Int(Date().timeIntervalSince1970 * 1000) } self.hubUrl = hubUrl self.drafts = drafts + self.contentSearch = contentSearch + } + + /// Debounced cross-session message search driven by `.task(id: model.searchQuery)`. + func runContentSearch() async { + let trimmed = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines) + guard trimmed.count >= 2, let contentSearch else { + contentSearchResults = [] + isSearchingContent = false + return + } + try? await Task.sleep(for: .milliseconds(300)) + guard !Task.isCancelled else { return } + isSearchingContent = true + defer { isSearchingContent = false } + do { + let response = try await contentSearch(trimmed) + guard !Task.isCancelled else { return } + contentSearchResults = response.results + } catch { + guard !Task.isCancelled else { return } + contentSearchResults = [] + } } // MARK: - Derived state @@ -281,6 +491,7 @@ final class SessionListModel { } var order: SessionListOrder { orderPrefs.order } + var collapsedProjectIds: Set { projectCollapseStore.collapsedKeys } /// Filters or a non-default order: the menu button is tinted. var isCustomized: Bool { hasActiveFilters || !order.isDefault } @@ -318,6 +529,7 @@ final class SessionListModel { func setUnreadOnly(_ enabled: Bool) { filters.unreadOnly = enabled + reconcileFilterMemberOverrides() } func setStatus(_ status: SessionListStatus) { @@ -332,6 +544,10 @@ final class SessionListModel { orderPrefs.setActiveFirst(enabled) } + func toggleProjectSection(_ sectionId: String) { + projectCollapseStore.toggle(sectionId) + } + /// Content not yet read by a client in this namespace. var unreadCount: Int { let readState = lastSeenStore.state @@ -370,6 +586,7 @@ final class SessionListModel { func clearFilters() { filters = SessionListFilters() + reconcileFilterMemberOverrides() } /// Clear the stored pick as well, so a vanished group cannot resurrect it. @@ -377,49 +594,345 @@ final class SessionListModel { if filters.machineId != activeMachineFilter { filters.machineId = nil } + reconcileFilterMemberOverrides() } - /// Machine filter → status → unread lens (both keep the selected - /// session) → order. Text search ranks by relevance instead, with the base - /// order as tie-break as on web, keeping pin sections so the Pinned header - /// still applies. - var rows: [SessionRowUI] { + /// Filters that can surface matching members under a non-matching leader + /// automatically open member lists while active. + private var isAutoExpandingMemberLists: Bool { + isSearching || filters.unreadOnly || activeMachineFilter != nil + } + + private func reconcileFilterMemberOverrides() { + if !isAutoExpandingMemberLists && !filterMemberListOverrides.isEmpty { + filterMemberListOverrides.removeAll() + } + } + + private func revealSelectedMemberIfNeeded(sessionId: String) { + guard let summary = sessionStore.sessions.first(where: { $0.id == sessionId }) else { return } + let projectKey = ProjectGroupIdentity.groupKey( + machineId: summary.metadata?.machineId, + path: Self.projectPathKey(summary) + ) + projectCollapseStore.expand(projectKey) + guard summary.globalPinned != true, + let leaderId = summary.metadata?.groupLeaderId, + !leaderId.isEmpty, + leaderId != sessionId + else { return } + if memberListOverrides[leaderId] == false { + memberListOverrides.removeValue(forKey: leaderId) + } + if filterMemberListOverrides[leaderId] == false { + filterMemberListOverrides.removeValue(forKey: leaderId) + } + } + + /// Ensure a member's group opens when navigating to that session (e.g. + /// from a chat citation link or notification on iPhone stack navigation). + func openMemberListIfNeeded(forSessionId sessionId: String) { + guard let summary = sessionStore.sessions.first(where: { $0.id == sessionId }) else { return } + let projectKey = ProjectGroupIdentity.groupKey( + machineId: summary.metadata?.machineId, + path: Self.projectPathKey(summary) + ) + projectCollapseStore.expand(projectKey) + guard summary.globalPinned != true, + let leaderId = summary.metadata?.groupLeaderId, + !leaderId.isEmpty, + leaderId != sessionId + else { return } + openMemberList(leaderId: leaderId) + } + + func openMemberList(leaderId: String) { + if isAutoExpandingMemberLists { + filterMemberListOverrides[leaderId] = true + return + } + openGroupStore.setOpen(true, leaderId: leaderId) + memberListOverrides[leaderId] = true + } + + func toggleMemberList(leaderId: String, currentlyOpen: Bool) { + if isAutoExpandingMemberLists { + filterMemberListOverrides[leaderId] = !currentlyOpen + return + } + openGroupStore.setOpen(!currentlyOpen, leaderId: leaderId) + memberListOverrides[leaderId] = !currentlyOpen + } + + private func isMemberListOpen(leaderId: String, visibleMembers: [SessionSummary]) -> Bool { + if isAutoExpandingMemberLists { + return filterMemberListOverrides[leaderId] ?? true + } + if let override = memberListOverrides[leaderId] { + return override + } + return openGroupStore.isOpen(leaderId) + || visibleMembers.contains { $0.id == selectedSessionId } + } + + private struct ComputedList { + let topLevel: [SessionRowUI] + let snapshot: SessionListSnapshot + } + + private func computeGroupedList() -> ComputedList { let readState = lastSeenStore.state let followedTails = lastSeenStore.followedTails let activeFilter = activeMachineFilter let status = filters.status - var visible = sessionStore.sessions.filter { summary in - if let activeFilter, (summary.metadata?.machineId ?? unknownMachineFilterId) != activeFilter { - return false - } - return status.includes(summary) || summary.id == selectedSessionId + let allKnown = sessionStore.sessions + + // Status filter (Show: All / Active / Archived) scopes the `known` pool: + // if a leader is hidden by Show, its visible members become ordinary rows. + let statusSessions = allKnown.filter { summary in + status.includes(summary) || summary.id == selectedSessionId + } + + var filtered = statusSessions + if let activeFilter { + filtered = filtered.filter { ($0.metadata?.machineId ?? unknownMachineFilterId) == activeFilter } } if filters.unreadOnly { - visible = visible.filter { summary in + filtered = filtered.filter { summary in summary.id == selectedSessionId || LastSeenStore.isUnread(summary, state: readState, followedTails: followedTails) } } - if isSearching { - let labels = Dictionary(uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) }) - if let index = SessionListSearch.scoreIndex(sessions: visible, query: searchQuery, machineLabel: { id in - labels[id ?? unknownMachineFilterId] ?? "" - }) { - visible = SessionListSearch.rank(visible, by: index) - } - } else if order != .base { - // The store already keeps the base order. - visible = sortSessionSummaries(visible, order: order) + + let machineLabels = Dictionary(uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) }) + let rawSearchIndex: SessionListSearch.ScoreIndex? + let visible: [SessionSummary] + if isSearching, + let index = SessionListSearch.scoreIndex(sessions: filtered, query: searchQuery, machineLabel: { id in + machineLabels[id ?? unknownMachineFilterId] ?? "" + }) { + rawSearchIndex = index + visible = filtered.filter { index.matches($0.id) } + } else { + rawSearchIndex = nil + visible = filtered + } + + let layout = SessionGroups.layout(known: statusSessions, visible: visible) + let allMembersByLeader = SessionGroups.collectMembers(from: allKnown) + + let orderedTopLevel: [SessionSummary] + if let rawSearchIndex { + let boosted = SessionGroups.boostSearchScores(rawSearchIndex, layout: layout) + orderedTopLevel = SessionListSearch.rank(layout.topLevel, by: boosted) + } else { + orderedTopLevel = sortSessionSummaries(layout.topLevel, order: order) } - return visible.map { summary in - SessionRowUI( + + let pinnedBoundary = orderedTopLevel.prefix { $0.globalPinned == true || $0.pinned == true }.count + let now = nowMs() + let isUnread: (SessionSummary) -> Bool = { summary in + LastSeenStore.isUnread(summary, state: readState, followedTails: followedTails) + } + + var topLevelRows: [SessionRowUI] = [] + topLevelRows.reserveCapacity(orderedTopLevel.count) + var pinnedItems: [SessionListItem] = [] + var recentItems: [SessionListItem] = [] + + for (index, summary) in orderedTopLevel.enumerated() { + let row = SessionRowUI( summary: summary, title: Self.sessionTitle(summary), project: Self.projectLabel(summary), flavor: summary.metadata?.flavor, - unread: LastSeenStore.isUnread(summary, state: readState, followedTails: followedTails) + unread: isUnread(summary) + ) + topLevelRows.append(row) + + let visibleMembers = layout.membersByLeader[summary.id] ?? [] + let allMembers = allMembersByLeader[summary.id] ?? [] + let canDissolve: Bool + if allMembers.isEmpty { + canDissolve = false + } else { + let unconfirmed = dissolveStore.unconfirmedIds(forLeaderId: summary.id) + canDissolve = !SessionGroups.dissolveTargets( + leader: summary, + allMembers: allMembers, + unconfirmed: unconfirmed + ).live.isEmpty + } + + let isDissolving = dissolvingLeaderIds.contains(summary.id) + var group: SessionGroupSummaryUI? + var memberItems: [SessionListItem] = [] + if !visibleMembers.isEmpty { + let isOpen = isMemberListOpen(leaderId: summary.id, visibleMembers: visibleMembers) + group = SessionGroupSummaryUI( + memberCount: visibleMembers.count, + isExpandable: true, + isExpanded: isOpen, + status: SessionGroups.summarizeMembers(visibleMembers, isUnread: isUnread, nowMs: now), + isDissolving: isDissolving + ) + if isOpen { + let sortedMembers = SessionGroups.sortMembers( + visibleMembers, + order: order, + searchScores: rawSearchIndex + ) + for (memberIndex, member) in sortedMembers.enumerated() { + let memberRow = SessionRowUI( + summary: member, + title: Self.sessionTitle(member), + project: Self.projectLabel(member), + flavor: member.metadata?.flavor, + unread: isUnread(member) + ) + memberItems.append(.groupMember(SessionMemberRowUI( + row: memberRow, + leaderId: summary.id, + isLast: memberIndex == sortedMembers.count - 1 + ))) + } + } + } else if !allMembers.isEmpty && canDissolve { + // Every member is pinned elsewhere or filtered out: the leader + // still says it leads a group, and the menu keeps Dissolve. + group = SessionGroupSummaryUI( + memberCount: allMembers.count, + isExpandable: false, + isExpanded: false, + status: SessionGroupStatus(), + isDissolving: isDissolving + ) + } + + let itemsForRow: [SessionListItem] = [ + .session(row, group: group, canDissolve: canDissolve) + ] + memberItems + + if index < pinnedBoundary { + pinnedItems.append(contentsOf: itemsForRow) + } else { + recentItems.append(contentsOf: itemsForRow) + } + } + + var projectSections: [SessionProjectSection] = [] + if !isSearching && !recentItems.isEmpty { + let machineLabelsById = Dictionary( + uniqueKeysWithValues: machineFilters.map { ($0.id, $0.label) } ) + var orderKeys: [String] = [] + var metaByKey: [String: (machineId: String?, path: String?)] = [:] + var itemsByKey: [String: [SessionListItem]] = [:] + var activeProjectKey = ProjectGroupIdentity.groupKey(machineId: nil, path: nil) + + for item in recentItems { + switch item { + case .session(var row, let group, let canDissolve): + let machineId = row.summary.metadata?.machineId + let path = Self.projectPathKey(row.summary) + let key = ProjectGroupIdentity.groupKey(machineId: machineId, path: path) + activeProjectKey = key + if itemsByKey[key] == nil { + orderKeys.append(key) + metaByKey[key] = (machineId: machineId, path: path) + } + row.projectImplied = true + itemsByKey[key, default: []].append(.session(row, group: group, canDissolve: canDissolve)) + case .groupMember(let member): + // Keep expanded group members attached directly beneath their + // leader; one from another project keeps its project label. + var row = member.row + row.projectImplied = ProjectGroupIdentity.groupKey( + machineId: row.summary.metadata?.machineId, + path: Self.projectPathKey(row.summary) + ) == activeProjectKey + itemsByKey[activeProjectKey, default: []].append( + .groupMember(SessionMemberRowUI(row: row, leaderId: member.leaderId, isLast: member.isLast)) + ) + } + } + + let titles = ProjectGroupIdentity.disambiguatedTitles( + for: orderKeys.map { key in + let meta = metaByKey[key] + return (key: key, machineId: meta?.machineId, path: meta?.path) + }, + otherLabel: String(localized: "Other") + ) + + projectSections = orderKeys.compactMap { key in + guard let items = itemsByKey[key], !items.isEmpty else { return nil } + let meta = metaByKey[key] + let machineLabel: String? = meta?.machineId.flatMap { id in + if let resolved = machineLabelsById[id] { return resolved } + let trimmed = id.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : String(trimmed.prefix(8)) + } + var count = 0 + var hasUnread = false + var hasAttention = false + for item in items { + switch item { + case .session(let row, let group, _): + count += 1 + if let group, !group.isExpanded { + count += group.memberCount + } + if row.unread || (group?.status.unread ?? 0) > 0 { hasUnread = true } + if (row.summary.active && row.summary.pendingRequestsCount > 0) + || (group?.status.waiting ?? 0) > 0 { + hasAttention = true + } + case .groupMember(let member): + count += 1 + if member.row.unread { hasUnread = true } + if member.row.summary.active && member.row.summary.pendingRequestsCount > 0 { + hasAttention = true + } + } + } + let isCollapsed = !filters.unreadOnly && projectCollapseStore.isCollapsed(key) + return SessionProjectSection( + id: key, + title: titles[key] ?? String(localized: "Other"), + machineLabel: machineLabel, + isCollapsed: isCollapsed, + sessionCount: count, + hasUnread: hasUnread, + hasAttention: hasAttention, + items: items + ) + } } + + return ComputedList( + topLevel: topLevelRows, + snapshot: SessionListSnapshot( + pinnedItems: pinnedItems, + recentItems: recentItems, + projectSections: projectSections + ) + ) + } + + /// Top-level rows (ungrouped sessions, globally pinned members, and leaders). + var rows: [SessionRowUI] { + computeGroupedList().topLevel + } + + /// Full rendered sections, including group member bars and expanded members. + var listSnapshot: SessionListSnapshot { + computeGroupedList().snapshot + } + + /// Session ids in visual display order for keyboard stepping (⌘⌥↑/↓). + var displayedSessionIds: [String] { + listSnapshot.displayedSessionIds } /// Every order puts globalPinned/pinned rows first; this boundary index @@ -431,10 +944,131 @@ final class SessionListModel { /// Use the worktree's owning project, not its temporary checkout name. /// The home needs a scan key, not a repeated path or machine inventory. static func projectLabel(_ summary: SessionSummary) -> String? { - guard let path = summary.metadata?.worktree?.basePath ?? summary.metadata?.path else { return nil } + guard let path = projectPathKey(summary) else { return nil } return path.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) } + private static func projectPathKey(_ summary: SessionSummary) -> String? { + summary.metadata?.worktree?.basePath ?? summary.metadata?.path + } + + // MARK: - Group dissolve + + /// Every member of one leader in a single pass; `collectMembers` builds the + /// map for every leader and is meant for whole-list layout. + private func allMembers(ofLeader leaderId: String) -> [SessionSummary] { + sessionStore.sessions.filter { session in + session.id != leaderId && session.metadata?.groupLeaderId == leaderId + } + } + + func canDissolveGroup(leaderId: String) -> Bool { + guard let leader = sessionStore.sessions.first(where: { $0.id == leaderId }) else { return false } + let allMembers = self.allMembers(ofLeader: leaderId) + guard !allMembers.isEmpty else { return false } + let unconfirmed = dissolveStore.unconfirmedIds(forLeaderId: leaderId) + return !SessionGroups.dissolveTargets(leader: leader, allMembers: allMembers, unconfirmed: unconfirmed).live.isEmpty + } + + func dissolvePrompt(forLeaderId leaderId: String) -> GroupDissolvePrompt? { + guard !dissolvingLeaderIds.contains(leaderId), + let leader = sessionStore.sessions.first(where: { $0.id == leaderId }) + else { return nil } + let allMembers = self.allMembers(ofLeader: leaderId) + guard !allMembers.isEmpty else { return nil } + let unconfirmed = dissolveStore.unconfirmedIds(forLeaderId: leaderId) + let targets = SessionGroups.dissolveTargets(leader: leader, allMembers: allMembers, unconfirmed: unconfirmed) + guard !targets.live.isEmpty else { return nil } + let title = Self.sessionTitle(leader) + let impact = SessionGroups.summarizeDissolve(targets.live, nowMs: nowMs()) + let description = Self.dissolveDescription(leaderTitle: title, count: targets.live.count, impact: impact) + return GroupDissolvePrompt( + leaderId: leaderId, + leaderTitle: title, + count: targets.live.count, + impact: impact, + description: description + ) + } + + func dissolveGroup(leaderId: String) { + guard !dissolvingLeaderIds.contains(leaderId), + let leader = sessionStore.sessions.first(where: { $0.id == leaderId }) + else { return } + let allMembers = self.allMembers(ofLeader: leaderId) + guard !allMembers.isEmpty else { return } + + dissolvingLeaderIds.insert(leaderId) + let dissolveStore = self.dissolveStore + let ops = self.dissolveOps + let nowMs = self.nowMs + Task { + defer { self.dissolvingLeaderIds.remove(leaderId) } + let outcome = await GroupDissolver.dissolve( + leader: leader, + allMembers: allMembers, + store: dissolveStore, + archiveSession: ops.archiveSession, + fetchSessions: ops.fetchSessions, + refreshSessions: ops.refreshSessions, + nowMs: nowMs + ) + if let message = Self.dissolveFailureMessage(for: outcome) { + self.actionErrorTitle = String(localized: "Archive could not be confirmed") + self.actionError = message + } + } + } + + static func dissolveDescription(leaderTitle: String, count: Int, impact: GroupDissolveImpact) -> String { + var parts: [String] = [ + String( + format: String(localized: "Archive the %lld running sessions of the group led by “%@”?"), + Int64(count), + leaderTitle + ) + ] + if impact.working > 0 { + parts.append(String(format: String(localized: "%lld still working."), Int64(impact.working))) + } + if impact.waiting > 0 { + parts.append(String(format: String(localized: "%lld waiting for your answer."), Int64(impact.waiting))) + } + if impact.worktree > 0 { + parts.append(String( + format: String(localized: "%lld in a worktree: check for unmerged changes first."), + Int64(impact.worktree) + )) + } + return parts.joined(separator: " ") + } + + static func dissolveFailureMessage(for outcome: GroupDissolver.Outcome) -> String? { + switch outcome { + case .nothingToDissolve, .succeeded: + return nil + case .membersFailed(let failed, let total): + return String( + format: String(localized: "%lld of %lld members not archived. The leader is still running."), + Int64(failed), + Int64(total) + ) + case .uncheckedMembers: + return String(localized: "Could not check the group for new members. The leader is still running.") + case .membersRunning(let count): + return String( + format: String(localized: "%lld members are running. The leader is still running; review the group and dissolve it again."), + Int64(count) + ) + case .leaderFailed(let total): + return String( + format: String(localized: "%lld of %lld sessions not archived."), + Int64(1), + Int64(total) + ) + } + } + // MARK: - Actions /// A split sidebar can disappear/reappear just because the window @@ -470,11 +1104,26 @@ final class SessionListModel { /// `PUT /sessions/:id/pin` with store-side optimistic re-sort; failures /// surface on `actionError`. func setPinMode(sessionId: String, mode: SessionPinMode) { + let returningLeaderId: String? + if mode != .global, + let summary = sessionStore.sessions.first(where: { $0.id == sessionId }), + summary.globalPinned == true, + let leaderId = summary.metadata?.groupLeaderId, + !leaderId.isEmpty, + leaderId != sessionId { + returningLeaderId = leaderId + } else { + returningLeaderId = nil + } let store = sessionStore Task { do { try await store.setPinMode(sessionId: sessionId, mode: mode) + if let returningLeaderId { + self.openMemberList(leaderId: returningLeaderId) + } } catch { + self.actionErrorTitle = nil self.actionError = String( format: String(localized: "Pin failed: %@"), error.localizedDescription @@ -491,6 +1140,7 @@ final class SessionListModel { do { try await store.archiveSession(sessionId: sessionId) } catch { + self.actionErrorTitle = nil self.actionError = String( format: String(localized: "Archive failed: %@"), error.localizedDescription @@ -508,6 +1158,7 @@ final class SessionListModel { do { try await store.renameSession(sessionId: sessionId, name: trimmed) } catch { + self.actionErrorTitle = nil self.actionError = String( format: String(localized: "Rename failed: %@"), error.localizedDescription @@ -524,6 +1175,7 @@ final class SessionListModel { do { try await store.deleteSession(sessionId: sessionId) } catch { + self.actionErrorTitle = nil self.actionError = isActiveSessionConflict(error) ? String(localized: "Active sessions can't be deleted — archive first") : String(format: String(localized: "Delete failed: %@"), error.localizedDescription) @@ -540,15 +1192,29 @@ final class SessionListModel { let response = try await store.reopenSession(sessionId: sessionId) if response.sessionId != sessionId { self.drafts?.move(fromSessionId: sessionId, toSessionId: response.sessionId) + self.moveLeaderState(from: sessionId, to: response.sessionId) } onReopened(response.sessionId) } catch { + self.actionErrorTitle = nil self.actionError = formatReopenError(error) ?? String(localized: "Failed to reopen session") } } } + func moveLeaderState(from oldId: String, to newId: String) { + guard oldId != newId else { return } + openGroupStore.move(from: oldId, to: newId) + dissolveStore.moveLeader(from: oldId, to: newId) + if let override = memberListOverrides.removeValue(forKey: oldId) { + memberListOverrides[newId] = override + } + if let filterOverride = filterMemberListOverrides.removeValue(forKey: oldId) { + filterMemberListOverrides[newId] = filterOverride + } + } + // MARK: - Helpers /// `getSessionTitle` (`web/src/lib/sessionTitle.ts`): name → summary diff --git a/ios/Hapi/Features/Sessions/SessionListView.swift b/ios/Hapi/Features/Sessions/SessionListView.swift index 07f4788ba53..96f1dd589a3 100644 --- a/ios/Hapi/Features/Sessions/SessionListView.swift +++ b/ios/Hapi/Features/Sessions/SessionListView.swift @@ -17,7 +17,8 @@ import SwiftUI /// state its own mark (working / background / waiting / stopped); title with trailing /// relative `updatedAt` (unread: semibold title + accent time, no dot so /// the badge stays the only dot); a quiet second line has project left and an attention symbol right -/// (a running attached job takes the project's place). No preview, todo progress, +/// (a running attached job takes the project's place; under a project header the project +/// gives way to a worktree or group summary). No preview, todo progress, /// machine/path details or spinners. Disconnected rows are not dimmed; /// - swipe actions: leading pin/mark-read, trailing archive or delete/reopen; /// - long-press context menu → rename, pin (none/project/global), then @@ -33,8 +34,9 @@ struct SessionListView: View { @State private var renameTarget: SessionRowUI? @State private var renameText = "" @State private var deleteTarget: SessionRowUI? - /// Rows kept while a pushed chat covers the list (see `sessionList`). - @State private var frozenRows: [SessionRowUI]? + @State private var dissolveTarget: GroupDissolvePrompt? + /// Snapshot kept while a pushed chat covers the list (see `sessionList`). + @State private var frozenSnapshot: SessionListSnapshot? var body: some View { // Rows own their minute-tick age labels; the list itself only @@ -59,22 +61,27 @@ struct SessionListView: View { await model.refresh() } } + .task(id: model.searchQuery) { + await model.runContentSearch() + } .refreshable { await model.refresh() } .alert( - "Action failed", + model.actionErrorTitle ?? String(localized: "Action failed"), isPresented: Binding( get: { model.actionError != nil }, set: { presented in if !presented { model.actionError = nil + model.actionErrorTitle = nil } } ) ) { Button("OK") { model.actionError = nil + model.actionErrorTitle = nil } } message: { Text(model.actionError ?? "") @@ -113,63 +120,101 @@ struct SessionListView: View { } message: { row in Text(SessionNameRules.deleteMessage(title: row.title)) } + .alert( + "Dissolve group", + isPresented: Binding( + get: { dissolveTarget != nil }, + set: { if !$0 { dissolveTarget = nil } } + ), + presenting: dissolveTarget + ) { prompt in + Button("Archive", role: .destructive) { + model.dissolveGroup(leaderId: prompt.leaderId) + } + Button("Cancel", role: .cancel) {} + } message: { prompt in + Text(prompt.description) + } } // MARK: - List - /// Covered by a pushed chat, the list keeps its last rows: on a large + /// Covered by a pushed chat, the list keeps its last snapshot: on a large /// hub every streaming session would otherwise rebuild and diff /// thousands of rows nobody sees (~80 ms main-thread stalls while /// scrolling the chat). A side-by-side split never disappears and /// stays live; returning refreshes once. private var sessionList: some View { - let rows = frozenRows ?? model.rows - return KeyedContent(key: ListRenderKey(rows: rows, selectable: selection != nil, - theme: theme, filters: model.filters, order: model.order)) { - list(rows) + let snapshot = frozenSnapshot ?? model.listSnapshot + return KeyedContent(key: ListRenderKey(snapshot: snapshot, selectable: selection != nil, + theme: theme, filters: model.filters, order: model.order, + collapsedProjectIds: model.collapsedProjectIds, + contentHits: model.contentSearchResults, + isSearchingContent: model.isSearchingContent)) { + list(snapshot) } .equatable() - .onAppear { frozenRows = nil } - .onDisappear { frozenRows = model.rows } + .onAppear { frozenSnapshot = nil } + .onDisappear { frozenSnapshot = model.listSnapshot } } - private func list(_ rows: [SessionRowUI]) -> some View { - let pinnedCount = SessionListModel.pinnedCount(of: rows) + private func list(_ snapshot: SessionListSnapshot) -> some View { + let hasPinned = !snapshot.pinnedItems.isEmpty return List(selection: selection) { - if pinnedCount > 0 { + if hasPinned { Section { - ForEach(rows.prefix(pinnedCount)) { row in - equatableRow(row) + ForEach(snapshot.pinnedItems) { item in + equatableItem(item) } } header: { sectionHeader("Pinned") } .listSectionSeparator(.hidden, edges: .top) } - if rows.count > pinnedCount { - // Headerless when nothing is pinned: an empty-string Section - // header still reserves a blank sticky band above the list - // (device feedback: "一片空白"). - if pinnedCount > 0 { + if !snapshot.projectSections.isEmpty { + ForEach(snapshot.projectSections) { section in Section { - ForEach(rows.dropFirst(pinnedCount)) { row in - equatableRow(row) + if !section.isCollapsed { + ForEach(section.items) { item in + equatableItem(item) + } } } header: { - // Not "Sessions": the navigation title already says so. - sectionHeader("Recent") + projectSectionHeader(section) } .listSectionSeparator(.hidden, edges: .top) - } else { - // Top edge hidden: a plain list otherwise draws a stray - // separator above the very first row (device feedback). - Section { - ForEach(rows) { row in - equatableRow(row) - } + } + } else if !snapshot.recentItems.isEmpty { + // Searching renders flat relevance-ranked results. + Section { + ForEach(snapshot.recentItems) { item in + equatableItem(item) } - .listSectionSeparator(.hidden, edges: .top) } + .listSectionSeparator(.hidden, edges: .top) + } + if !model.contentSearchResults.isEmpty { + Section { + ForEach(model.contentSearchResults) { hit in + contentSearchRow(hit) + .listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)) + .listRowSeparatorTint(theme.divider) + } + } header: { + sectionHeader("Matching Messages") + } + .listSectionSeparator(.hidden, edges: .top) + } else if model.isSearchingContent && snapshot.isEmpty { + Section { + HStack(spacing: 8) { + ProgressView().controlSize(.small) + Text("Searching messages…") + .font(.subheadline) + .foregroundStyle(.secondary) + } + .padding(.vertical, 8) + } + .listSectionSeparator(.hidden, edges: .top) } } .modifier(PlatformSessionListStyle()) @@ -182,54 +227,195 @@ struct SessionListView: View { .id(ListIdentity(filters: model.filters, order: model.order)) .accessibilityIdentifier("home.sessions") .overlay { - if rows.isEmpty { + if snapshot.isEmpty && model.contentSearchResults.isEmpty && !model.isSearchingContent { emptyState .allowsHitTesting(false) // keep the pull-to-refresh gesture } } } - /// The List evaluates every row's content (offscreen ones included) on - /// each list change, so one streaming session cost O(all rows) per - /// update. Rows compare only what they draw and skip unchanged content. - private func equatableRow(_ row: SessionRowUI) -> some View { - KeyedContent(key: RowRenderKey(row: row, selectable: selection != nil, theme: theme)) { - rowCell(row) + private func projectSectionHeader(_ section: SessionProjectSection) -> some View { + Button { + withAnimation(.snappy(duration: 0.2)) { + model.toggleProjectSection(section.id) + } + } label: { + HStack(spacing: 6) { + Image(systemName: section.isCollapsed ? "chevron.right" : "chevron.down") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.tertiary) + .frame(width: 10) + Image(systemName: "folder") + .font(.caption2) + .foregroundStyle(.secondary) + Text(verbatim: section.title) + .font(.caption.weight(.semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + .truncationMode(.middle) + if let machine = section.machineLabel { + Text(verbatim: "·") + .font(.caption2) + .foregroundStyle(.tertiary) + Text(verbatim: machine) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + } + Spacer(minLength: 6) + if section.isCollapsed { + if section.hasAttention { + Circle() + .fill(theme.warning) + .frame(width: 6, height: 6) + } else if section.hasUnread { + Circle() + .fill(theme.accent) + .frame(width: 6, height: 6) + } + } + Text(verbatim: "\(section.sessionCount)") + .font(.caption2.monospacedDigit()) + .foregroundStyle(.tertiary) + } + .frame(maxWidth: .infinity, minHeight: 32, alignment: .leading) + .contentShape(Rectangle()) } - .equatable() + .buttonStyle(.plain) + .textCase(nil) + .listRowInsets(EdgeInsets(top: 6, leading: 16, bottom: 4, trailing: 16)) + .accessibilityLabel( + section.machineLabel.map { "\(section.title), \($0), \(section.sessionCount)" } + ?? "\(section.title), \(section.sessionCount)" + ) + .accessibilityValue(section.isCollapsed ? String(localized: "Collapsed") : String(localized: "Expanded")) } - private func rowCell(_ row: SessionRowUI) -> some View { - Group { - if selection != nil { - NavigationLink(value: row.id) { - rowLabel(row) - } - .tag(row.id) - } else { - Button { - onOpenSession(row.id) - } label: { - rowLabel(row) + private func contentSearchRow(_ hit: SessionContentSearchHit) -> some View { + Button { + onOpenSession(hit.session.id) + } label: { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + Text(verbatim: SessionListModel.sessionTitle(hit.session)) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) + .lineLimit(1) + Spacer(minLength: 4) + Text(hit.match.role == "user" ? String(localized: "You") : String(localized: "Agent")) + .font(.caption2.weight(.medium)) + .foregroundStyle(.secondary) } - .buttonStyle(.plain) + Text(hit.match.snippet) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + .fixedSize(horizontal: false, vertical: true) } + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) } - .listRowInsets(EdgeInsets(top: Self.rowVerticalInset, leading: 16, bottom: Self.rowVerticalInset, trailing: 16)) - // Default separator color reads heavy against these rows; the theme - // divider is the WeChat-style faint hairline. - .listRowSeparatorTint(theme.divider) - .swipeActions(edge: .leading) { - leadingSwipeActions(row) - } - .swipeActions(edge: .trailing) { - trailingSwipeActions(row) + .buttonStyle(.plain) + } + + /// The List evaluates every row's content (offscreen ones included) on + /// each list change, so one streaming session cost O(all rows) per + /// update. Items compare only what they draw and skip unchanged content. + /// + /// List container traits (`listRowInsets`, `listRowSeparator`, `tag`, + /// `swipeActions`, `contextMenu`) stay outside `KeyedContent` so SwiftUI + /// reads them directly on each `ForEach` element. + @ViewBuilder + private func equatableItem(_ item: SessionListItem) -> some View { + switch item { + case .session(let row, let group, let canDissolve): + let membersBelow = group?.isExpanded == true + KeyedContent(key: ItemRenderKey(item: item, selectable: selection != nil, theme: theme)) { + rowContent(row, group: group) + } + .equatable() + .tag(row.id) + .listRowInsets(EdgeInsets( + top: Self.rowVerticalInset, + leading: 16, + bottom: membersBelow ? Self.attachedLeaderBottomInset : Self.rowVerticalInset, + trailing: 16 + )) + .listRowSeparator(membersBelow ? .hidden : .automatic, edges: .bottom) + // Default separator color reads heavy against these rows; the theme + // divider is the WeChat-style faint hairline. + .listRowSeparatorTint(theme.divider) + .swipeActions(edge: .leading) { + leadingSwipeActions(row) + } + .swipeActions(edge: .trailing) { + trailingSwipeActions(row) + } + // SwiftUI builds menu content eagerly for every row, so it reads the + // snapshot's precomputed flag instead of scanning all sessions. + .contextMenu { + contextMenuActions(row, allowDissolveGroup: canDissolve) + } + + case .groupMember(let member): + // A compact session row indented under its leader's title. Only the + // last member draws a separator, at the top-level inset, so the + // group reads as one block that ends there. + KeyedContent(key: ItemRenderKey(item: item, selectable: selection != nil, theme: theme)) { + rowContent(member.row, group: nil, member: member) + } + .equatable() + .tag(member.id) + .listRowInsets(EdgeInsets( + top: Self.memberVerticalInset, + leading: SessionRowView.memberLeading, + bottom: member.isLast ? Self.rowVerticalInset : Self.memberVerticalInset, + trailing: 16 + )) + .listRowSeparator(member.isLast ? .automatic : .hidden, edges: .bottom) + .listRowSeparatorTint(theme.divider) + .swipeActions(edge: .leading) { + leadingSwipeActions(member.row) + } + .swipeActions(edge: .trailing) { + trailingSwipeActions(member.row) + } + .contextMenu { + contextMenuActions(member.row, allowDissolveGroup: false) + } } - .contextMenu { - contextMenuActions(row) + } + + @ViewBuilder + private func rowContent( + _ row: SessionRowUI, + group: SessionGroupSummaryUI?, + member: SessionMemberRowUI? = nil + ) -> some View { + if selection != nil { + NavigationLink(value: row.id) { + rowLabel(row, group: group, member: member) + } + } else { + Button { + onOpenSession(row.id) + } label: { + rowLabel(row, group: group, member: member) + } + .buttonStyle(.plain) } } + /// Member rows are compact, so their insets are tighter too. + private static var memberVerticalInset: CGFloat { + #if targetEnvironment(macCatalyst) + 4 + #else + 8 + #endif + } + /// Pointer rows on a Mac sidebar are denser than touch rows. private static var rowVerticalInset: CGFloat { #if targetEnvironment(macCatalyst) @@ -239,6 +425,14 @@ struct SessionListView: View { #endif } + private static var attachedLeaderBottomInset: CGFloat { + #if targetEnvironment(macCatalyst) + 2 + #else + 4 + #endif + } + /// Compact header (Mail-style) instead of the large plain-list default. private func sectionHeader(_ title: LocalizedStringKey) -> some View { Text(title) @@ -300,14 +494,25 @@ struct SessionListView: View { } } - private func rowLabel(_ row: SessionRowUI) -> some View { - SessionRowView(row: row) - .frame(maxWidth: .infinity, alignment: .leading) - .contentShape(Rectangle()) + private func rowLabel( + _ row: SessionRowUI, + group: SessionGroupSummaryUI?, + member: SessionMemberRowUI? + ) -> some View { + SessionRowView( + row: row, + group: group, + onToggleGroup: group.map { group in + { model.toggleMemberList(leaderId: row.id, currentlyOpen: group.isExpanded) } + }, + member: member.map { $0.isLast ? .last : .inner } + ) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) } @ViewBuilder - private func contextMenuActions(_ row: SessionRowUI) -> some View { + private func contextMenuActions(_ row: SessionRowUI, allowDissolveGroup: Bool) -> some View { let summary = row.summary Button { renameText = row.title @@ -358,6 +563,15 @@ struct SessionListView: View { Label("Delete…", systemImage: "trash") } } + if allowDissolveGroup { + Divider() + Button(role: .destructive) { + dissolveTarget = model.dissolvePrompt(forLeaderId: row.id) + } label: { + Label("Dissolve group", systemImage: "archivebox.circle") + } + .disabled(model.dissolvingLeaderIds.contains(row.id)) + } } // MARK: - Chrome @@ -408,18 +622,21 @@ private struct KeyedContent: View, Equatable { static func == (lhs: Self, rhs: Self) -> Bool { lhs.key == rhs.key } } -private struct RowRenderKey: Equatable { - let row: SessionRowUI +private struct ItemRenderKey: Equatable { + let item: SessionListItem let selectable: Bool let theme: HapiTheme } private struct ListRenderKey: Equatable { - let rows: [SessionRowUI] + let snapshot: SessionListSnapshot let selectable: Bool let theme: HapiTheme let filters: SessionListFilters let order: SessionListOrder + let collapsedProjectIds: Set + let contentHits: [SessionContentSearchHit] + let isSearchingContent: Bool } private struct ListIdentity: Hashable { @@ -433,8 +650,55 @@ struct SessionRowView: View { @ScaledMetric(relativeTo: .footnote) private var statusSlotSize: CGFloat = 16 let row: SessionRowUI + /// Set on a group leader: its member summary joins the detail line. + var group: SessionGroupSummaryUI? = nil + var onToggleGroup: (() -> Void)? = nil + /// Set on a nested group member, which draws as a compact row. + var member: MemberPosition? = nil + + enum MemberPosition { + /// Hides its separator, so the members read as one block. + case inner + /// Its separator closes the group at the top-level inset. + case last + } + + /// Top-level row leading inset, which the member indent builds on. + static let rowLeading: CGFloat = 16 + private static let iconSpacing: CGFloat = 12 + /// Members start under the leader's title (`16 + 30 icon + 12 spacing`): + /// the indent marks them as nested. + static let memberLeading: CGFloat = rowLeading + 30 + iconSpacing + /// Member icons are 80% of a top-level icon (24pt at the default size). + private static let memberIconScale: CGFloat = 0.8 - private let iconSpacing: CGFloat = 12 + private var iconSpacing: CGFloat { Self.iconSpacing } + private var rowIconSize: CGFloat { member == nil ? iconSize : iconSize * Self.memberIconScale } + + /// Separators start under the text column, as in Mail and Messages; the + /// last member's lines up with the top-level rows' to close the group. + private var separatorLeading: CGFloat { + switch member { + case .last: Self.rowLeading + iconSize + iconSpacing - Self.memberLeading + case .inner, nil: rowIconSize + iconSpacing + } + } + private var subtitleText: String? { row.detailSubtitle(hasGroup: group != nil) } + + /// Unread members of a folded group, rolled up onto the leader as in a + /// Mail thread; an open group shows them on the member rows instead. + private var foldedUnreadMembers: Int { + guard let group, !group.isExpanded else { return 0 } + return group.status.unread + } + + private var showsUnread: Bool { row.unread || foldedUnreadMembers > 0 } + + private var unreadAccessibilityValue: Text { + if row.unread { return Text("Unread") } + if foldedUnreadMembers > 0 { return Text("\(Int64(foldedUnreadMembers)) unread") } + return Text(verbatim: "") + } var body: some View { HStack(alignment: .center, spacing: iconSpacing) { @@ -444,19 +708,22 @@ struct SessionRowView: View { detailLine } } - // Separators start under the text column, as in Mail and Messages. - .alignmentGuide(.listRowSeparatorLeading) { _ in iconSize + iconSpacing } + .alignmentGuide(.listRowSeparatorLeading) { _ in + separatorLeading + } .accessibilityElement(children: .combine) - .accessibilityValue(row.unread ? Text("Unread") : Text(verbatim: "")) + .accessibilityValue(unreadAccessibilityValue) + .modifier(GroupToggleAccessibilityAction(group: group, onToggle: onToggleGroup)) .accessibilityIdentifier("home.session.\(row.id)") } /// The agent owns the leading column; its presence badge carries the /// session state instead of dimming disconnected rows. private var agentIcon: some View { - AgentFlavorIconView(flavor: row.flavor, size: iconSize * 0.8) - .frame(width: iconSize, height: iconSize) + AgentFlavorIconView(flavor: row.flavor, size: rowIconSize * 0.8) + .frame(width: rowIconSize, height: rowIconSize) .overlay(alignment: .bottomTrailing) { + // The badge keeps its full size on a member: it carries state. SessionPresenceBadge(presence: row.presence, size: iconSize * 0.3) .offset(x: 2, y: 2) } @@ -464,11 +731,7 @@ struct SessionRowView: View { private var titleLine: some View { HStack(spacing: 8) { - Text(verbatim: row.title) - .font(.body) - .fontWeight(row.unread ? .semibold : .regular) - .foregroundStyle(theme.textPrimary) - .lineLimit(1) + titleText Spacer(minLength: 4) // Unread is a semibold title plus an accent timestamp, not a // dot: the presence badge is the row's only dot. @@ -477,43 +740,69 @@ struct SessionRowView: View { Text(verbatim: formatRelativeAge(now: context.date, thenEpochMs: row.summary.updatedAt)) } .font(.footnote) - .fontWeight(row.unread ? .semibold : .regular) - .foregroundStyle(row.unread ? theme.accent : theme.textSecondary) + .fontWeight(showsUnread ? .semibold : .regular) + .foregroundStyle(showsUnread ? theme.accent : theme.textSecondary) .monospacedDigit() .fixedSize() } } + private var titleText: some View { + Text(verbatim: row.title) + .font(member == nil ? .body : .subheadline) + .fontWeight(showsUnread ? .semibold : .regular) + .foregroundStyle(theme.textPrimary) + .lineLimit(1) + .layoutPriority(1) + } + /// Project left; only states that need the user (reply/approval) get a - /// trailing symbol. Routine activity lives on the icon badge. + /// trailing symbol. Routine activity lives on the icon badge. A group + /// leader adds its member summary after the project. private var detailLine: some View { HStack(alignment: .center, spacing: 0) { - if let job = row.runningJob { - AttachedJobLine(job: job) - } else { - // Keep the same text line height when metadata is missing, - // so the row height does not jump. - Text(verbatim: row.project ?? " ") - .lineLimit(1) - .accessibilityHidden(row.project == nil) + HStack(alignment: .center, spacing: 4) { + if let job = row.runningJob { + AttachedJobLine(job: job) + } else if group == nil || subtitleText != nil { + // Keep the same text line height when metadata is missing, + // so the row height does not jump. + Text(verbatim: subtitleText ?? " ") + .lineLimit(1) + .accessibilityHidden(subtitleText == nil) + } + if let group { + if row.runningJob != nil || subtitleText != nil { + Text(verbatim: "·") + .foregroundStyle(theme.textHint) + } + SessionGroupSummaryView(group: group, onToggle: onToggleGroup) + .layoutPriority(1) + .accessibilityIdentifier("home.group.members.\(row.id)") + } } Spacer(minLength: 12) if let status = row.status { - Image(systemName: status.symbolName) - .symbolVariant(.none) - .symbolRenderingMode(.monochrome) - .foregroundStyle(attentionColor) - // One slot keeps every attention symbol aligned. - .frame(width: statusSlotSize, height: statusSlotSize) - .fixedSize() - .layoutPriority(1) - .accessibilityLabel(statusAccessibilityText(status)) + statusMark(status) } } .font(.footnote) .foregroundStyle(theme.textSecondary) } + private func statusMark(_ status: SessionRowStatus) -> some View { + Image(systemName: status.symbolName) + .font(.footnote) + .symbolVariant(.none) + .symbolRenderingMode(.monochrome) + .foregroundStyle(attentionColor) + // One slot keeps every attention symbol aligned. + .frame(width: statusSlotSize, height: statusSlotSize) + .fixedSize() + .layoutPriority(1) + .accessibilityLabel(statusAccessibilityText(status)) + } + // Darker amber keeps thin strokes visible on white without a filled // symbol, background badge or animation competing with the session title. private var attentionColor: Color { @@ -531,6 +820,101 @@ struct SessionRowView: View { } } +/// A group leader's member summary on its detail line: `2 members · +/// 1 working ›`. Tapping it folds or unfolds the members; the rest of the +/// row still opens the leader. A borderless button keeps its own hit region +/// inside the row's button / navigation link. +/// +/// Only `waiting` (needs the user) is coloured; routine activity already +/// shows on each icon badge and unread rolls up onto the leader's title. +/// An open group drops the counts, since its member rows show them. +struct SessionGroupSummaryView: View { + @Environment(\.hapiTheme) private var theme + let group: SessionGroupSummaryUI + let onToggle: (() -> Void)? + + var body: some View { + if group.isExpandable, let onToggle { + Button(action: onToggle) { + label + // A taller hit target than the footnote line, without + // growing the row. + .padding(.vertical, Self.hitPadding) + .padding(.trailing, Self.hitPadding) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .padding(.vertical, -Self.hitPadding) + .padding(.trailing, -Self.hitPadding) + .accessibilityValue(group.isExpanded ? Text("Expanded") : Text("Collapsed")) + } else { + label + } + } + + private var label: some View { + HStack(alignment: .center, spacing: 4) { + summaryText + .lineLimit(1) + if group.isDissolving { + ProgressView() + .controlSize(.mini) + } else if group.isExpandable { + // Down/up says "fold in place"; a trailing `›` would read as + // navigation, which the rest of the row already does. + Image(systemName: group.isExpanded ? "chevron.up" : "chevron.down") + .font(.caption2.weight(.semibold)) + .foregroundStyle(theme.textHint) + } + } + } + + private var summaryText: Text { + var text = Text("\(Int64(group.memberCount)) members") + .foregroundStyle(theme.textSecondary) + guard !group.isExpanded else { return text } + let sep = Text(verbatim: " · ").foregroundStyle(theme.textHint) + if group.status.waiting > 0 { + let part = Text("\(Int64(group.status.waiting)) waiting").foregroundStyle(attentionColor) + text = Text("\(text)\(sep)\(part)") + } + if group.status.working > 0 { + let part = Text("\(Int64(group.status.working)) working").foregroundStyle(theme.textSecondary) + text = Text("\(text)\(sep)\(part)") + } + return text + } + + private var attentionColor: Color { + theme.isDark ? theme.warning : Color(hex: 0x9A6700) + } + + private static var hitPadding: CGFloat { + #if targetEnvironment(macCatalyst) + 4 + #else + 10 + #endif + } +} + +/// The leader row is one combined accessibility element, so the member +/// fold is offered as a named action on it instead of a nested button. +private struct GroupToggleAccessibilityAction: ViewModifier { + let group: SessionGroupSummaryUI? + let onToggle: (() -> Void)? + + func body(content: Content) -> some View { + if let group, group.isExpandable, let onToggle { + content.accessibilityAction(named: group.isExpanded ? Text("Hide members") : Text("Show members")) { + onToggle() + } + } else { + content + } + } +} + /// A running attached job on the row's second line (web `SessionRowSummary` /// job line, without the bar): label, then remaining or percent, then /// elapsed wall time — never an ETA. After 15 minutes without a heartbeat it diff --git a/ios/Hapi/Features/Settings/SettingsView.swift b/ios/Hapi/Features/Settings/SettingsView.swift index 658f29ebe57..1d89d217b4a 100644 --- a/ios/Hapi/Features/Settings/SettingsView.swift +++ b/ios/Hapi/Features/Settings/SettingsView.swift @@ -29,13 +29,15 @@ final class SettingsModel { var hubUrl: String { session.hubUrl } private let session: HubSession + private var registry: HubRegistry? private var started = false init(session: HubSession) { self.session = session } - func start() { + func start(registry: HubRegistry? = nil) { + if let registry { self.registry = registry } guard !started else { return } started = true Task { await self.loadOwnerGate() } @@ -89,7 +91,11 @@ final class SettingsModel { private func loadHubInfo() async { do { - hubInfo = .loaded(try await session.api.health()) + let health = try await session.api.health() + if let hubId = health.hubId { + registry?.setHubId(hubId, for: session.hubUrl) + } + hubInfo = .loaded(health) } catch is CancellationError { // View dismissed mid-flight; nothing to show. } catch { @@ -105,7 +111,9 @@ final class SettingsModel { struct SettingsView: View { @State private var model: SettingsModel @State private var languagePrefs: LanguagePrefs + @AppStorage(ReadingPrefs.autoExpandReasoningKey) private var autoExpandReasoning = false @State private var confirmSignOut = false + @State private var copiedDiagnostics = false @Environment(AppModel.self) private var appModel @Environment(ThemePrefs.self) private var themePrefs @Environment(\.dismiss) private var dismiss @@ -143,7 +151,7 @@ struct SettingsView: View { } } .task { - model.start() + model.start(registry: appModel.registry) PushCoordinator.shared.refreshStatus() } } @@ -252,6 +260,7 @@ struct SettingsView: View { Text(mode.label).tag(mode) } } + Toggle("Auto-expand reasoning", isOn: $autoExpandReasoning) } } @@ -330,6 +339,10 @@ struct SettingsView: View { "Registered hubs", value: "\(push.registeredHubs.count) / \(push.pairedHubs.count)" ) + Toggle("Permission requests", isOn: pushPrefBinding(\.permissionRequest)) + Toggle("Input requests", isOn: pushPrefBinding(\.inputRequest)) + Toggle("Ready for input", isOn: pushPrefBinding(\.ready)) + Toggle("Model errors", isOn: pushPrefBinding(\.modelError)) Button("Re-register push") { PushCoordinator.shared.reregisterAll() } @@ -345,6 +358,19 @@ struct SettingsView: View { } } + private func pushPrefBinding( + _ keyPath: WritableKeyPath + ) -> Binding { + Binding( + get: { PushCoordinator.shared.preferences[keyPath: keyPath] }, + set: { newValue in + var updated = PushCoordinator.shared.preferences + updated[keyPath: keyPath] = newValue + PushCoordinator.shared.updatePreferences(updated) + } + ) + } + private func permissionLabel(_ status: UNAuthorizationStatus) -> String { switch status { case .authorized, .provisional, .ephemeral: @@ -379,6 +405,26 @@ struct SettingsView: View { LabeledContent("App version", value: appVersion) LabeledContent("Protocol version", value: String(ProtocolVersion.supported)) hubRow + Button { + let report = DiagnosticsCoordinator.shared.buildReport( + appModel: appModel, + hubInfo: model.hubInfo + ) + UIPasteboard.general.string = report + copiedDiagnostics = true + Task { @MainActor in + try? await Task.sleep(for: .seconds(1.5)) + copiedDiagnostics = false + } + } label: { + HStack { + Text(copiedDiagnostics ? "Diagnostics copied" : "Copy diagnostics") + Spacer() + Image(systemName: copiedDiagnostics ? "checkmark" : "doc.on.doc") + .foregroundStyle(copiedDiagnostics ? Color.green : Color.secondary) + } + } + .accessibilityIdentifier("settings-copy-diagnostics") PrivacyPolicyLink() } } diff --git a/ios/Hapi/Features/Settings/UsageQuotasSection.swift b/ios/Hapi/Features/Settings/UsageQuotasSection.swift index ad338e6f9a8..69e4e2c6091 100644 --- a/ios/Hapi/Features/Settings/UsageQuotasSection.swift +++ b/ios/Hapi/Features/Settings/UsageQuotasSection.swift @@ -4,6 +4,9 @@ import SwiftUI struct UsageQuotasSection: View { let api: APIClient + /// When opened from a chat session, scope the primary view to that + /// session's machine and tuck other machines into a collapsed disclosure. + var preferredMachineId: String? = nil @State private var response: UsageQuotasResponse? @State private var error: String? @@ -30,35 +33,75 @@ struct UsageQuotasSection: View { } } if let error { - Text(error) - .foregroundStyle(.secondary) + ExpandableQuotaNote(raw: error) } if let response { - let machines = response.machines.filter { - !$0.supported || $0.error?.isEmpty == false || !$0.visibleAccounts.isEmpty - } - if error != nil && !machines.isEmpty { + let plan = QuotaPresentation.plan( + machines: response.machines, + preferredMachineId: preferredMachineId + ) + if error != nil && !plan.isEmpty { Text("Last loaded quotas").font(.caption).foregroundStyle(.secondary) } - if machines.isEmpty && error == nil { + if plan.isEmpty && error == nil { Text("No online machines reported CLI accounts.") .foregroundStyle(.secondary) } - ForEach(machines, id: \.machineId) { machine in - let label = machine.machineName.isEmpty ? machine.machineId : machine.machineName - if !machine.supported || (machine.accounts.isEmpty && machine.error?.contains("RPC method not available") == true) { - Text("\(label): Update the runner to view quotas.") - } else { - if response.machines.count > 1 || machine.error?.isEmpty == false { - Text(label).font(.caption).foregroundStyle(.secondary) + let showMachineHeader = response.machines.count > 1 || preferredMachineId != nil + ForEach(plan.primaryMachines, id: \.machineId) { machine in + machineSection(machine, showHeader: showMachineHeader || machine.error?.isEmpty == false) + } + if !plan.unavailableMachines.isEmpty { + if plan.primaryMachines.isEmpty { + ForEach(plan.unavailableMachines, id: \.machineId) { machine in + unavailableMachineRow(machine, showHeader: showMachineHeader || plan.unavailableMachines.count > 1) } - if let error = machine.error, !error.isEmpty { - Text(error) + } else { + DisclosureGroup { + VStack(alignment: .leading, spacing: 10) { + ForEach(plan.unavailableMachines, id: \.machineId) { machine in + unavailableMachineRow(machine, showHeader: true) + } + } + .padding(.top, 6) + } label: { + unavailableMachinesLabel(count: plan.unavailableMachines.count) } - ForEach(machine.visibleAccounts, id: \.agent) { account in - accountRow(account) + .tint(.secondary) + } + } + if !plan.otherMachines.isEmpty { + let otherPlan = QuotaPresentation.plan(machines: plan.otherMachines, preferredMachineId: nil) + DisclosureGroup { + VStack(alignment: .leading, spacing: 12) { + ForEach(otherPlan.primaryMachines, id: \.machineId) { machine in + machineSection(machine, showHeader: true) + } + if !otherPlan.unavailableMachines.isEmpty { + if otherPlan.primaryMachines.isEmpty { + ForEach(otherPlan.unavailableMachines, id: \.machineId) { machine in + unavailableMachineRow(machine, showHeader: true) + } + } else { + DisclosureGroup { + VStack(alignment: .leading, spacing: 10) { + ForEach(otherPlan.unavailableMachines, id: \.machineId) { machine in + unavailableMachineRow(machine, showHeader: true) + } + } + .padding(.top, 6) + } label: { + unavailableMachinesLabel(count: otherPlan.unavailableMachines.count) + } + .tint(.secondary) + } + } } + .padding(.top, 6) + } label: { + otherMachinesLabel(count: plan.otherMachines.count) } + .tint(.secondary) } } } @@ -66,6 +109,117 @@ struct UsageQuotasSection: View { .task { await load(refresh: false) } } + @ViewBuilder + private func machineSection(_ machine: UsageQuotasResponse.Machine, showHeader: Bool) -> some View { + let label = machine.machineName.isEmpty ? machine.machineId : machine.machineName + let partition = QuotaPresentation.partitionAccounts(machine.visibleAccounts) + let machineError = machine.error?.trimmingCharacters(in: .whitespacesAndNewlines) + let hasMachineError = machineError?.isEmpty == false + + VStack(alignment: .leading, spacing: 10) { + if showHeader { + Text(verbatim: label) + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + } + ForEach(partition.healthy, id: \.agent) { account in + accountRow(account) + } + let issueCount = partition.unavailable.count + (hasMachineError ? 1 : 0) + if issueCount > 0 { + DisclosureGroup { + VStack(alignment: .leading, spacing: 8) { + if let machineError, !machineError.isEmpty { + ExpandableQuotaNote(raw: machineError) + } + ForEach(partition.unavailable, id: \.agent) { account in + unavailableAccountRow(account) + } + } + .padding(.top, 6) + } label: { + unavailableAccountsLabel(count: issueCount) + } + .tint(.secondary) + } + } + } + + @ViewBuilder + private func unavailableMachineRow(_ machine: UsageQuotasResponse.Machine, showHeader: Bool) -> some View { + let label = machine.machineName.isEmpty ? machine.machineId : machine.machineName + VStack(alignment: .leading, spacing: 6) { + if QuotaPresentation.isRunnerUnsupported(machine) { + Text("\(label): Update the runner to view quotas.") + .font(.caption) + .foregroundStyle(.secondary) + } else { + if showHeader { + Text(verbatim: label) + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + } + if let machineError = machine.error, !machineError.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + ExpandableQuotaNote(raw: machineError) + } + let partition = QuotaPresentation.partitionAccounts(machine.visibleAccounts) + ForEach(partition.unavailable, id: \.agent) { account in + unavailableAccountRow(account) + } + } + } + } + + private func unavailableAccountRow(_ account: UsageQuotasResponse.Account) -> some View { + let name = account.agent.isKnown ? account.agent.displayLabel : account.agent.rawValue + let note = statusNote(account) ?? String(localized: "Quota unavailable") + return VStack(alignment: .leading, spacing: 2) { + Text(verbatim: name) + .font(.caption.weight(.medium)) + ExpandableQuotaNote(raw: note) + } + } + + private func unavailableAccountsLabel(count: Int) -> some View { + HStack(spacing: 6) { + Image(systemName: "exclamationmark.circle") + .font(.caption) + .foregroundStyle(.secondary) + Text( + count == 1 + ? String(localized: "1 unavailable") + : String(format: String(localized: "%lld unavailable"), Int64(count)) + ) + .font(.caption) + .foregroundStyle(.secondary) + } + } + + private func unavailableMachinesLabel(count: Int) -> some View { + HStack(spacing: 6) { + Image(systemName: "exclamationmark.circle") + .font(.caption) + .foregroundStyle(.secondary) + Text( + count == 1 + ? String(localized: "1 machine unavailable") + : String(format: String(localized: "%lld machines unavailable"), Int64(count)) + ) + .font(.caption) + .foregroundStyle(.secondary) + } + } + + private func otherMachinesLabel(count: Int) -> some View { + Text( + count == 1 + ? String(localized: "1 other machine") + : String(format: String(localized: "%lld other machines"), Int64(count)) + ) + .font(.caption) + .foregroundStyle(.secondary) + } + private func accountRow(_ account: UsageQuotasResponse.Account) -> some View { VStack(alignment: .leading, spacing: 6) { Text(account.agent.isKnown ? account.agent.displayLabel : account.agent.rawValue) @@ -76,25 +230,53 @@ struct UsageQuotasSection: View { Text(detail).font(.caption).foregroundStyle(.secondary) } ForEach(account.buckets, id: \.id) { bucket in + let pace = QuotaPace.evaluate(bucket) VStack(alignment: .leading, spacing: 4) { Text(bucket.label) Text("\(Int(bucket.remainingPercent.rounded()))% remaining · \(Int(bucket.usedPercent.rounded()))% used") .font(.caption) ProgressView(value: min(100, max(0, bucket.remainingPercent)), total: 100) .accessibilityHidden(true) - if let reset = bucket.resetDate { - Text("Resets \(reset.formatted(.dateTime.month(.abbreviated).day().hour().minute()))") - .font(.caption).foregroundStyle(.secondary) + HStack(spacing: 6) { + if let reset = bucket.resetDate { + Text("Resets \(reset.formatted(.dateTime.month(.abbreviated).day().hour().minute()))") + .font(.caption).foregroundStyle(.secondary) + } + paceTag(pace) } } .accessibilityElement(children: .combine) } if let note = statusNote(account) { - Text(note).font(.caption).foregroundStyle(.secondary) + ExpandableQuotaNote(raw: note) } } } + @ViewBuilder + private func paceTag(_ pace: QuotaPace) -> some View { + switch pace { + case .unknown: + EmptyView() + case .onTrack: + Text("On track") + .font(.caption2.weight(.medium)) + .foregroundStyle(.green) + case .tight: + Text("Pace: tight") + .font(.caption2.weight(.medium)) + .foregroundStyle(.orange) + case .runsOut(let date): + Text("Runs out \(date.formatted(.dateTime.month(.abbreviated).day().hour().minute()))") + .font(.caption2.weight(.medium)) + .foregroundStyle(.orange) + case .reached: + Text("Limit reached") + .font(.caption2.weight(.medium)) + .foregroundStyle(.red) + } + } + private func statusNote(_ account: UsageQuotasResponse.Account) -> String? { if let note = account.note, !note.isEmpty { return note } switch account.status { @@ -141,3 +323,61 @@ struct UsageQuotasSection: View { } } } + +/// Concise quota error/status note with tap-to-expand raw diagnostics only +/// when the original message carries multi-line or truncated detail. +private struct ExpandableQuotaNote: View { + let raw: String + @State private var isExpanded = false + + var body: some View { + let concise = ConciseErrorSummary.concise(raw) + let display = concise.isEmpty ? raw : concise + let hasMore = ConciseErrorSummary.hasExtraDetail(raw: raw, concise: display) + + if hasMore { + VStack(alignment: .leading, spacing: 4) { + Button { + withAnimation(.easeInOut(duration: 0.18)) { + isExpanded.toggle() + } + } label: { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text(verbatim: display) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + Image(systemName: isExpanded ? "chevron.up" : "chevron.down") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.tertiary) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityHint( + isExpanded + ? String(localized: "Hide full details") + : String(localized: "Show full details") + ) + + if isExpanded { + Text(verbatim: raw.trimmingCharacters(in: .whitespacesAndNewlines)) + .font(.caption2.monospaced()) + .foregroundStyle(.secondary) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(8) + .background(.fill.quaternary, in: RoundedRectangle(cornerRadius: 8)) + } + } + } else { + Text(verbatim: display) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + .frame(maxWidth: .infinity, alignment: .leading) + } + } +} diff --git a/ios/Hapi/Features/Terminal/TerminalModel.swift b/ios/Hapi/Features/Terminal/TerminalModel.swift new file mode 100644 index 00000000000..b7502198f76 --- /dev/null +++ b/ios/Hapi/Features/Terminal/TerminalModel.swift @@ -0,0 +1,498 @@ +import Foundation +import HapiClient +import HapiProtocol +import HapiUI +import Observation +import UIKit + +/// Presentation and lifecycle controller for the native CoreText remote terminal. +/// +/// Manages a single Engine.IO/Socket.IO `/terminal` transport serving both: +/// - **Agent PTY** (`agent-terminal:*`) for active PTY sessions (view + drive TUI), and +/// - **Shell Terminal** (`terminal:*`) for an interactive shell in the session's cwd. +/// +/// Switching between Agent and Shell preserves each mode's `TerminalEmulator` buffer +/// and retains the shell `terminalId` in `HubSession` so reopening reattaches with +/// scrollback intact. +@MainActor @Observable +final class TerminalModel { + enum Mode: String, Hashable, CaseIterable { + case agent + case shell + } + + let sessionId: String + let canViewAgentTerminal: Bool + let canOpenShellTerminal: Bool + + private(set) var mode: Mode + private(set) var connectionState: TerminalConnectionState = .idle + private(set) var shellReady: Bool = false + private(set) var shellExitInfo: String? + private(set) var shellErrorMessage: String? + private(set) var terminalTitle: String = "" + private(set) var renderGeneration: UInt64 = 0 + private(set) var scrollOffsetFromBottom: Int = 0 + private(set) var modifiers = TerminalModifierState() + private(set) var isKeyboardFocused: Bool = false + var fontSize: CGFloat { + didSet { + let clamped = max(10, min(22, fontSize.rounded())) + if clamped != fontSize { + fontSize = clamped + return + } + UserDefaults.standard.set(Double(clamped), forKey: Self.fontSizeDefaultsKey) + } + } + + var activeEmulator: TerminalEmulator { + mode == .agent ? agentEmulator : shellEmulator + } + + var isInputEnabled: Bool { + switch mode { + case .agent: + return connectionState == .connected + case .shell: + return connectionState == .connected && shellExitInfo == nil && shellErrorMessage == nil + } + } + + var statusBanner: (message: String, isRestartableShell: Bool)? { + if mode == .shell, let exit = shellExitInfo { + return (exit, true) + } + if mode == .shell, let err = shellErrorMessage { + return (err, true) + } + if case .error(let message) = connectionState { + return (message, false) + } + return nil + } + + @ObservationIgnored private let hub: HubSession + @ObservationIgnored private let agentEmulator = TerminalEmulator(cols: 80, rows: 24) + @ObservationIgnored private let shellEmulator = TerminalEmulator(cols: 80, rows: 24) + @ObservationIgnored private var socketClient: TerminalSocketClient? + @ObservationIgnored private var eventTask: Task? + @ObservationIgnored private var resizeTask: Task? + @ObservationIgnored private var syncFlushTask: Task? + @ObservationIgnored private var currentCols: Int = 80 + @ObservationIgnored private var currentRows: Int = 24 + @ObservationIgnored private var shellTerminalId: String + @ObservationIgnored private var hasCreatedShellForCurrentConnection: Bool = false + @ObservationIgnored private var isAgentSubscribed: Bool = false + @ObservationIgnored private var started: Bool = false + @ObservationIgnored private var backgroundedAt: Date? + + private static let fontSizeDefaultsKey = "settings.terminalFontSize" + + init( + hub: HubSession, + sessionId: String, + canViewAgentTerminal: Bool, + canOpenShellTerminal: Bool, + initialMode: Mode? = nil + ) { + self.hub = hub + self.sessionId = sessionId + self.canViewAgentTerminal = canViewAgentTerminal + self.canOpenShellTerminal = canOpenShellTerminal + self.shellTerminalId = hub.shellTerminalId(for: sessionId) + + if let initialMode { + self.mode = initialMode + } else if canViewAgentTerminal { + self.mode = .agent + } else { + self.mode = .shell + } + + let storedSize = UserDefaults.standard.double(forKey: Self.fontSizeDefaultsKey) + if storedSize >= 10 && storedSize <= 22 { + self.fontSize = CGFloat(storedSize) + } else { + let defaultSize: CGFloat = (UIDevice.current.userInterfaceIdiom == .pad || ProcessInfo.processInfo.isMacCatalystApp) ? 14 : 13 + self.fontSize = defaultSize + } + + wireEmulatorCallbacks() + } + + private func wireEmulatorCallbacks() { + agentEmulator.onReply = { [weak self] reply in + guard let self else { return } + Task { @MainActor [weak self] in + await self?.sendRawToAgent(reply) + } + } + agentEmulator.onTitleChange = { [weak self] title in + guard let self, self.mode == .agent else { return } + self.terminalTitle = title + } + + shellEmulator.onReply = { [weak self] reply in + guard let self else { return } + Task { @MainActor [weak self] in + await self?.sendRawToShell(reply) + } + } + shellEmulator.onTitleChange = { [weak self] title in + guard let self, self.mode == .shell else { return } + self.terminalTitle = title + } + } + + // MARK: - Lifecycle + + func start() { + guard !started else { return } + started = true + connectSocket() + } + + func stop() { + guard started else { return } + started = false + resizeTask?.cancel() + resizeTask = nil + syncFlushTask?.cancel() + syncFlushTask = nil + eventTask?.cancel() + eventTask = nil + + let client = socketClient + socketClient = nil + let wasSubscribed = isAgentSubscribed + isAgentSubscribed = false + hasCreatedShellForCurrentConnection = false + let sid = sessionId + if let client { + Task { + if wasSubscribed { + await client.unsubscribeAgent(sessionId: sid) + } + await client.stop() + } + } + } + + func reconnect() { + stop() + shellErrorMessage = nil + shellExitInfo = nil + started = true + connectSocket() + } + + /// Reconnects proactively after a long app backgrounding (when iOS has + /// likely suspended the TCP socket) while keeping quick copy/paste switches + /// uninterrupted. + func handleScenePhaseChanged(isActive: Bool, isBackground: Bool) { + if isBackground { + backgroundedAt = Date() + return + } + guard isActive, started else { return } + let elapsed = backgroundedAt.map { Date().timeIntervalSince($0) } ?? 0 + backgroundedAt = nil + if elapsed >= 20 || connectionState == .idle || connectionState != .connected { + if case .connecting = connectionState, elapsed < 20 { return } + reconnect() + } + } + + private func connectSocket() { + let auth = hub.authManager + let client = TerminalSocketClient(configuration: .init( + baseURL: hub.baseURL, + tokenProvider: { rejectedToken in + if let rejectedToken { + // Naming the rejected token makes the auth manager refresh + // past it instead of returning the same cached JWT. + return try? await auth.refreshAfterUnauthorized(failedToken: rejectedToken) + } + return try? await auth.validToken() + } + )) + socketClient = client + hasCreatedShellForCurrentConnection = false + isAgentSubscribed = false + + eventTask?.cancel() + eventTask = Task { [weak self] in + let stream = await client.start() + for await event in stream { + guard !Task.isCancelled, let self else { return } + self.handle(event) + } + } + } + + // MARK: - Mode Switching & Shell Management + + func selectMode(_ next: Mode) { + guard next != mode else { return } + if next == .agent && !canViewAgentTerminal { return } + if next == .shell && !canOpenShellTerminal { return } + + let previous = mode + mode = next + scrollOffsetFromBottom = 0 + terminalTitle = activeEmulator.title + renderGeneration = activeEmulator.generation + + guard connectionState == .connected, let client = socketClient else { return } + if previous == .agent && isAgentSubscribed { + isAgentSubscribed = false + Task { await client.unsubscribeAgent(sessionId: sessionId) } + } + activateCurrentMode(on: client) + } + + func restartShell() { + let oldId = shellTerminalId + shellTerminalId = hub.rotateShellTerminalId(for: sessionId) + shellExitInfo = nil + shellErrorMessage = nil + shellReady = false + hasCreatedShellForCurrentConnection = false + shellEmulator.reset() + shellEmulator.resize(cols: currentCols, rows: currentRows) + if mode == .shell { + renderGeneration = shellEmulator.generation + } + + guard let client = socketClient else { + reconnect() + return + } + let sid = sessionId + let newId = shellTerminalId + let cols = currentCols + let rows = currentRows + Task { + await client.closeShell(terminalId: oldId) + await client.createShell(sessionId: sid, terminalId: newId, cols: cols, rows: rows) + } + hasCreatedShellForCurrentConnection = true + } + + // MARK: - Grid Resize + + func handleGridSizeChange(cols: Int, rows: Int) { + let safeCols = max(20, cols) + let safeRows = max(6, rows) + guard safeCols != currentCols || safeRows != currentRows else { return } + currentCols = safeCols + currentRows = safeRows + + agentEmulator.resize(cols: safeCols, rows: safeRows) + shellEmulator.resize(cols: safeCols, rows: safeRows) + renderGeneration = activeEmulator.generation + + resizeTask?.cancel() + resizeTask = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(80)) + guard !Task.isCancelled, let self, self.connectionState == .connected, let client = self.socketClient else { + return + } + if self.mode == .agent { + await client.resizeAgent(sessionId: self.sessionId, cols: safeCols, rows: safeRows) + } else if self.hasCreatedShellForCurrentConnection { + await client.resizeShell(terminalId: self.shellTerminalId, cols: safeCols, rows: safeRows) + } + } + } + + func updateScrollOffset(_ offset: Int) { + scrollOffsetFromBottom = offset + } + + func updateKeyboardFocus(_ focused: Bool) { + isKeyboardFocused = focused + } + + // MARK: - Input Dispatch + + func toggleCtrl() { + modifiers.ctrl.toggle() + } + + func toggleAlt() { + modifiers.alt.toggle() + } + + func sendTypedInput(_ raw: String) { + guard !raw.isEmpty else { return } + let encoded = TerminalInputEncoding.applyModifiers(raw, state: modifiers) + if modifiers.hasActiveModifier { + modifiers = TerminalModifierState() + } + sendDirectSequence(encoded) + } + + func sendSpecialKey(_ key: TerminalSpecialKey) { + let base = key.sequence(applicationCursorKeys: activeEmulator.applicationCursorKeys) + let encoded = TerminalInputEncoding.applyModifiers(base, state: modifiers) + if modifiers.hasActiveModifier { + modifiers = TerminalModifierState() + } + sendDirectSequence(encoded) + } + + func sendDirectSequence(_ sequence: String) { + guard !sequence.isEmpty else { return } + if mode == .agent { + Task { await sendRawToAgent(sequence) } + } else { + Task { await sendRawToShell(sequence) } + } + } + + func sendPaste(_ text: String) { + guard !text.isEmpty else { return } + let encoded = TerminalInputEncoding.encodePaste( + text, + bracketedPasteMode: activeEmulator.bracketedPasteMode + ) + sendDirectSequence(encoded) + } + + func pasteFromClipboard() { + if let text = UIPasteboard.general.string, !text.isEmpty { + sendPaste(text) + } + } + + func clearScreen() { + sendDirectSequence("\u{0c}") + } + + func zoomIn() { + fontSize = min(22, fontSize + 1) + } + + func zoomOut() { + fontSize = max(10, fontSize - 1) + } + + func resetZoom() { + fontSize = (UIDevice.current.userInterfaceIdiom == .pad || ProcessInfo.processInfo.isMacCatalystApp) ? 14 : 13 + } + + func visibleScreenText() -> String { + activeEmulator.visiblePlainText + } + + private func sendRawToShell(_ data: String) async { + guard let client = socketClient, connectionState == .connected else { return } + await client.writeShell(terminalId: shellTerminalId, data: data) + } + + private func sendRawToAgent(_ data: String) async { + guard let client = socketClient, connectionState == .connected else { return } + await client.sendAgentInput(sessionId: sessionId, data: data) + } + + // MARK: - Socket Event Handling + + private func handle(_ event: TerminalSocketEvent) { + switch event { + case .stateChanged(let state): + connectionState = state + if state == .connected, let client = socketClient { + hasCreatedShellForCurrentConnection = false + isAgentSubscribed = false + shellErrorMessage = nil + activateCurrentMode(on: client) + } + + case .shellReady(let terminalId): + guard terminalId == shellTerminalId else { return } + shellReady = true + shellErrorMessage = nil + shellExitInfo = nil + + case .shellOutput(let terminalId, let data): + guard terminalId == shellTerminalId else { return } + shellReady = true + shellEmulator.feed(data) + if mode == .shell { + syncRenderState(for: shellEmulator) + } + + case .shellExit(let terminalId, let code, let signal): + guard terminalId == shellTerminalId else { return } + shellReady = false + hasCreatedShellForCurrentConnection = false + if let signal, !signal.isEmpty { + shellExitInfo = String( + format: String(localized: "Shell exited (%@)"), + signal + ) + } else if let code { + shellExitInfo = String( + format: String(localized: "Shell exited (code %lld)"), + Int64(code) + ) + } else { + shellExitInfo = String(localized: "Shell exited") + } + + case .shellError(let terminalId, let message): + guard terminalId == shellTerminalId else { return } + shellReady = false + hasCreatedShellForCurrentConnection = false + shellErrorMessage = message + + case .agentOutput(let incomingSessionId, let data): + guard incomingSessionId.isEmpty || incomingSessionId == sessionId else { return } + agentEmulator.feed(data) + if mode == .agent { + syncRenderState(for: agentEmulator) + } + } + } + + private func activateCurrentMode(on client: TerminalSocketClient) { + let cols = currentCols + let rows = currentRows + let sid = sessionId + switch mode { + case .agent: + isAgentSubscribed = true + Task { + await client.subscribeAgent(sessionId: sid) + await client.resizeAgent(sessionId: sid, cols: cols, rows: rows) + } + case .shell: + guard !hasCreatedShellForCurrentConnection else { return } + hasCreatedShellForCurrentConnection = true + let tid = shellTerminalId + Task { + await client.createShell(sessionId: sid, terminalId: tid, cols: cols, rows: rows) + } + } + } + + private func syncRenderState(for emulator: TerminalEmulator) { + if emulator.synchronizedOutputActive { + // Safety flush in case a TUI never closes DECSET 2026. + syncFlushTask?.cancel() + syncFlushTask = Task { [weak self, weak emulator] in + try? await Task.sleep(for: .milliseconds(120)) + guard !Task.isCancelled, let self, let emulator else { return } + emulator.flushSynchronizedOutput() + if self.activeEmulator === emulator { + self.renderGeneration = emulator.generation + } + } + } else { + syncFlushTask?.cancel() + renderGeneration = emulator.generation + } + } +} diff --git a/ios/Hapi/Features/Terminal/TerminalQuickKeysBar.swift b/ios/Hapi/Features/Terminal/TerminalQuickKeysBar.swift new file mode 100644 index 00000000000..76626e27890 --- /dev/null +++ b/ios/Hapi/Features/Terminal/TerminalQuickKeysBar.swift @@ -0,0 +1,198 @@ +import HapiClient +import HapiUI +import SwiftUI + +/// Compact 2-row touch virtual key bar floating cleanly above the keyboard. +/// +/// Row 1 keeps essential TUI/shell controls (`Esc`, `Tab`, sticky `Ctrl`, sticky `Alt`, +/// and arrow cluster) pinned in fixed positions. Row 2 offers a horizontally scrollable +/// strip of high-frequency control chords & shell symbols plus a trailing keyboard toggle. +struct TerminalQuickKeysBar: View { + let modifiers: TerminalModifierState + let isKeyboardFocused: Bool + let isEnabled: Bool + let onSpecialKey: (TerminalSpecialKey) -> Void + let onSequence: (String) -> Void + let onToggleCtrl: () -> Void + let onToggleAlt: () -> Void + let onPaste: () -> Void + let onToggleKeyboard: () -> Void + + @Environment(\.hapiTheme) private var theme + + private struct QuickItem: Identifiable { + let id: String + let label: String + let sequence: String + let accessibility: String + } + + private static let secondaryKeys: [QuickItem] = [ + QuickItem(id: "ctrl-c", label: "⌃C", sequence: "\u{03}", accessibility: "Control C"), + QuickItem(id: "ctrl-d", label: "⌃D", sequence: "\u{04}", accessibility: "Control D"), + QuickItem(id: "ctrl-z", label: "⌃Z", sequence: "\u{1a}", accessibility: "Control Z"), + QuickItem(id: "ctrl-l", label: "⌃L", sequence: "\u{0c}", accessibility: "Clear screen"), + QuickItem(id: "shift-tab", label: "⇧Tab", sequence: "\u{1b}[Z", accessibility: "Shift Tab"), + QuickItem(id: "slash", label: "/", sequence: "/", accessibility: "Slash"), + QuickItem(id: "dash", label: "-", sequence: "-", accessibility: "Hyphen"), + QuickItem(id: "pipe", label: "|", sequence: "|", accessibility: "Pipe"), + QuickItem(id: "tilde", label: "~", sequence: "~", accessibility: "Tilde"), + QuickItem(id: "underscore", label: "_", sequence: "_", accessibility: "Underscore"), + QuickItem(id: "home", label: "Home", sequence: "\u{1b}[H", accessibility: "Home"), + QuickItem(id: "end", label: "End", sequence: "\u{1b}[F", accessibility: "End"), + QuickItem(id: "pgup", label: "PgUp", sequence: "\u{1b}[5~", accessibility: "Page Up"), + QuickItem(id: "pgdn", label: "PgDn", sequence: "\u{1b}[6~", accessibility: "Page Down"), + ] + + var body: some View { + VStack(spacing: 6) { + // Row 1: Fixed high-frequency TUI/shell controls + arrow keys. + HStack(spacing: 5) { + keyCap("Esc", accessibility: "Escape") { + onSpecialKey(.escape) + } + keyCap("Tab", accessibility: "Tab") { + onSpecialKey(.tab) + } + modifierCap("Ctrl", active: modifiers.ctrl, accessibility: "Control modifier") { + onToggleCtrl() + } + modifierCap("Alt", active: modifiers.alt, accessibility: "Alt modifier") { + onToggleAlt() + } + Spacer(minLength: 2) + arrowCap("chevron.left", accessibility: "Arrow left") { + onSpecialKey(.arrowLeft) + } + arrowCap("chevron.down", accessibility: "Arrow down") { + onSpecialKey(.arrowDown) + } + arrowCap("chevron.up", accessibility: "Arrow up") { + onSpecialKey(.arrowUp) + } + arrowCap("chevron.right", accessibility: "Arrow right") { + onSpecialKey(.arrowRight) + } + } + + // Row 2: Scrollable chords & shell symbols + Paste + Keyboard toggle. + HStack(spacing: 6) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 5) { + ForEach(Self.secondaryKeys) { item in + keyCap(item.label, accessibility: item.accessibility, compact: true) { + onSequence(item.sequence) + } + } + Button { + HapiHaptics.light() + onPaste() + } label: { + Label("Paste", systemImage: "doc.on.clipboard") + .labelStyle(.titleAndIcon) + .font(.system(size: 12, weight: .medium)) + .padding(.horizontal, 9) + .frame(height: 30) + .background(keyBackground, in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + } + .buttonStyle(.plain) + .foregroundStyle(theme.textPrimary) + .disabled(!isEnabled) + } + } + + Button { + HapiHaptics.light() + onToggleKeyboard() + } label: { + Image(systemName: isKeyboardFocused ? "keyboard.chevron.compact.down" : "keyboard") + .font(.system(size: 14, weight: .medium)) + .frame(width: 34, height: 30) + .background(keyBackground, in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + } + .buttonStyle(.plain) + .foregroundStyle(theme.textSecondary) + .accessibilityLabel(isKeyboardFocused ? String(localized: "Hide keyboard") : String(localized: "Show keyboard")) + } + } + .padding(.horizontal, 8) + .padding(.vertical, 7) + .background(theme.surface) + .overlay(alignment: .top) { + Divider().overlay(theme.divider) + } + } + + private var keyBackground: Color { + theme.isDark ? Color.white.opacity(0.10) : Color.black.opacity(0.06) + } + + private func keyCap( + _ title: String, + accessibility: String, + compact: Bool = false, + action: @escaping () -> Void + ) -> some View { + Button { + HapiHaptics.light() + action() + } label: { + Text(verbatim: title) + .font(.system(size: compact ? 12 : 12.5, weight: .medium, design: .monospaced)) + .lineLimit(1) + .padding(.horizontal, compact ? 8 : 9) + .frame(minWidth: compact ? 30 : 38, minHeight: compact ? 30 : 32) + .background(keyBackground, in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + } + .buttonStyle(.plain) + .foregroundStyle(theme.textPrimary) + .disabled(!isEnabled) + .opacity(isEnabled ? 1 : 0.45) + .accessibilityLabel(accessibility) + } + + private func modifierCap( + _ title: String, + active: Bool, + accessibility: String, + action: @escaping () -> Void + ) -> some View { + Button { + HapiHaptics.light() + action() + } label: { + Text(verbatim: title) + .font(.system(size: 12.5, weight: .semibold, design: .monospaced)) + .lineLimit(1) + .padding(.horizontal, 9) + .frame(minWidth: 38, minHeight: 32) + .background( + active ? theme.accent : keyBackground, + in: RoundedRectangle(cornerRadius: 7, style: .continuous) + ) + } + .buttonStyle(.plain) + .foregroundStyle(active ? Color.white : theme.textPrimary) + .disabled(!isEnabled) + .opacity(isEnabled ? 1 : 0.45) + .accessibilityLabel(accessibility) + .accessibilityAddTraits(active ? .isSelected : []) + } + + private func arrowCap(_ systemImage: String, accessibility: String, action: @escaping () -> Void) -> some View { + Button { + HapiHaptics.light() + action() + } label: { + Image(systemName: systemImage) + .font(.system(size: 13, weight: .semibold)) + .frame(width: 32, height: 32) + .background(keyBackground, in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + } + .buttonStyle(.plain) + .foregroundStyle(theme.textPrimary) + .disabled(!isEnabled) + .opacity(isEnabled ? 1 : 0.45) + .accessibilityLabel(accessibility) + } +} diff --git a/ios/Hapi/Features/Terminal/TerminalScreenView.swift b/ios/Hapi/Features/Terminal/TerminalScreenView.swift new file mode 100644 index 00000000000..c58a370b9ab --- /dev/null +++ b/ios/Hapi/Features/Terminal/TerminalScreenView.swift @@ -0,0 +1,292 @@ +import HapiClient +import HapiUI +import SwiftUI +import UIKit + +/// Native CoreText remote terminal screen pushed from `ChatView`. +/// +/// Offers live Agent PTY view/control (for active PTY sessions) and an +/// interactive Shell terminal in the session's working directory, with zero +/// `WKWebView` overhead, full hardware keyboard + touch quick-key support, +/// scrollback panning, text selection copy, and Send-to-Chat excerpt insertion. +struct TerminalScreenView: View { + @State private var model: TerminalModel + @State private var focusToken = 0 + @State private var dismissKeyboardToken = 0 + @State private var jumpToBottomToken = 0 + @State private var copiedNotice = false + @Environment(\.hapiTheme) private var theme + @Environment(\.dismiss) private var dismiss + @Environment(\.scenePhase) private var scenePhase + + private let onSendExcerptToChat: ((String) -> Void)? + + init( + hub: HubSession, + sessionId: String, + canViewAgentTerminal: Bool, + canOpenShellTerminal: Bool, + initialMode: TerminalModel.Mode? = nil, + onSendExcerptToChat: ((String) -> Void)? = nil + ) { + _model = State(initialValue: TerminalModel( + hub: hub, + sessionId: sessionId, + canViewAgentTerminal: canViewAgentTerminal, + canOpenShellTerminal: canOpenShellTerminal, + initialMode: initialMode + )) + self.onSendExcerptToChat = onSendExcerptToChat + } + + private var showsModePicker: Bool { + model.canViewAgentTerminal && model.canOpenShellTerminal + } + + var body: some View { + VStack(spacing: 0) { + if let banner = model.statusBanner { + statusBannerView(message: banner.message, restartableShell: banner.isRestartableShell) + } + + ZStack(alignment: .bottomTrailing) { + TerminalSurfaceView( + emulator: model.activeEmulator, + generation: model.renderGeneration, + fontSize: model.fontSize, + focusToken: focusToken, + dismissKeyboardToken: dismissKeyboardToken, + jumpToBottomToken: jumpToBottomToken, + onInput: { model.sendTypedInput($0) }, + onPaste: { model.sendPaste($0) }, + onGridSizeChange: { cols, rows in + model.handleGridSizeChange(cols: cols, rows: rows) + }, + onScrollOffsetChange: { model.updateScrollOffset($0) }, + onSendExcerpt: onSendExcerptToChat.map { handler in + { excerpt in + let formatted = TerminalInputEncoding.formatExcerptForChat(excerpt) + guard !formatted.isEmpty else { return } + handler(formatted) + dismiss() + } + }, + onFontSizeChange: { model.fontSize = $0 }, + onFocusChange: { model.updateKeyboardFocus($0) } + ) + .frame(maxWidth: .infinity, maxHeight: .infinity) + + if model.scrollOffsetFromBottom > 0 { + Button { + HapiHaptics.light() + jumpToBottomToken += 1 + } label: { + Label("Latest", systemImage: "arrow.down") + .font(.caption.weight(.semibold)) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background(.ultraThinMaterial, in: Capsule()) + .overlay(Capsule().stroke(theme.divider, lineWidth: 0.5)) + } + .buttonStyle(.plain) + .foregroundStyle(theme.textPrimary) + .padding(12) + } + + if copiedNotice { + Text("Copied") + .font(.caption.weight(.semibold)) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(.ultraThinMaterial, in: Capsule()) + .padding(12) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + .transition(.opacity) + } + } + + TerminalQuickKeysBar( + modifiers: model.modifiers, + isKeyboardFocused: model.isKeyboardFocused, + isEnabled: model.isInputEnabled, + onSpecialKey: { model.sendSpecialKey($0) }, + onSequence: { model.sendDirectSequence($0) }, + onToggleCtrl: { model.toggleCtrl() }, + onToggleAlt: { model.toggleAlt() }, + onPaste: { model.pasteFromClipboard() }, + onToggleKeyboard: { + if model.isKeyboardFocused { + dismissKeyboardToken += 1 + } else { + focusToken += 1 + } + } + ) + } + .background(theme.background) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .principal) { + headerContent + } + ToolbarItem(placement: .topBarTrailing) { + Menu { + Button { + let text = model.visibleScreenText() + if !text.isEmpty { + UIPasteboard.general.string = text + showCopiedBanner() + } + } label: { + Label("Copy Screen", systemImage: "doc.on.doc") + } + if let onSendExcerptToChat { + Button { + let formatted = TerminalInputEncoding.formatExcerptForChat(model.visibleScreenText()) + guard !formatted.isEmpty else { return } + onSendExcerptToChat(formatted) + dismiss() + } label: { + Label("Send Screen to Chat", systemImage: "text.bubble") + } + } + Divider() + Button { + model.zoomIn() + } label: { + Label("Larger Text", systemImage: "textformat.size.larger") + } + Button { + model.zoomOut() + } label: { + Label("Smaller Text", systemImage: "textformat.size.smaller") + } + Button { + model.resetZoom() + } label: { + Label("Reset Text Size", systemImage: "textformat.size") + } + Divider() + Button { + model.clearScreen() + } label: { + Label("Clear Screen", systemImage: "sparkles") + } + if model.mode == .shell { + Button { + model.restartShell() + } label: { + Label("Restart Shell", systemImage: "arrow.counterclockwise") + } + } + Button { + model.reconnect() + } label: { + Label("Reconnect", systemImage: "arrow.triangle.2.circlepath") + } + } label: { + Image(systemName: "ellipsis.circle") + } + .accessibilityLabel("Terminal actions") + } + } + .onAppear { + model.start() + } + .onDisappear { + model.stop() + } + .onChange(of: scenePhase) { _, phase in + model.handleScenePhaseChanged( + isActive: phase == .active, + isBackground: phase == .background + ) + } + } + + @ViewBuilder + private var headerContent: some View { + HStack(spacing: 8) { + connectionDot + if showsModePicker { + Picker("Terminal Mode", selection: Binding( + get: { model.mode }, + set: { model.selectMode($0) } + )) { + Text("Agent").tag(TerminalModel.Mode.agent) + Text("Shell").tag(TerminalModel.Mode.shell) + } + .pickerStyle(.segmented) + .frame(maxWidth: 168) + } else { + Text(model.terminalTitle.isEmpty ? String(localized: "Terminal") : model.terminalTitle) + .font(.headline) + .lineLimit(1) + } + } + } + + private var connectionDot: some View { + let color: Color + let label: String + switch model.connectionState { + case .connected: + color = theme.success + label = String(localized: "Connected") + case .connecting: + color = theme.warning + label = String(localized: "Connecting") + case .idle: + color = theme.textHint + label = String(localized: "Disconnected") + case .error: + color = theme.danger + label = String(localized: "Connection error") + } + return Circle() + .fill(color) + .frame(width: 8, height: 8) + .accessibilityLabel(label) + } + + private func statusBannerView(message: String, restartableShell: Bool) -> some View { + HStack(spacing: 10) { + Image(systemName: "exclamationmark.triangle.fill") + .font(.caption) + .foregroundStyle(theme.warning) + Text(message) + .font(.caption) + .foregroundStyle(theme.textPrimary) + .lineLimit(2) + Spacer() + Button(restartableShell ? String(localized: "Restart Shell") : String(localized: "Reconnect")) { + if restartableShell { + model.restartShell() + } else { + model.reconnect() + } + } + .font(.caption.weight(.semibold)) + .buttonStyle(.bordered) + .controlSize(.mini) + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background(theme.surface) + .overlay(alignment: .bottom) { + Divider().overlay(theme.divider) + } + } + + private func showCopiedBanner() { + withAnimation(.easeInOut(duration: 0.15)) { + copiedNotice = true + } + Task { + try? await Task.sleep(for: .seconds(1.2)) + withAnimation(.easeInOut(duration: 0.2)) { + copiedNotice = false + } + } + } +} diff --git a/ios/Hapi/HapiApp.swift b/ios/Hapi/HapiApp.swift index 823fbbc9cd7..b23c68b2941 100644 --- a/ios/Hapi/HapiApp.swift +++ b/ios/Hapi/HapiApp.swift @@ -12,6 +12,10 @@ struct HapiApp: App { private let log = Logger(subsystem: "run.hapi.companion", category: "app") + init() { + DiagnosticsCoordinator.shared.start() + } + var body: some Scene { WindowGroup { RootView() diff --git a/ios/Hapi/Models/ChatSession.swift b/ios/Hapi/Models/ChatSession.swift index 8d815c04adb..0770352f2f5 100644 --- a/ios/Hapi/Models/ChatSession.swift +++ b/ios/Hapi/Models/ChatSession.swift @@ -48,6 +48,7 @@ final class ChatSession { @ObservationIgnored var onSessionRemoved: (@MainActor () -> Void)? private let baseURL: URL + private let api: APIClient private let authManager: AuthManager private let windows: MessageWindowControllers private let sessionStore: SessionListStore @@ -68,6 +69,7 @@ final class ChatSession { init( sessionId: String, baseURL: URL, + api: APIClient, authManager: AuthManager, windows: MessageWindowControllers, sessionStore: SessionListStore, @@ -80,6 +82,7 @@ final class ChatSession { ) { self.sessionId = sessionId self.baseURL = baseURL + self.api = api self.authManager = authManager self.windows = windows self.sessionStore = sessionStore @@ -161,6 +164,7 @@ final class ChatSession { private func startSessionSSE() { let auth = authManager + let api = self.api let configuration = SSEClientConfiguration( baseUrl: baseURL, tokenProvider: { @@ -169,7 +173,10 @@ final class ChatSession { // pipe in `HubSession`, which tears this session down too. try? await auth.validToken() }, - scope: .session(sessionId) + scope: .session(sessionId), + foregroundLivenessProbe: { subscriptionId in + await HubSession.probeForegroundLiveness(api: api, subscriptionId: subscriptionId) + } ) let client = SSEClient(configuration: configuration, pathObserver: NWPathObserver()) sse = client @@ -210,7 +217,8 @@ final class ChatSession { private func route(_ event: SyncEvent) async { switch event { - case .messageReceived, .messagesConsumed, .messageCancelled, + case .messageReceived, .messagesConsumed, .messagesIndeterminate, + .messagesRequeued, .messageCancelled, .messagesInvalidated, .scheduledMatured: // Message-stream family → the open window (the controller // re-checks the session id defensively). diff --git a/ios/Hapi/Models/DiagnosticsCoordinator.swift b/ios/Hapi/Models/DiagnosticsCoordinator.swift new file mode 100644 index 00000000000..8df46c05249 --- /dev/null +++ b/ios/Hapi/Models/DiagnosticsCoordinator.swift @@ -0,0 +1,148 @@ +import Foundation +import HapiClient +import HapiProtocol +#if canImport(MetricKit) +import MetricKit +#endif +import UIKit +import UserNotifications + +/// App-level diagnostic aggregator: subscribes to MetricKit hang/crash/hitch +/// diagnostics and assembles a redacted diagnostic report for Settings → Copy +/// Diagnostics without ever leaking tokens, hostnames, or conversation text. +@MainActor +final class DiagnosticsCoordinator: NSObject { + static let shared = DiagnosticsCoordinator() + + private var started = false + private(set) var hangCount = 0 + private(set) var crashCount = 0 + private(set) var lastScrollHitchRatio: String? + + private override init() { + super.init() + } + + func start() { + guard !started else { return } + started = true + #if canImport(MetricKit) + MXMetricManager.shared.add(self) + #endif + } + + func buildReport(appModel: AppModel, hubInfo: SettingsModel.HubInfoState) -> String { + let session = appModel.session + let push = PushCoordinator.shared + let bundle = Bundle.main + let short = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "?" + let build = bundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "?" + let appVersion = "\(short) (\(build))" + + #if targetEnvironment(macCatalyst) + let platform = "Mac Catalyst" + #else + let platform = UIDevice.current.userInterfaceIdiom == .pad ? "iPadOS" : "iOS" + #endif + let osVersion = ProcessInfo.processInfo.operatingSystemVersionString + + let hubHealthStatus: String + switch hubInfo { + case .loading: + hubHealthStatus = "loading" + case .loaded(let health): + hubHealthStatus = "\(health.status) (protocol v\(health.protocolVersion))" + case .failed(let message): + hubHealthStatus = "unreachable (\(message ?? "unknown"))" + } + + let sseStateLabel: String + if let state = session?.connectionState { + switch state { + case .idle: sseStateLabel = "idle" + case .connecting: sseStateLabel = "connecting" + case .connected: sseStateLabel = "connected" + case .backoff(let attempt): sseStateLabel = "backoff(attempt=\(attempt))" + case .suspended: sseStateLabel = "suspended" + } + } else { + sseStateLabel = "none" + } + + let resumeLabel: String? = session?.lastResumeVerdict.map { verdict in + switch verdict { + case .ok: "ok" + case .gap: "gap" + } + } + + let pushAuth: String + switch push.authorizationStatus { + case .authorized: pushAuth = "authorized" + case .provisional: pushAuth = "provisional" + case .ephemeral: pushAuth = "ephemeral" + case .denied: pushAuth = "denied" + case .notDetermined: pushAuth = "notDetermined" + @unknown default: pushAuth = "unknown" + } + + let onlineMachines = session?.machineStore.machines.filter(\.active).count ?? 0 + let snapshot = DiagnosticSnapshot( + appVersion: appVersion, + osVersion: osVersion, + platform: platform, + protocolVersion: ProtocolVersion.supported, + pairedHubCount: appModel.hubs.count, + activeHubRedacted: session.map { DiagnosticRedactor.redactHubOrigin($0.hubUrl) }, + hubHealthStatus: hubHealthStatus, + globalSSEState: sseStateLabel, + lastResumeVerdict: resumeLabel, + sessionCount: session?.sessionStore.sessions.count ?? 0, + onlineMachineCount: onlineMachines, + activeChatOpen: session?.openChatSessionId != nil, + activeChatReconnecting: session?.isActiveChatReconnecting ?? false, + pushAuthorization: pushAuth, + pushRegisteredHubCount: push.registeredHubs.count, + pushLastProblem: push.lastRegistrationProblem, + hangCount: hangCount, + crashCount: crashCount, + scrollHitchRatio: lastScrollHitchRatio, + recentEvents: DiagnosticEventLog.shared.snapshot() + ) + return snapshot.formattedReport() + } +} + +#if canImport(MetricKit) +extension DiagnosticsCoordinator: MXMetricManagerSubscriber { + nonisolated func didReceive(_ payloads: [MXDiagnosticPayload]) { + var hangs = 0 + var crashes = 0 + for payload in payloads { + hangs += payload.hangDiagnostics?.count ?? 0 + crashes += payload.crashDiagnostics?.count ?? 0 + } + guard hangs > 0 || crashes > 0 else { return } + DiagnosticEventLog.shared.record( + category: "metrickit", + "Received diagnostics: hangs=\(hangs), crashes=\(crashes)" + ) + Task { @MainActor in + self.hangCount += hangs + self.crashCount += crashes + } + } + + nonisolated func didReceive(_ payloads: [MXMetricPayload]) { + for payload in payloads { + if let hitch = payload.animationMetrics?.scrollHitchTimeRatio { + let formatted = String(format: "%.2f ms/s", hitch.value) + DiagnosticEventLog.shared.record(category: "metrickit", "Scroll hitch ratio: \(formatted)") + Task { @MainActor in + self.lastScrollHitchRatio = formatted + } + } + } + } +} +#endif diff --git a/ios/Hapi/Models/HubSession.swift b/ios/Hapi/Models/HubSession.swift index 86430ca4096..2ed68bac98b 100644 --- a/ios/Hapi/Models/HubSession.swift +++ b/ios/Hapi/Models/HubSession.swift @@ -34,6 +34,8 @@ final class HubSession { /// Per-session scratchlist cache (A-M4b), fed the `scratchlistUpdatedAt` /// invalidation signal from the session-patch application below. let scratchlist: ScratchlistStore + /// Per-session inline diff review comment drafts (persisted across files). + let diffReview: DiffReviewStore /// `POST /api/visibility` reporter (M3b): fed every pipe's handshake /// subscription id, flipped with the scene phase. let visibility: VisibilityReporter @@ -48,6 +50,7 @@ final class HubSession { /// foreground-suppression rule (Android `openChatSessionId`): a push for /// the chat the user is looking at is pure noise. private(set) var openChatSessionId: String? + var isActiveChatReconnecting: Bool { activeChat?.reconnectNotice.isVisible ?? false } struct SessionRemoval: Equatable { let sessionId: String @@ -70,6 +73,11 @@ final class HubSession { /// back to pairing with a banner. @ObservationIgnored var onTerminalAuthFailure: (@MainActor () -> Void)? + /// Stable per-hub, per-namespace persistence scope for session-group UI state. + var groupStateScope: String { + "\(hubUrl):\(readNamespace ?? "default")" + } + @ObservationIgnored private let router: SyncEventRouter @ObservationIgnored private var sse: SSEClient? @ObservationIgnored private var consumeTask: Task? @@ -86,6 +94,9 @@ final class HubSession { /// way). Keyed by session id; never reused across hubs because the whole /// `HubSession` — cursors included — dies on hub switch. @ObservationIgnored private var chatCursors: [String: String] = [:] + /// Stable per-session shell `terminalId`s surviving Terminal screen close + /// and reopen so the hub replays its retained 256 KB PTY scrollback buffer. + @ObservationIgnored private var shellTerminalIds: [String: String] = [:] init?( hubUrl: String, @@ -125,6 +136,7 @@ final class HubSession { ) let scratchlist = ScratchlistStore(api: api) self.scratchlist = scratchlist + self.diffReview = DiffReviewStore(scope: "\(hubUrl):\(readNamespace ?? "default")") // `scratchlistUpdatedAt` on a session patch (either SSE pipe — both // route through this store) is a bare refetch trigger for that // session's scratchlist (A-M4b). @@ -137,6 +149,7 @@ final class HubSession { self.router = SyncEventRouter(sessions: sessionStore, machines: machineStore) sessionStore.onSessionRemoved = { [weak self] sessionId in guard let self else { return } + self.shellTerminalIds.removeValue(forKey: sessionId) if self.composerHandoff?.sourceSessionId == sessionId { return } // A resume may merge/delete the source before its HTTP response // arrives. Let the upload handoff navigate instead of popping the @@ -160,6 +173,7 @@ final class HubSession { ChatSession( sessionId: sessionId, baseURL: baseURL, + api: api, authManager: authManager, windows: windows, sessionStore: sessionStore, @@ -231,6 +245,28 @@ final class HubSession { return interactor } + // MARK: - Remote terminal identity + + /// Returns the retained shell `terminalId` for `sessionId`, creating one + /// on first use so reopening the Terminal screen reattaches to the same + /// hub PTY and replays its buffered scrollback. + func shellTerminalId(for sessionId: String) -> String { + if let existing = shellTerminalIds[sessionId] { + return existing + } + let fresh = UUID().uuidString.lowercased() + shellTerminalIds[sessionId] = fresh + return fresh + } + + /// Replaces the cached shell `terminalId` with a fresh identifier (used by + /// "Restart Shell" after closing the previous PTY). + func rotateShellTerminalId(for sessionId: String) -> String { + let fresh = UUID().uuidString.lowercased() + shellTerminalIds[sessionId] = fresh + return fresh + } + // MARK: - Lifecycle (driven by AppModel from scenePhase) /// First call starts the global SSE subscription; later calls resume a @@ -280,10 +316,12 @@ final class HubSession { let sessionStore = sessionStore let machineStore = machineStore let lastSeenStore = lastSeenStore + let windows = windows Task { await sessionStore.flushPersistence() await machineStore.flushPersistence() await lastSeenStore.flushPersistence() + await windows.flushPersistence() } } @@ -291,6 +329,7 @@ final class HubSession { func shutdown() { isShutDown = true composerHandoff = nil + shellTerminalIds.removeAll() readStateTask?.cancel() lastSeenStore.shutdown() onTerminalAuthFailure = nil @@ -300,6 +339,8 @@ final class HubSession { openChatSessionId = nil consumeTask?.cancel() consumeTask = nil + let windows = windows + Task { await windows.flushPersistence() } if let sse { self.sse = nil Task { await sse.stop() } @@ -311,6 +352,7 @@ final class HubSession { private func startGlobalSSE() { let auth = authManager + let api = self.api let configuration = SSEClientConfiguration( baseUrl: baseURL, tokenProvider: { [weak self] in @@ -331,7 +373,10 @@ final class HubSession { return nil } }, - scope: .global + scope: .global, + foregroundLivenessProbe: { subscriptionId in + await Self.probeForegroundLiveness(api: api, subscriptionId: subscriptionId) + } ) let client = SSEClient(configuration: configuration, pathObserver: NWPathObserver()) sse = client @@ -368,4 +413,25 @@ final class HubSession { shutdown() callback?() } + + nonisolated static func probeForegroundLiveness( + api: APIClient, + subscriptionId: String? + ) async -> Bool { + if let subscriptionId, !subscriptionId.isEmpty { + do { + try await api.setVisibility(subscriptionId: subscriptionId, visibility: .visible) + return true + } catch let error as APIError where error.status == 404 { + // Hub already dropped this subscription — tear down and reconnect immediately. + return false + } catch let error as APIError where error.status == 503 { + // Visibility tracker unavailable on hub; fall back to /health. + return (try? await api.health()) != nil + } catch { + return false + } + } + return (try? await api.health()) != nil + } } diff --git a/ios/Hapi/Models/PushCoordinator.swift b/ios/Hapi/Models/PushCoordinator.swift index 7e813bc55b7..7464d7140b1 100644 --- a/ios/Hapi/Models/PushCoordinator.swift +++ b/ios/Hapi/Models/PushCoordinator.swift @@ -1,5 +1,6 @@ import Foundation import HapiClient +import HapiProtocol import Observation import OSLog import Security @@ -85,6 +86,10 @@ final class PushCoordinator: NSObject { private(set) var registeredHubs: Set = [] /// Human-readable failure of the latest APNs/registration attempt. private(set) var lastRegistrationProblem: String? + /// Per-device push event filter persisted locally and synced to each hub. + let preferencesStore = PushNotificationPrefs() + + var preferences: PushNotificationPreferences { preferencesStore.preferences } /// Paired hub origins (for the Settings "x of y" count). Snapshot, not /// observable — refreshed whenever the observable fields change. @@ -92,6 +97,7 @@ final class PushCoordinator: NSObject { @ObservationIgnored private var environment: Environment? @ObservationIgnored private var apnsTokenHex: String? + @ObservationIgnored private var preferencesSyncTask: Task? @ObservationIgnored private let log = Logger(subsystem: "run.hapi.companion", category: "push") // MARK: - Wiring (AppModel) @@ -178,6 +184,24 @@ final class PushCoordinator: NSObject { } } + /// Updates per-device push event preferences and re-registers every paired + /// hub (debounced so rapid switch flips coalesce into one round-trip). + func updatePreferences(_ updated: PushNotificationPreferences) { + guard preferencesStore.preferences != updated else { return } + preferencesStore.setPreferences(updated) + preferencesSyncTask?.cancel() + guard let hubs = environment?.registry.hubs, !hubs.isEmpty else { return } + preferencesSyncTask = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(200)) + guard !Task.isCancelled, let self else { return } + if self.apnsTokenHex != nil { + await self.registerHubs(hubs) + } else if self.authorizationStatus == .authorized || self.authorizationStatus == .provisional { + UIApplication.shared.registerForRemoteNotifications() + } + } + } + // MARK: - APNs callbacks (AppDelegate) func handleAPNsToken(_ deviceToken: Data) { @@ -234,6 +258,7 @@ final class PushCoordinator: NSObject { lastRegistrationProblem = String(localized: "Could not store the push key.") return } + let currentPreferences = preferencesStore.preferences for hub in hubs { // Re-check the roster per hub: a sign-out can land mid-loop. guard environment.registry.hubs.contains(hub) else { continue } @@ -245,7 +270,15 @@ final class PushCoordinator: NSObject { ) let api = APIClient(baseURL: url, authManager: auth, performer: environment.performer) do { - try await api.registerDevice(token: token, deviceId: deviceId, pushKey: pushKey.base64) + let response = try await api.registerDevice( + token: token, + deviceId: deviceId, + pushKey: pushKey.base64, + preferences: currentPreferences + ) + if let hubId = response.hubId { + environment.registry.setHubId(hubId, for: hub) + } registeredHubs.insert(hub) } catch { registeredHubs.remove(hub) @@ -337,6 +370,12 @@ extension PushCoordinator: UNUserNotificationCenterDelegate { if let payload = payload(from: notification.request.content.userInfo), let openId = environment?.openChatSessionId(), openId == payload.sessionId { + if let registry = environment?.registry, + let targetHub = Self.directTapTarget(forHubId: payload.hubId, registry: registry), + let activeHub = registry.activeHub, + targetHub != activeHub { + return [.banner, .list, .sound] + } return [] } return [.banner, .list, .sound] @@ -353,11 +392,11 @@ extension PushCoordinator: UNUserNotificationCenterDelegate { } switch response.actionIdentifier { case UNNotificationDefaultActionIdentifier: - await openSession(payload.sessionId) + await openSession(payload) case ActionID.allow: guard payload.type == .permissionRequest, payload.supportsActions, let requestId = payload.requestId else { return } - let outcome = await actionRunner().approve( + let outcome = await actionRunner(preferredHubId: payload.hubId).approve( sessionId: payload.sessionId, requestId: requestId ) @@ -365,7 +404,7 @@ extension PushCoordinator: UNUserNotificationCenterDelegate { case ActionID.deny: guard payload.type == .permissionRequest, payload.supportsActions, let requestId = payload.requestId else { return } - let outcome = await actionRunner().deny( + let outcome = await actionRunner(preferredHubId: payload.hubId).deny( sessionId: payload.sessionId, requestId: requestId ) @@ -375,7 +414,7 @@ extension PushCoordinator: UNUserNotificationCenterDelegate { let text = (response as? UNTextInputNotificationResponse)? .userText.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" guard !text.isEmpty else { return } - let outcome = await actionRunner().sendMessage( + let outcome = await actionRunner(preferredHubId: payload.hubId).sendMessage( sessionId: payload.sessionId, text: text, localId: UUID().uuidString @@ -386,38 +425,63 @@ extension PushCoordinator: UNUserNotificationCenterDelegate { } } - /// Tap-through. The payload carries no hub, so with several paired hubs - /// a session the active list does not know is located first (active hub - /// first, like the actions). A miss or an unreachable owner falls back - /// to the active hub. - private func openSession(_ sessionId: String) async { + /// Tap-through. When the encrypted payload includes `hubId` and it maps to + /// a paired hub, switches directly in O(1) with zero network probing. + /// Older hubs (no `hubId`) fall back to probing paired hubs (active first). + private func openSession(_ payload: PushPayload) async { guard let environment else { return } + if let directHub = Self.directTapTarget(forHubId: payload.hubId, registry: environment.registry) { + environment.openSession(payload.sessionId, directHub) + return + } var owner: String? - if hubsActiveFirst().count > 1, !environment.activeHubKnowsSession(sessionId), - case .success(let hubUrl) = await actionRunner().locate(sessionId: sessionId) { + if hubsActiveFirst().count > 1, !environment.activeHubKnowsSession(payload.sessionId), + case .success(let hubUrl) = await actionRunner(preferredHubId: nil).locate(sessionId: payload.sessionId) { owner = hubUrl } - environment.openSession(sessionId, owner) + environment.openSession(payload.sessionId, owner) } - private func actionRunner() -> PushActionRunner { - PushActionRunner( - hubs: hubsActiveFirst(), + private func actionRunner(preferredHubId: String?) -> PushActionRunner { + let hubs: [String] + if let registry = environment?.registry { + hubs = Self.candidateHubs(forHubId: preferredHubId, registry: registry) + } else { + hubs = [] + } + return PushActionRunner( + hubs: hubs, credentialStore: environment?.credentialStore ?? InMemoryCredentialStore(), performer: environment?.performer ?? URLSessionHTTPPerformer.shared ) } - /// Paired hub origins with the active hub first — the try-order for - /// hub-resolving actions (the payload carries no hub URL; for the - /// overwhelmingly common single-hub setup the first try is the only try). - private func hubsActiveFirst() -> [String] { - guard let registry = environment?.registry else { return [] } + /// Direct O(1) tap-through target when `hubId` resolves to a paired hub. + static func directTapTarget(forHubId hubId: String?, registry: HubRegistry) -> String? { + hubId.flatMap { registry.hubUrl(forHubId: $0) } + } + + /// Hub try-order for push actions. When `hubId` matches paired hub(s), + /// returns only those hub(s) (active first) so actions hit the owning hub + /// directly without probing unrelated hubs. Falls back to every paired hub + /// (active first) when `hubId` is absent or not yet cached. + static func candidateHubs(forHubId hubId: String?, registry: HubRegistry) -> [String] { + if let hubId { + let matched = registry.hubUrls(forHubId: hubId) + if !matched.isEmpty { return matched } + } let hubs = registry.hubs guard let active = registry.activeHub else { return hubs } return [active] + hubs.filter { $0 != active } } + /// Paired hub origins with the active hub first — the fallback try-order + /// when a push carries no `hubId`. + private func hubsActiveFirst() -> [String] { + guard let registry = environment?.registry else { return [] } + return Self.candidateHubs(forHubId: nil, registry: registry) + } + /// The Android workers flip the notification through pending → done / /// failed states; iOS dismisses the notification the moment an action is /// chosen, so only the failures need a surface — a local notice, because diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 55b67b8486b..8476a536398 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -1548,6 +1548,29 @@ } } }, + "%lld in a worktree: check for unmerged changes first." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 件が worktree 内です。未マージの変更がないか先に確認してください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В worktree: %lld. Сначала проверьте, нет ли неслитых изменений." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 个在 worktree 中:请先确认没有未合并的改动。" + } + } + } + }, "%lld lines" : { "extractionState" : "manual", "localizations" : { @@ -1571,6 +1594,70 @@ } } }, + "%lld members" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld member" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld members" + } + } + } + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "メンバー %lld 人" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "участников: %lld" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 个成员" + } + } + } + }, + "%lld members are running. The leader is still running; review the group and dissolve it again." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "メンバー %lld 件が実行中です。リーダーは実行中のままです。グループを確認してもう一度解散してください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Участников в работе: %lld. Ведущая сессия продолжает работать; проверьте группу и распустите её снова." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "还有 %lld 个成员在运行。leader 仍在运行,请检查分组后重新解散。" + } + } + } + }, "%lld new messages ↓" : { "extractionState" : "manual", "localizations" : { @@ -1647,6 +1734,52 @@ } } }, + "%lld of %lld members not archived. The leader is still running." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "メンバー %2$lld 件のうち %1$lld 件をアーカイブできませんでした。リーダーは実行中のままです。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не архивировано участников: %1$lld из %2$lld. Ведущая сессия продолжает работать." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%2$lld 个成员中有 %1$lld 个未能归档。leader 仍在运行。" + } + } + } + }, + "%lld of %lld sessions not archived." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%2$lld 件中 %1$lld 件のセッションをアーカイブできませんでした。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не архивировано сессий: %1$lld из %2$lld." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$lld/%2$lld 个会话未归档。" + } + } + } + }, "%lld other tools" : { "extractionState" : "manual", "localizations" : { @@ -1939,525 +2072,732 @@ } } }, - "%lld tool calls" : { + "%lld still working." : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ツール呼び出し %lld 回" + "value" : "%lld 件がまだ作業中です。" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Вызовы инструментов: %lld" + "value" : "Ещё работают: %lld." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "%lld 次工具调用" + "value" : "%lld 个仍在工作。" } } } }, - "%lld tools" : { + "%lld tool calls" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ツール %lld 件" + "value" : "ツール呼び出し %lld 回" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Инструменты: %lld" + "value" : "Вызовы инструментов: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "%lld 个工具" + "value" : "%lld 次工具调用" } } } }, - "%lld web requests" : { + "%lld tools" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Web リクエスト %lld 件" + "value" : "ツール %lld 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Веб-запросы: %lld" + "value" : "Инструменты: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "%lld 次网络请求" + "value" : "%lld 个工具" } } } }, - "● Recording… %@" : { + "%lld unread" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "● 録音中… %@" + "value" : "未読 %lld 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "● Запись… %@" + "value" : "непрочитано: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "● 录音中… %@" + "value" : "%lld 个未读" } } } }, - "✓ Approved" : { + "%lld waiting" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "✓ 承認済み" + "value" : "対応待ち %lld 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "✓ Одобрено" + "value" : "ждут ответа: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "✓ 已批准" + "value" : "%lld 个待处理" } } } }, - "✕ Denied" : { + "%lld waiting for your answer." : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "✕ 拒否済み" + "value" : "%lld 件があなたの回答を待っています。" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "✕ Отклонено" + "value" : "Ждут вашего ответа: %lld." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "✕ 已拒绝" + "value" : "%lld 个在等待你的回复。" } } } }, - "0 tokens" : { + "%lld web requests" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "0 トークン" + "value" : "Web リクエスト %lld 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "0 токенов" + "value" : "Веб-запросы: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "0 Token" + "value" : "%lld 次网络请求" } } } }, - "1 agent step" : { + "%lld working" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "エージェントのステップ 1 件" + "value" : "実行中 %lld 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 шаг агента" + "value" : "работают: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 个代理步骤" + "value" : "%lld 个运行中" } } } }, - "1 command" : { + "Archive could not be confirmed" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "コマンド 1 件" + "value" : "アーカイブを確認できませんでした" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 команда" + "value" : "Не удалось подтвердить архивирование" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 条命令" + "value" : "归档尚未确认完成" } } } }, - "1 edit" : { + "Archive the %lld running sessions of the group led by “%@”?" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "編集 1 件" + "value" : "「%2$@」が率いるグループの実行中セッション %1$lld 件をアーカイブしますか?" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 правка" + "value" : "Архивировать запущенные сессии (%1$lld) группы, которую ведёт «%2$@»?" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 次修改" + "value" : "归档由“%2$@”带领的分组中 %1$lld 个运行中的会话?" } } } }, - "1 finding" : { + "Could not check the group for new members. The leader is still running." : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "指摘 1 件" + "value" : "グループに新しいメンバーがいるか確認できませんでした。リーダーは実行中のままです。" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 замечание" + "value" : "Не удалось проверить, появились ли в группе новые участники. Ведущая сессия продолжает работать." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 条发现" + "value" : "无法确认分组是否有新成员。leader 仍在运行。" } } } }, - "1 new message ↓" : { + "Dissolve group" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "新着メッセージ 1 件 ↓" + "value" : "グループを解散" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 новое сообщение ↓" + "value" : "Распустить группу" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 条新消息 ↓" + "value" : "解散分组" } } } }, - "1 note" : { + "● Recording… %@" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "メモ 1 件" + "value" : "● 録音中… %@" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 заметка" + "value" : "● Запись… %@" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 条笔记" + "value" : "● 录音中… %@" } } } }, - "1 other tool" : { + "✓ Approved" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "その他のツール 1 件" + "value" : "✓ 承認済み" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 другой инструмент" + "value" : "✓ Одобрено" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 个其他工具" + "value" : "✓ 已批准" } } } }, - "1 queued message" : { + "✕ Denied" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "キュー内のメッセージ 1 件" + "value" : "✕ 拒否済み" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 сообщение в очереди" + "value" : "✕ Отклонено" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 条排队消息" + "value" : "✕ 已拒绝" } } } }, - "1 read" : { + "0 tokens" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "読み取り 1 回" + "value" : "0 トークン" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 чтение" + "value" : "0 токенов" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 次读取" + "value" : "0 Token" } } } }, - "1 search" : { + "1 agent step" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "検索 1 回" + "value" : "エージェントのステップ 1 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 поиск" + "value" : "1 шаг агента" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 次搜索" + "value" : "1 个代理步骤" } } } }, - "1 tool" : { + "1 command" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ツール 1 件" + "value" : "コマンド 1 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 инструмент" + "value" : "1 команда" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 个工具" + "value" : "1 条命令" } } } }, - "1 tool call" : { + "1 edit" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ツール呼び出し 1 回" + "value" : "編集 1 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 вызов инструмента" + "value" : "1 правка" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 次工具调用" + "value" : "1 次修改" } } } }, - "1 web request" : { + "1 finding" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Web リクエスト 1 件" + "value" : "指摘 1 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "1 веб-запрос" + "value" : "1 замечание" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "1 次网络请求" + "value" : "1 条发现" } } } }, - "7 days" : { + "1 new message ↓" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "過去 7 日間" + "value" : "新着メッセージ 1 件 ↓" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "7 дней" + "value" : "1 новое сообщение ↓" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "近 7 天" + "value" : "1 条新消息 ↓" } } } }, - "30 days" : { + "1 note" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "過去 30 日間" + "value" : "メモ 1 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "30 дней" + "value" : "1 заметка" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "近 30 天" + "value" : "1 条笔记" } } } }, - "A note can hold at most %lld attachments" : { + "1 other tool" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "1 件のメモに添付できるファイルは最大 %lld 件です" + "value" : "その他のツール 1 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Максимум вложений в заметке: %lld" + "value" : "1 другой инструмент" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 个其他工具" + } + } + } + }, + "1 queued message" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "キュー内のメッセージ 1 件" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 сообщение в очереди" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 条排队消息" + } + } + } + }, + "1 read" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "読み取り 1 回" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 чтение" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 次读取" + } + } + } + }, + "1 search" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "検索 1 回" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 поиск" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 次搜索" + } + } + } + }, + "1 tool" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ツール 1 件" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 инструмент" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 个工具" + } + } + } + }, + "1 tool call" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ツール呼び出し 1 回" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 вызов инструмента" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 次工具调用" + } + } + } + }, + "1 web request" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Web リクエスト 1 件" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 веб-запрос" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 次网络请求" + } + } + } + }, + "7 days" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "過去 7 日間" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "7 дней" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "近 7 天" + } + } + } + }, + "30 days" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "過去 30 日間" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "30 дней" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "近 30 天" + } + } + } + }, + "A note can hold at most %lld attachments" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 件のメモに添付できるファイルは最大 %lld 件です" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Максимум вложений в заметке: %lld" } }, "zh-Hans" : { @@ -8034,6 +8374,29 @@ } } }, + "Hide members" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "メンバーを隠す" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Скрыть участников" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "收起成员" + } + } + } + }, "Hide note" : { "extractionState" : "manual", "localizations" : { @@ -14405,6 +14768,29 @@ } } }, + "Show members" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "メンバーを表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать участников" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "展开成员" + } + } + } + }, "Show original" : { "extractionState" : "manual", "localizations" : { @@ -14980,2677 +15366,5276 @@ } } }, - "Stop the current turn" : { + "Stop the current turn" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "現在のターンを停止" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Остановить текущий ход" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "停止当前回合" + } + } + } + }, + "Stop translating my messages" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "メッセージの翻訳を停止" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не переводить мои сообщения" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "停止翻译我的消息" + } + } + } + }, + "Stopped" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "停止済み" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Остановлена" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已停止" + } + } + } + }, + "Storage" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ストレージ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хранилище" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "存储空间" + } + } + } + }, + "Subdirectories" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "サブディレクトリ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Подкаталоги" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "子目录" + } + } + } + }, + "Submit" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "送信" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправить" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "提交" + } + } + } + }, + "Submit answer" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "回答を送信" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправить ответ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "提交回答" + } + } + } + }, + "Submitting answer…" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "回答を送信中…" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправка ответа…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在提交回答…" + } + } + } + }, + "Submitting approval…" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "承認を送信中…" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправка одобрения…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在提交授权…" + } + } + } + }, + "Take draft" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "下書きを取り出す" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Взять черновик" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "取回" + } + } + } + }, + "Team: %@" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "チーム:%@" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Команда: %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "团队:%@" + } + } + } + }, + "Terminal" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ターミナル" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Терминал" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "终端" + } + } + } + }, + "That code is not a HAPI pairing QR — scan one printed by the hub." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "これは HAPI のペアリング用 QR コードではありません — Hub に表示された QR コードをスキャンしてください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот код не является QR-кодом сопряжения HAPI — отсканируйте напечатанный хабом." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "这不是 HAPI 配对二维码 — 请扫描 Hub 打印的二维码。" + } + } + } + }, + "That file is over the %lld MB limit" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このファイルは上限の %lld MB を超えています" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот файл превышает лимит %lld МБ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "该文件超过 %lld MB 上限" + } + } + } + }, + "That file is over the hub's per-file size limit" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このファイルは Hub のファイルサイズ上限を超えています" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот файл превышает лимит размера файла на хабе" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "该文件超过 Hub 的单文件大小上限" + } + } + } + }, + "That file type isn't allowed for scratchlist attachments" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このファイル形式はスクラッチリストの添付ファイルには使用できません" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот тип файла не разрешён для вложений в заметки" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "草稿夹附件不支持该文件类型" + } + } + } + }, + "The app checks the hub is reachable, then exchanges the token for a session." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "アプリは Hub に到達できることを確認した後、トークンをセッションと交換します。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Приложение проверяет доступность хаба, затем обменивает токен на сессию." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "应用会先确认 Hub 可达,再用令牌换取会话。" + } + } + } + }, + "The attachments exceed the scratchlist limits — remove a file or choose a smaller one" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "添付ファイルがスクラッチリストの上限を超えています — ファイルを削除するか、より小さいファイルを選択してください" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вложения превышают лимиты заметок — удалите файл или выберите меньший" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "附件超出草稿夹限制,请移除附件或选择更小的文件" + } + } + } + }, + "the dropped item" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ドロップした項目" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "перетащенный элемент" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "拖入的项目" + } + } + } + }, + "The hub answered unexpectedly (HTTP %lld). Try again in a moment." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub から予期しない応答がありました(HTTP %lld)。しばらくしてからもう一度お試しください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб ответил неожиданно (HTTP %lld). Попробуйте снова через мгновение." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub 返回了意外响应(HTTP %lld)。请稍后重试。" + } + } + } + }, + "The hub rejected the stored credentials — the access token was probably rotated. Pair again to reconnect." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub が保存済みの認証情報を拒否しました — アクセストークンがローテーションされた可能性があります。再接続するには、もう一度ペアリングしてください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб отклонил сохранённые учётные данные — вероятно, токен доступа был обновлён. Сопрягите заново, чтобы переподключиться." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub 拒绝了已保存的凭据 — 访问令牌可能已被轮换。请重新配对以恢复连接。" + } + } + } + }, + "The hub rejected this access token — it may have been rotated. Get a fresh pairing code from the hub and try again." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub がこのアクセストークンを拒否しました — ローテーションされた可能性があります。Hub から新しいペアリングコードを取得して、もう一度お試しください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб отклонил этот токен доступа — возможно, он был обновлён. Получите свежий код сопряжения с хаба и попробуйте снова." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub 拒绝了此访问令牌 — 它可能已被轮换。请从 Hub 获取新的配对码后重试。" + } + } + } + }, + "The hub speaks protocol v%lld, this app supports v%lld. Update the older side, then try again." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub はプロトコル v%lld を使用していますが、このアプリは v%lld に対応しています。古い方を更新してから、もう一度お試しください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб использует протокол v%lld, а это приложение поддерживает v%lld. Обновите более старую сторону и попробуйте снова." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub 使用协议 v%lld,本应用支持 v%lld。请升级较旧的一方后重试。" + } + } + } + }, + "The selected Agent is not available on this machine." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "選択したエージェントはこのマシンでは利用できません。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбранный агент недоступен на этой машине." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "所选代理在此机器上不可用。" + } + } + } + }, + "The session is no longer active." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このセッションはアクティブではなくなりました。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессия больше не активна." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "该会话已不再活跃。" + } + } + } + }, + "Theme" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "テーマ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Тема" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "主题" + } + } + } + }, + "Thinking" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "思考中" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Думает" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "思考中" + } + } + } + }, + "This agent manages its own permissions. YOLO mode is not available." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このエージェントは権限を自身で管理します。YOLO モードは利用できません。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот агент сам управляет разрешениями. Режим YOLO недоступен." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此代理自行管理权限,YOLO 模式不适用。" + } + } + } + }, + "This dashboard is only available to the hub owner (default namespace)." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このダッシュボードは Hub の所有者(default 名前空間)のみ利用できます。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Эта панель доступна только владельцу хаба (пространство имён по умолчанию)." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此看板仅 Hub 所有者(default 命名空间)可用。" + } + } + } + }, + "This device cannot scan QR codes (for example the Simulator). Go back and use manual entry instead." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このデバイスでは QR コードをスキャンできません(シミュレータなど)。戻って手動で入力してください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Это устройство не может сканировать QR-коды (например, симулятор). Вернитесь и введите данные вручную." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此设备无法扫描二维码(例如模拟器)。请返回并使用手动输入。" + } + } + } + }, + "This export contains %lld messages (about %@), above the recommended %lld." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このエクスポートには %1$lld 件のメッセージ(約 %2$@)が含まれており、推奨の %3$lld 件を超えています。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Экспорт содержит сообщений: %1$lld (около %2$@), больше рекомендуемых %3$lld." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此导出包含 %1$lld 条消息(约 %2$@),超过建议的 %3$lld 条。" + } + } + } + }, + "This export is too large to prepare safely (%lld messages, %@; maximum %@)." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このエクスポートは大きすぎるため、安全に準備できません(%1$lld 件のメッセージ、%2$@、上限 %3$@)。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Экспорт слишком велик для безопасной подготовки (сообщений: %1$lld, %2$@; максимум %3$@)." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "导出内容过大,无法安全准备(%1$lld 条消息,%2$@;上限 %3$@)。" + } + } + } + }, + "This file is empty" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このファイルは空です" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот файл пуст" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "文件为空" + } + } + } + }, + "This hub will be added to your paired hubs and become active." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "この Hub はペアリング済みの Hub に追加され、アクティブになります。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот хаб будет добавлен к сопряжённым и станет активным." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此 Hub 将加入已配对列表并成为当前 Hub。" + } + } + } + }, + "This media cannot be played on this device." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このメディアはこのデバイスで再生できません。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Это медиа не воспроизводится на этом устройстве." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此设备无法播放该媒体。" + } + } + } + }, + "This note's attachment budget is used up" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このメモの添付ファイルの容量を使い切りました" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Бюджет вложений этой заметки исчерпан" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此笔记的附件配额已用完" + } + } + } + }, + "This pairing link is invalid or incomplete. Copy the full link from your hub." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このペアリングリンクは無効、または不完全です。Hub から完全なリンクをコピーしてください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Эта ссылка для сопряжения недействительна или неполна. Скопируйте полную ссылку с хаба." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "配对链接无效或不完整。请从 Hub 复制完整链接。" + } + } + } + }, + "This question could not be displayed. Open details to inspect the request." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "この質問を表示できませんでした。詳細を開いてリクエストを確認してください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось показать этот вопрос. Откройте детали, чтобы изучить запрос." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无法显示这个问题。请打开详情查看原始请求。" + } + } + } + }, + "To composer" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "入力欄へ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В поле ввода" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "复制到输入框" + } + } + } + }, + "Todo list" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ToDo リスト" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Список задач" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "任务清单" + } + } + } + }, + "Toggle Sidebar" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "サイドバーを切り替え" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать/скрыть боковую панель" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "显示/隐藏边栏" + } + } + } + }, + "Token rejected" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "トークンが拒否されました" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Токен отклонён" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "令牌被拒绝" + } + } + } + }, + "Token usage across agents and models" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "エージェントとモデルごとのトークン使用量" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использование токенов по агентам и моделям" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "各 Agent 与模型的 Token 用量" + } + } + } + }, + "Tool %lld of %lld" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ツール %lld / %lld" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Инструмент %lld из %lld" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "第 %lld 个工具,共 %lld 个" + } + } + } + }, + "Tool details" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ツールの詳細" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Детали инструмента" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "工具详情" + } + } + } + }, + "Total" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "合計" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Итого" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "总计" + } + } + } + }, + "Total tokens" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "合計トークン" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Всего токенов" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "总 Token" + } + } + } + }, + "Transcription failed" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "文字起こしに失敗しました" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка транскрипции" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "转录失败" + } + } + } + }, + "Translate my messages to English" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "メッセージを英語に翻訳" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переводить мои сообщения на английский" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "将我的消息翻译为英文" + } + } + } + }, + "Translated" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "翻訳済み" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переведено" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已翻译" + } + } + } + }, + "Try Again" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "もう一度試す" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Повторить" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "重试" + } + } + } + }, + "Type an answer first" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "先に回答を入力してください" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сначала введите ответ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "请先输入答案" + } + } + } + }, + "Type to search files in the session directory" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "入力してセッションのディレクトリ内のファイルを検索" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Начните вводить текст для поиска файлов в каталоге сессии" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "输入以在会话目录中搜索文件" + } + } + } + }, + "Type your answer…" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "回答を入力…" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Введите ответ…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "输入您的答案…" + } + } + } + }, + "Uncached" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "キャッシュなし" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Без кеша" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "非缓存" + } + } + } + }, + "Unknown machine" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "不明なマシン" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Неизвестная машина" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未知机器" + } + } + } + }, + "Unpin" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ピン留めを解除" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Открепить" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "取消置顶" + } + } + } + }, + "Unread" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "未読" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Непрочитано" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未读" + } + } + } + }, + "Unread only" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "未読のみ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Только непрочитанные" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "仅未读" + } + } + } + }, + "Unread Only" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "未読のみ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Только непрочитанные" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "仅未读" + } + } + } + }, + "Unstaged" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "未ステージ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вне индекса" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未暂存" + } + } + } + }, + "Unstaged (%lld)" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "未ステージ(%lld)" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вне индекса (%lld)" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未暂存(%lld)" + } + } + } + }, + "Up" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "上へ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вверх" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "上一级" + } + } + } + }, + "Upgrade and restart this machine's HAPI runner before creating sessions." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "セッションを作成する前に、このマシンの HAPI runner をアップグレードして再起動してください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Обновите и перезапустите раннер HAPI этой машины перед созданием сессий." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "创建会话前,请升级并重启此机器上的 HAPI runner。" + } + } + } + }, + "Upload failed — check the hub connection" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "アップロードに失敗しました — Hub への接続を確認してください" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка загрузки — проверьте подключение к хабу" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "上传失败 — 请检查 Hub 连接" + } + } + } + }, + "Uploading…" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "アップロード中…" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "上传中…" + } + } + } + }, + "Usage" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "使用量" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использование" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "用量" + } + } + } + }, + "Use selected directory as-is" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "選択したディレクトリをそのまま使用" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использовать выбранный каталог как есть" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "直接使用选定的目录" + } + } + } + }, + "Uses dangerous agent flags when spawning." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "起動時に危険なエージェントフラグを使用します。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использует опасные флаги агента при запуске." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "启动时使用危险的代理标志。" + } + } + } + }, + "Uses dangerous agent flags when spawning. Applies native %@ mode." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "起動時に危険なエージェントフラグを使用します。ネイティブの %@ モードを適用します。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использует опасные флаги агента при запуске. Применяет нативный режим %@." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "启动时使用危险的代理标志。将应用原生 %@ 模式。" + } + } + } + }, + "Version mismatch" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "バージョンが一致しません" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Несовпадение версий" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "版本不匹配" + } + } + } + }, + "View agent process" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "サブエージェントの処理を表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс агента" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看子代理执行过程" + } + } + } + }, + "View all" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "すべて表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать все" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看全部" + } + } + } + }, + "View current file" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "現在のファイルを表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать текущий файл" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看当前文件" + } + } + } + }, + "View full input" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "入力全文を表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать полный ввод" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看完整输入" + } + } + } + }, + "View full message" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "メッセージ全文を表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать сообщение целиком" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看完整消息" + } + } + } + }, + "View full questions and answers" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "質問と回答の全文を表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать все вопросы и ответы" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看完整问题与回答" + } + } + } + }, + "View image" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "画像を表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать изображение" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看图片" + } + } + } + }, + "View process · %lld steps" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "variations" : { + "plural" : { + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "処理を表示 · %lld ステップ" + } + } + } + } + }, + "ru" : { + "variations" : { + "plural" : { + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс · %lld шага" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс · %lld шагов" + } + }, + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс · %lld шаг" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс · %lld шага" + } + } + } + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看过程 · %lld 个步骤" + } + } + } + }, + "View the full draft" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "下書きの全文を表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать черновик целиком" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看草稿全文" + } + } + } + }, + "View tool details" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ツールの詳細を表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать детали инструмента" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看工具详情" + } + } + } + }, + "View tool group" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ツールグループを表示" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать группу инструментов" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "查看工具组" + } + } + } + }, + "Wait for agent" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "エージェントを待機" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ждать агента" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "等待代理" + } + } + } + }, + "Wait for result" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "結果を待機" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ждать результат" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "等待结果" + } + } + } + }, + "Waiting for output…" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "出力を待機中…" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ожидание вывода…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "等待输出…" + } + } + } + }, + "Web fetch" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Web 取得" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Веб-запрос" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "获取网页" + } + } + } + }, + "Web search" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Web 検索" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Веб-поиск" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "网络搜索" + } + } + } + }, + "Workspace file" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ワークスペースのファイル" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файл рабочего пространства" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "工作区文件" + } + } + } + }, + "Workspace Roots" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ワークスペースルート" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Корни рабочего пространства" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "工作区根目录" + } + } + } + }, + "Worktree" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Worktree" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Worktree" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "工作树" + } + } + } + }, + "Worktree sessions require an existing repository directory." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Worktreeのセッションには、既存のリポジトリのディレクトリが必要です。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Для сессий worktree нужен существующий каталог репозитория." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "工作树会话需要已存在的仓库目录。" + } + } + } + }, + "Write draft" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "下書きを書く" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Написать черновик" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "写草稿" + } + } + } + }, + "Write file" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ファイルを書き込み" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запись файла" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "写入文件" + } + } + } + }, + "Write-ahead log" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "先行書き込みログ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Журнал упреждающей записи" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "预写日志" + } + } + } + }, + "You already have a draft" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "入力欄にすでに内容があります" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "У вас уже есть черновик" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "输入框中已有内容" + } + } + } + }, + "Your answer" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "あなたの回答" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ваш ответ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "你的回答" + } + } + } + }, + "Your input changed — review it and try again" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "入力内容が変更されました — 確認してもう一度お試しください" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ваш ввод изменился — проверьте его и попробуйте снова" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "输入内容已发生变化,请检查后重试" + } + } + } + }, + "Enter Hub address manually" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub のアドレスを手動で入力" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ввести адрес хаба вручную" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "手动输入 Hub 地址" + } + } + } + }, + "Hub address needed" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub のアドレスが必要です" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нужен адрес хаба" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "需要 Hub 地址" + } + } + } + }, + "Passkey for another hub" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "別の Hub のパスキー" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ключ доступа другого хаба" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "属于其他 Hub 的通行密钥" + } + } + } + }, + "This passkey does not include its hub address. Enter the hub URL, then sign in with the same passkey." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このパスキーには Hub のアドレスが含まれていません。Hub の URL を入力してから、同じパスキーでサインインしてください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот ключ доступа не содержит адрес своего хаба. Введите URL хаба и войдите с тем же ключом." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此通行密钥未包含其 Hub 地址。请输入 Hub URL,然后使用同一通行密钥登录。" + } + } + } + }, + "This passkey belongs to a different hub. Choose a passkey for this hub, or check the hub address." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このパスキーは別の Hub のものです。この Hub のパスキーを選択するか、Hub のアドレスを確認してください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот ключ доступа принадлежит другому хабу. Выберите ключ для этого хаба или проверьте адрес." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此通行密钥属于其他 Hub。请选择此 Hub 的通行密钥,或检查 Hub 地址。" + } + } + } + }, + "%@: Update the runner to view quotas." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@:クォータを表示するには runner を更新してください。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@: обновите runner для просмотра квот." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@:更新 runner 以查看配额。" + } + } + } + }, + "%lld%% remaining · %lld%% used" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "残り %1$lld%% · 使用済み %2$lld%%" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Осталось %1$lld%% · использовано %2$lld%%" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "剩余 %1$lld%% · 已用 %2$lld%%" + } + } + } + }, + "CLI account quotas" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "CLI アカウントのクォータ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Квоты аккаунтов CLI" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "CLI 账户配额" + } + } + } + }, + "Custom endpoint / API key" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "カスタムエンドポイント / API キー" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Свой адрес API / ключ API" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "自定义端点 / API 密钥" + } + } + } + }, + "Last loaded quotas" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "前回取得したクォータ" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Последние загруженные квоты" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "上次加载的配额" + } + } + } + }, + "Loading quotas" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "クォータを読み込み中" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка квот" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在加载配额" + } + } + } + }, + "No online machines reported CLI accounts." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "CLI アカウントを報告したオンラインのマシンはありません。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ни одна машина в сети не сообщила об аккаунтах CLI." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "没有在线机器报告 CLI 账户。" + } + } + } + }, + "Not signed in" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "未ログイン" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вход не выполнен" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未登录" + } + } + } + }, + "Only the hub owner can view CLI account quotas." : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "CLI アカウントのクォータを表示できるのはハブの所有者のみです。" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Просматривать квоты аккаунтов CLI может только владелец хаба." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "仅 Hub 所有者可查看 CLI 账户配额。" + } + } + } + }, + "Quota unavailable" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "クォータを取得できません" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Квота недоступна" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "配额不可用" + } + } + } + }, + "Refresh quotas" : { + "extractionState" : "manual", + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "クォータを更新" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Обновить квоты" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "刷新配额" + } + } + } + }, + "Resets %@" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "現在のターンを停止" + "value" : "%@ にリセット" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Остановить текущий ход" + "value" : "Сброс %@" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "停止当前回合" + "value" : "%@ 重置" } } } }, - "Stop translating my messages" : { + "Update the hub to view CLI account quotas." : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "メッセージの翻訳を停止" + "value" : "CLI アカウントのクォータを表示するにはハブを更新してください。" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Не переводить мои сообщения" + "value" : "Обновите хаб для просмотра квот аккаунтов CLI." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "停止翻译我的消息" + "value" : "更新 Hub 以查看 CLI 账户配额。" } } } }, - "Stopped" : { + "%lld files" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "停止済み" + "value" : "%lld 件のファイル" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Остановлена" + "value" : "Файлов: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "已停止" + "value" : "%lld 个文件" } } } }, - "Storage" : { + "%lld/%lld tasks" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ストレージ" + "value" : "%1$lld/%2$lld タスク" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Хранилище" + "value" : "%1$lld/%2$lld задач" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "存储空间" + "value" : "%1$lld/%2$lld 项任务" } } } }, - "Subdirectories" : { + "1 file" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "サブディレクトリ" + "value" : "1 件のファイル" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Подкаталоги" + "value" : "1 файл" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "子目录" + "value" : "1 个文件" } } } }, - "Submit" : { + "1 member" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "送信" + "value" : "1 名のメンバー" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Отправить" + "value" : "1 участник" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "提交" + "value" : "1 位成员" } } } }, - "Submit answer" : { + "Cache write" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "回答を送信" + "value" : "キャッシュ書き込み" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Отправить ответ" + "value" : "Запись в кэш" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "提交回答" + "value" : "缓存写入" } } } }, - "Submitting answer…" : { + "Context %@ tokens used" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "回答を送信中…" + "value" : "コンテキスト使用量 %@ トークン" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Отправка ответа…" + "value" : "Использовано %@ токенов контекста" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "正在提交回答…" + "value" : "上下文已使用 %@ tokens" } } } }, - "Submitting approval…" : { + "Context %lld%% used, %@ of %@ tokens" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "承認を送信中…" + "value" : "コンテキスト使用率 %1$lld%%、%2$@ / %3$@ トークン" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Отправка одобрения…" + "value" : "Контекст: %1$lld%% (%2$@ из %3$@ токенов)" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "正在提交授权…" + "value" : "上下文已使用 %1$lld%%,%2$@ / %3$@ tokens" } } } }, - "Take draft" : { + "Context & Quotas" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "下書きを取り出す" + "value" : "コンテキストとクォータ" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Взять черновик" + "value" : "Контекст и квоты" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "取回" + "value" : "上下文与配额" } } } }, - "Team: %@" : { + "Context window" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "チーム:%@" + "value" : "コンテキストウィンドウ" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Команда: %@" + "value" : "Окно контекста" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "团队:%@" + "value" : "上下文窗口" } } } }, - "Terminal" : { + "Copy as Markdown" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ターミナル" + "value" : "Markdown としてコピー" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Терминал" + "value" : "Скопировать как Markdown" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "终端" + "value" : "复制为 Markdown" } } } }, - "That code is not a HAPI pairing QR — scan one printed by the hub." : { + "Copy as Plain Text" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "これは HAPI のペアリング用 QR コードではありません — Hub に表示された QR コードをスキャンしてください。" + "value" : "プレーンテキストとしてコピー" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот код не является QR-кодом сопряжения HAPI — отсканируйте напечатанный хабом." + "value" : "Скопировать как текст" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "这不是 HAPI 配对二维码 — 请扫描 Hub 打印的二维码。" + "value" : "复制为纯文本" } } } }, - "That file is over the %lld MB limit" : { + "Copy diagnostics" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このファイルは上限の %lld MB を超えています" + "value" : "診断情報をコピー" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот файл превышает лимит %lld МБ" + "value" : "Скопировать диагностику" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "该文件超过 %lld MB 上限" + "value" : "复制诊断信息" } } } }, - "That file is over the hub's per-file size limit" : { + "Diagnostics copied" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このファイルは Hub のファイルサイズ上限を超えています" + "value" : "診断情報をコピーしました" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот файл превышает лимит размера файла на хабе" + "value" : "Диагностика скопирована" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "该文件超过 Hub 的单文件大小上限" + "value" : "已复制诊断信息" } } } }, - "That file type isn't allowed for scratchlist attachments" : { + "Group Members" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このファイル形式はスクラッチリストの添付ファイルには使用できません" + "value" : "グループメンバー" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот тип файла не разрешён для вложений в заметки" + "value" : "Участники группы" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "草稿夹附件不支持该文件类型" + "value" : "组成员" } } } }, - "The app checks the hub is reachable, then exchanges the token for a session." : { + "High" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "アプリは Hub に到達できることを確認した後、トークンをセッションと交換します。" + "value" : "高" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Приложение проверяет доступность хаба, затем обменивает токен на сессию." + "value" : "Высокий" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "应用会先确认 Hub 可达,再用令牌换取会话。" + "value" : "高" } } } }, - "The attachments exceed the scratchlist limits — remove a file or choose a smaller one" : { + "Last turn" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "添付ファイルがスクラッチリストの上限を超えています — ファイルを削除するか、より小さいファイルを選択してください" + "value" : "直前のターン" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Вложения превышают лимиты заметок — удалите файл или выберите меньший" + "value" : "Последний ход" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "附件超出草稿夹限制,请移除附件或选择更小的文件" + "value" : "上一轮" } } } }, - "the dropped item" : { + "Online" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ドロップした項目" + "value" : "オンライン" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "перетащенный элемент" + "value" : "В сети" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "拖入的项目" + "value" : "在线" } } } }, - "The hub answered unexpectedly (HTTP %lld). Try again in a moment." : { + "Remaining" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Hub から予期しない応答がありました(HTTP %lld)。しばらくしてからもう一度お試しください。" + "value" : "残り" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Хаб ответил неожиданно (HTTP %lld). Попробуйте снова через мгновение." + "value" : "Осталось" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "Hub 返回了意外响应(HTTP %lld)。请稍后重试。" + "value" : "剩余" } } } }, - "The hub rejected the stored credentials — the access token was probably rotated. Pair again to reconnect." : { + "Tasks" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Hub が保存済みの認証情報を拒否しました — アクセストークンがローテーションされた可能性があります。再接続するには、もう一度ペアリングしてください。" + "value" : "タスク" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Хаб отклонил сохранённые учётные данные — вероятно, токен доступа был обновлён. Сопрягите заново, чтобы переподключиться." + "value" : "Задачи" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "Hub 拒绝了已保存的凭据 — 访问令牌可能已被轮换。请重新配对以恢复连接。" + "value" : "任务" } } } }, - "The hub rejected this access token — it may have been rotated. Get a fresh pairing code from the hub and try again." : { + "Uncommitted changes: +%lld -%lld across %lld files" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Hub がこのアクセストークンを拒否しました — ローテーションされた可能性があります。Hub から新しいペアリングコードを取得して、もう一度お試しください。" + "value" : "未コミットの変更:%3$lld ファイル +%1$lld -%2$lld" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Хаб отклонил этот токен доступа — возможно, он был обновлён. Получите свежий код сопряжения с хаба и попробуйте снова." + "value" : "Незафиксированные изменения: +%1$lld -%2$lld (%3$lld файлов)" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "Hub 拒绝了此访问令牌 — 它可能已被轮换。请从 Hub 获取新的配对码后重试。" + "value" : "未提交更改:%3$lld 个文件 +%1$lld -%2$lld" } } } }, - "The hub speaks protocol v%lld, this app supports v%lld. Update the older side, then try again." : { + "Used" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Hub はプロトコル v%lld を使用していますが、このアプリは v%lld に対応しています。古い方を更新してから、もう一度お試しください。" + "value" : "使用済み" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Хаб использует протокол v%lld, а это приложение поддерживает v%lld. Обновите более старую сторону и попробуйте снова." + "value" : "Использовано" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "Hub 使用协议 v%lld,本应用支持 v%lld。请升级较旧的一方后重试。" + "value" : "已使用" } } } }, - "The selected Agent is not available on this machine." : { + "Waiting" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "選択したエージェントはこのマシンでは利用できません。" + "value" : "待機中" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Выбранный агент недоступен на этой машине." + "value" : "Ожидает" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "所选代理在此机器上不可用。" + "value" : "等待中" } } } }, - "The session is no longer active." : { + "Working" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このセッションはアクティブではなくなりました。" + "value" : "処理中" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Сессия больше не активна." + "value" : "Работает" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "该会话已不再活跃。" + "value" : "处理中" } } } }, - "Theme" : { + "%lld matches" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "テーマ" + "value" : "一致 %lld 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Тема" + "value" : "Совпадений: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "主题" + "value" : "%lld 条匹配" } } } }, - "Thinking" : { + "%lld msgs" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "思考中" + "value" : "%lld 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Думает" + "value" : "%lld сообщ." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "思考中" + "value" : "%lld 条消息" } } } }, - "This agent manages its own permissions. YOLO mode is not available." : { + "%lld review comments" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このエージェントは権限を自身で管理します。YOLO モードは利用できません。" + "value" : "レビューコメント %lld 件" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот агент сам управляет разрешениями. Режим YOLO недоступен." + "value" : "Комментарии: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此代理自行管理权限,YOLO 模式不适用。" + "value" : "%lld 条评审评论" } } } }, - "This dashboard is only available to the hub owner (default namespace)." : { + "Add Comment" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このダッシュボードは Hub の所有者(default 名前空間)のみ利用できます。" + "value" : "コメントを追加" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Эта панель доступна только владельцу хаба (пространство имён по умолчанию)." + "value" : "Добавить комментарий" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此看板仅 Hub 所有者(default 命名空间)可用。" + "value" : "添加评论" } } } }, - "This device cannot scan QR codes (for example the Simulator). Go back and use manual entry instead." : { + "Auto-expand reasoning" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このデバイスでは QR コードをスキャンできません(シミュレータなど)。戻って手動で入力してください。" + "value" : "推論を自動展開" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Это устройство не может сканировать QR-коды (например, симулятор). Вернитесь и введите данные вручную." + "value" : "Автораскрытие рассуждений" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此设备无法扫描二维码(例如模拟器)。请返回并使用手动输入。" + "value" : "自动展开思考过程" } } } }, - "This export contains %lld messages (about %@), above the recommended %lld." : { + "Cancel recording" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このエクスポートには %1$lld 件のメッセージ(約 %2$@)が含まれており、推奨の %3$lld 件を超えています。" + "value" : "録音をキャンセル" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Экспорт содержит сообщений: %1$lld (около %2$@), больше рекомендуемых %3$lld." + "value" : "Отменить запись" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此导出包含 %1$lld 条消息(约 %2$@),超过建议的 %3$lld 条。" + "value" : "取消录音" } } } }, - "This export is too large to prepare safely (%lld messages, %@; maximum %@)." : { + "Caution" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このエクスポートは大きすぎるため、安全に準備できません(%1$lld 件のメッセージ、%2$@、上限 %3$@)。" + "value" : "注意" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Экспорт слишком велик для безопасной подготовки (сообщений: %1$lld, %2$@; максимум %3$@)." + "value" : "Осторожно" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "导出内容过大,无法安全准备(%1$lld 条消息,%2$@;上限 %3$@)。" + "value" : "警告" } } } }, - "This file is empty" : { + "Clear All" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このファイルは空です" + "value" : "すべてクリア" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот файл пуст" + "value" : "Очистить всё" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "文件为空" + "value" : "清空全部" } } } }, - "This hub will be added to your paired hubs and become active." : { + "Compose Message" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "この Hub はペアリング済みの Hub に追加され、アクティブになります。" + "value" : "メッセージを作成" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот хаб будет добавлен к сопряжённым и станет активным." + "value" : "Новое сообщение" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此 Hub 将加入已配对列表并成为当前 Hub。" + "value" : "撰写消息" } } } }, - "This media cannot be played on this device." : { + "Connect a runner machine to browse and import local CLI sessions." : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このメディアはこのデバイスで再生できません。" + "value" : "ローカル CLI セッションを参照・インポートするにはオンラインのランナーマシンを接続してください。" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Это медиа не воспроизводится на этом устройстве." + "value" : "Подключите машину-раннер для просмотра и импорта локальных CLI-сессий." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此设备无法播放该媒体。" + "value" : "请连接在线的运行主机,以浏览和导入本地 CLI 会话。" } } } }, - "This note's attachment budget is used up" : { + "Delete Comment" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このメモの添付ファイルの容量を使い切りました" + "value" : "コメントを削除" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Бюджет вложений этой заметки исчерпан" + "value" : "Удалить комментарий" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此笔记的附件配额已用完" + "value" : "删除评论" } } } }, - "This pairing link is invalid or incomplete. Copy the full link from your hub." : { + "Edit Comment" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このペアリングリンクは無効、または不完全です。Hub から完全なリンクをコピーしてください。" + "value" : "コメントを編集" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Эта ссылка для сопряжения недействительна или неполна. Скопируйте полную ссылку с хаба." + "value" : "Изменить комментарий" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "配对链接无效或不完整。请从 Hub 复制完整链接。" + "value" : "编辑评论" } } } }, - "This question could not be displayed. Open details to inspect the request." : { + "Edit Draft" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "この質問を表示できませんでした。詳細を開いてリクエストを確認してください。" + "value" : "下書きを編集" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Не удалось показать этот вопрос. Откройте детали, чтобы изучить запрос." + "value" : "Редактировать черновик" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "无法显示这个问题。请打开详情查看原始请求。" + "value" : "编辑草稿" } } } }, - "To composer" : { + "Expand editor" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "入力欄へ" + "value" : "エディタを拡大" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "В поле ввода" + "value" : "Развернуть редактор" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "复制到输入框" + "value" : "全屏编辑" } } } }, - "Todo list" : { + "Failed to import session" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ToDo リスト" + "value" : "セッションのインポートに失敗しました" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Список задач" + "value" : "Не удалось импортировать сессию" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "任务清单" + "value" : "导入会话失败" } } } }, - "Toggle Sidebar" : { + "Failed to load local sessions" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "サイドバーを切り替え" + "value" : "ローカルセッションの読み込みに失敗しました" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать/скрыть боковую панель" + "value" : "Не удалось загрузить локальные сессии" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "显示/隐藏边栏" + "value" : "加载本地会话失败" } } } }, - "Token rejected" : { + "Filter local sessions…" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "トークンが拒否されました" + "value" : "ローカルセッションを絞り込み…" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Токен отклонён" + "value" : "Фильтр локальных сессий…" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "令牌被拒绝" + "value" : "筛选本地会话…" } } } }, - "Token usage across agents and models" : { + "Filter skills…" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "エージェントとモデルごとのトークン使用量" + "value" : "スキルを絞り込み…" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Использование токенов по агентам и моделям" + "value" : "Фильтр навыков…" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "各 Agent 与模型的 Token 用量" + "value" : "筛选技能…" } } } }, - "Tool %lld of %lld" : { + "Find in Conversation" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ツール %lld / %lld" + "value" : "会話内を検索" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Инструмент %lld из %lld" + "value" : "Поиск в диалоге" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "第 %lld 个工具,共 %lld 个" + "value" : "在对话中查找" } } } }, - "Tool details" : { + "Find in Conversation…" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ツールの詳細" + "value" : "会話内を検索…" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Детали инструмента" + "value" : "Поиск в диалоге…" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "工具详情" + "value" : "在对话中查找…" } } } }, - "Total" : { + "Find messages across the entire conversation history." : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "合計" + "value" : "会話履歴全体からメッセージを検索します。" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Итого" + "value" : "Поиск сообщений по всей истории диалога." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "总计" + "value" : "在整个对话历史中搜索消息。" } } } }, - "Total tokens" : { + "Group by Project" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "合計トークン" + "value" : "プロジェクト別にグループ化" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Всего токенов" + "value" : "Группировать по проектам" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "总 Token" + "value" : "按项目分组" } } } }, - "Transcription failed" : { + "Import Local Session" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "文字起こしに失敗しました" + "value" : "ローカルセッションをインポート" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ошибка транскрипции" + "value" : "Импорт локальной сессии" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "转录失败" + "value" : "导入本地会话" } } } }, - "Translate my messages to English" : { + "Important" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "メッセージを英語に翻訳" + "value" : "重要" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Переводить мои сообщения на английский" + "value" : "Важно" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "将我的消息翻译为英文" + "value" : "重要" } } } }, - "Translated" : { + "Imported" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "翻訳済み" + "value" : "インポート済み" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Переведено" + "value" : "Импортировано" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "已翻译" + "value" : "已导入" } } } }, - "Try Again" : { + "Import…" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "もう一度試す" + "value" : "インポート…" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Повторить" + "value" : "Импорт…" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "重试" + "value" : "导入…" } } } }, - "Type an answer first" : { + "Limit reached" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "先に回答を入力してください" + "value" : "上限に達しました" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Сначала введите ответ" + "value" : "Лимит исчерпан" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "请先输入答案" + "value" : "已达上限" } } } }, - "Type to search files in the session directory" : { + "Matching Messages" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "入力してセッションのディレクトリ内のファイルを検索" + "value" : "一致するメッセージ" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Начните вводить текст для поиска файлов в каталоге сессии" + "value" : "Совпадающие сообщения" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "输入以在会话目录中搜索文件" + "value" : "匹配的消息" } } } }, - "Type your answer…" : { + "No Local Sessions" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "回答を入力…" + "value" : "ローカルセッションなし" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Введите ответ…" + "value" : "Нет локальных сессий" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "输入您的答案…" + "value" : "无本地会话" } } } }, - "Uncached" : { + "No Online Machines" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "キャッシュなし" + "value" : "オンラインのマシンがありません" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Без кеша" + "value" : "Нет машин в сети" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "非缓存" + "value" : "没有在线主机" } } } }, - "Unknown machine" : { + "No local %@ sessions were found on this machine." : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "不明なマシン" + "value" : "このマシンにローカルの %@ セッションが見つかりませんでした。" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Неизвестная машина" + "value" : "Локальные сессии %@ на этой машине не найдены." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "未知机器" + "value" : "在此主机上未找到本地 %@ 会话。" } } } }, - "Unpin" : { + "On track" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ピン留めを解除" + "value" : "順調" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Открепить" + "value" : "В норме" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "取消置顶" + "value" : "消耗正常" } } } }, - "Unread" : { + "Other" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "未読" + "value" : "その他" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Непрочитано" + "value" : "Другое" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "未读" + "value" : "其他" } } } }, - "Unread only" : { + "Pace: tight" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "未読のみ" + "value" : "消費ペースやや速め" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Только непрочитанные" + "value" : "Темп высокий" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "仅未读" + "value" : "消耗较快" } } } }, - "Unread Only" : { + "Profile name" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "未読のみ" + "value" : "プロファイル名" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Только непрочитанные" + "value" : "Название профиля" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "仅未读" + "value" : "预设名称" } } } }, - "Unstaged" : { + "Profiles" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "未ステージ" + "value" : "プロファイル" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Вне индекса" + "value" : "Профили" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "未暂存" + "value" : "配置预设" } } } }, - "Unstaged (%lld)" : { + "Review Comments" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "未ステージ(%lld)" + "value" : "レビューコメント" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Вне индекса (%lld)" + "value" : "Комментарии ревью" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "未暂存(%lld)" + "value" : "评审评论" } } } }, - "Up" : { + "Review comment" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "上へ" + "value" : "レビューコメント" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Вверх" + "value" : "Комментарий ревью" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "上一级" + "value" : "评审评论" } } } }, - "Upgrade and restart this machine's HAPI runner before creating sessions." : { + "Runs out %@" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "セッションを作成する前に、このマシンの HAPI runner をアップグレードして再起動してください。" + "value" : "%@ 頃に枯渇見込み" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Обновите и перезапустите раннер HAPI этой машины перед созданием сессий." + "value" : "Закончится %@" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "创建会话前,请升级并重启此机器上的 HAPI runner。" + "value" : "预计 %@ 用尽" } } } }, - "Upload failed — check the hub connection" : { + "Save Current as Profile…" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "アップロードに失敗しました — Hub への接続を確認してください" + "value" : "現在の設定をプロファイルとして保存…" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ошибка загрузки — проверьте подключение к хабу" + "value" : "Сохранить текущее как профиль…" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "上传失败 — 请检查 Hub 连接" + "value" : "将当前配置保存为预设…" } } } }, - "Uploading…" : { + "Save Profile" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "アップロード中…" + "value" : "プロファイルを保存" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Загрузка…" + "value" : "Сохранить профиль" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "上传中…" + "value" : "保存预设" } } } }, - "Usage" : { + "Save the current model, effort, and permission mode for quick reuse." : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "使用量" + "value" : "現在のモデル、推論レベル、権限モードを保存してすばやく再利用します。" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Использование" + "value" : "Сохраните текущие модель, уровень усилий и режим разрешений для быстрого повторного использования." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "用量" + "value" : "保存当前模型、思考强度和权限模式,方便随时一键套用。" } } } }, - "Use selected directory as-is" : { + "Search Conversation" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "選択したディレクトリをそのまま使用" + "value" : "会話を検索" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Использовать выбранный каталог как есть" + "value" : "Поиск по диалогу" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "直接使用选定的目录" + "value" : "搜索对话" } } } }, - "Uses dangerous agent flags when spawning." : { + "Search Failed" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "起動時に危険なエージェントフラグを使用します。" + "value" : "検索に失敗しました" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Использует опасные флаги агента при запуске." + "value" : "Ошибка поиска" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "启动时使用危险的代理标志。" + "value" : "搜索失败" } } } }, - "Uses dangerous agent flags when spawning. Applies native %@ mode." : { + "Search messages…" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "起動時に危険なエージェントフラグを使用します。ネイティブの %@ モードを適用します。" + "value" : "メッセージを検索…" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Использует опасные флаги агента при запуске. Применяет нативный режим %@." + "value" : "Поиск сообщений…" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "启动时使用危险的代理标志。将应用原生 %@ 模式。" + "value" : "搜索消息…" } } } }, - "Version mismatch" : { + "Search models…" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "バージョンが一致しません" + "value" : "モデルを検索…" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Несовпадение версий" + "value" : "Поиск моделей…" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "版本不匹配" + "value" : "搜索模型…" } } } }, - "View agent process" : { + "Searching messages…" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "サブエージェントの処理を表示" + "value" : "メッセージを検索中…" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать процесс агента" + "value" : "Поиск сообщений…" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看子代理执行过程" + "value" : "正在搜索消息…" } } } }, - "View all" : { + "Skills" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "すべて表示" + "value" : "スキル" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать все" + "value" : "Навыки" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看全部" + "value" : "技能" } } } }, - "View current file" : { + "Tap any line to add a review comment" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "現在のファイルを表示" + "value" : "行をタップしてレビューコメントを追加" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать текущий файл" + "value" : "Нажмите на строку, чтобы добавить комментарий" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看当前文件" + "value" : "点击任意代码行添加评审评论" } } } }, - "View full input" : { + "Tip" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "入力全文を表示" + "value" : "ヒント" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать полный ввод" + "value" : "Совет" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看完整输入" + "value" : "提示" } } } }, - "View full message" : { + "Transcribe and send" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "メッセージ全文を表示" + "value" : "文字起こしして送信" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать сообщение целиком" + "value" : "Распознать и отправить" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看完整消息" + "value" : "转写并发送" } } } }, - "View full questions and answers" : { + "Transcribe to composer" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "質問と回答の全文を表示" + "value" : "入力欄に文字起こし" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать все вопросы и ответы" + "value" : "Распознать в поле ввода" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看完整问题与回答" + "value" : "转写到输入框" } } } }, - "View image" : { + "Unavailable" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "画像を表示" + "value" : "利用不可" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать изображение" + "value" : "Недоступно" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看图片" + "value" : "不可用" } } } }, - "View process · %lld steps" : { + "Warning" : { "extractionState" : "manual", "localizations" : { "ja" : { - "variations" : { - "plural" : { - "other" : { - "stringUnit" : { - "state" : "translated", - "value" : "処理を表示 · %lld ステップ" - } - } - } + "stringUnit" : { + "state" : "translated", + "value" : "警告" } }, "ru" : { - "variations" : { - "plural" : { - "few" : { - "stringUnit" : { - "state" : "translated", - "value" : "Показать процесс · %lld шага" - } - }, - "many" : { - "stringUnit" : { - "state" : "translated", - "value" : "Показать процесс · %lld шагов" - } - }, - "one" : { - "stringUnit" : { - "state" : "translated", - "value" : "Показать процесс · %lld шаг" - } - }, - "other" : { - "stringUnit" : { - "state" : "translated", - "value" : "Показать процесс · %lld шага" - } - } - } + "stringUnit" : { + "state" : "translated", + "value" : "Предупреждение" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看过程 · %lld 个步骤" + "value" : "注意" } } } }, - "View the full draft" : { + "You" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "下書きの全文を表示" + "value" : "あなた" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать черновик целиком" + "value" : "Вы" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看草稿全文" + "value" : "你" } } } }, - "View tool details" : { + "Delete Profile" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ツールの詳細を表示" + "value" : "プロファイルを削除" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать детали инструмента" + "value" : "Удалить профиль" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看工具详情" + "value" : "删除预设" } } } }, - "View tool group" : { + "1 unavailable" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ツールグループを表示" + "value" : "1 件利用不可" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Показать группу инструментов" + "value" : "1 недоступно" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "查看工具组" + "value" : "1 项不可用" } } } }, - "Wait for agent" : { + "%lld unavailable" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "エージェントを待機" + "value" : "%lld 件利用不可" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ждать агента" + "value" : "Недоступно: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "等待代理" + "value" : "%lld 项不可用" } } } }, - "Wait for result" : { + "1 machine unavailable" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "結果を待機" + "value" : "1 台のマシンが利用不可" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ждать результат" + "value" : "1 машина недоступна" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "等待结果" + "value" : "1 台机器不可用" } } } }, - "Waiting for output…" : { + "%lld machines unavailable" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "出力を待機中…" + "value" : "%lld 台のマシンが利用不可" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ожидание вывода…" + "value" : "Недоступно машин: %lld" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "等待输出…" + "value" : "%lld 台机器不可用" } } } }, - "Web fetch" : { + "1 other machine" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Web 取得" + "value" : "他のマシン 1 台" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Веб-запрос" + "value" : "Ещё 1 машина" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "获取网页" + "value" : "其他 1 台机器" } } } }, - "Web search" : { + "%lld other machines" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Web 検索" + "value" : "他のマシン %lld 台" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Веб-поиск" + "value" : "Другие машины (%lld)" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "网络搜索" + "value" : "其他 %lld 台机器" } } } }, - "Workspace file" : { + "Show full details" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ワークスペースのファイル" + "value" : "詳細をすべて表示" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Файл рабочего пространства" + "value" : "Показать подробности" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "工作区文件" + "value" : "展开完整详情" } } } }, - "Workspace Roots" : { + "Hide full details" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ワークスペースルート" + "value" : "詳細を隠す" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Корни рабочего пространства" + "value" : "Скрыть подробности" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "工作区根目录" + "value" : "收起完整详情" } } } }, - "Worktree" : { + "Input requests" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Worktree" + "value" : "入力リクエスト" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Worktree" + "value" : "Запросы ввода" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "工作树" + "value" : "提问与输入请求" } } } }, - "Worktree sessions require an existing repository directory." : { + "Model errors" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Worktreeのセッションには、既存のリポジトリのディレクトリが必要です。" + "value" : "モデルエラー" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Для сессий worktree нужен существующий каталог репозитория." + "value" : "Ошибки модели" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "工作树会话需要已存在的仓库目录。" + "value" : "模型错误" } } } }, - "Write draft" : { + "Permission requests" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "下書きを書く" + "value" : "権限リクエスト" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Написать черновик" + "value" : "Запросы разрешений" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "写草稿" + "value" : "权限审批请求" } } } }, - "Write file" : { + "Ready for input" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "ファイルを書き込み" + "value" : "入力待ち" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Запись файла" + "value" : "Готово к вводу" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "写入文件" + "value" : "完成并等待输入" } } } }, - "Write-ahead log" : { + "Clear Screen" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "先行書き込みログ" + "value" : "画面をクリア" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Журнал упреждающей записи" + "value" : "Очистить экран" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "预写日志" + "value" : "清屏" } } } }, - "You already have a draft" : { + "Connecting" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "入力欄にすでに内容があります" + "value" : "接続中" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "У вас уже есть черновик" + "value" : "Подключение" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "输入框中已有内容" + "value" : "正在连接" } } } }, - "Your answer" : { + "Connection error" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "あなたの回答" + "value" : "接続エラー" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ваш ответ" + "value" : "Ошибка подключения" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "你的回答" + "value" : "连接错误" } } } }, - "Your input changed — review it and try again" : { + "Copy Screen" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "入力内容が変更されました — 確認してもう一度お試しください" + "value" : "画面をコピー" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ваш ввод изменился — проверьте его и попробуйте снова" + "value" : "Скопировать экран" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "输入内容已发生变化,请检查后重试" + "value" : "复制屏幕内容" } } } }, - "Enter Hub address manually" : { + "Disconnected" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Hub のアドレスを手動で入力" + "value" : "未接続" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ввести адрес хаба вручную" + "value" : "Отключено" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "手动输入 Hub 地址" + "value" : "已断开" } } } }, - "Hub address needed" : { + "Hide keyboard" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Hub のアドレスが必要です" + "value" : "キーボードを隠す" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Нужен адрес хаба" + "value" : "Скрыть клавиатуру" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "需要 Hub 地址" + "value" : "隐藏键盘" } } } }, - "Passkey for another hub" : { + "Larger Text" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "別の Hub のパスキー" + "value" : "文字を大きく" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ключ доступа другого хаба" + "value" : "Увеличить шрифт" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "属于其他 Hub 的通行密钥" + "value" : "增大字号" } } } }, - "This passkey does not include its hub address. Enter the hub URL, then sign in with the same passkey." : { + "Latest" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このパスキーには Hub のアドレスが含まれていません。Hub の URL を入力してから、同じパスキーでサインインしてください。" + "value" : "最新" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот ключ доступа не содержит адрес своего хаба. Введите URL хаба и войдите с тем же ключом." + "value" : "Вниз" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此通行密钥未包含其 Hub 地址。请输入 Hub URL,然后使用同一通行密钥登录。" + "value" : "最新" } } } }, - "This passkey belongs to a different hub. Choose a passkey for this hub, or check the hub address." : { + "Paste" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "このパスキーは別の Hub のものです。この Hub のパスキーを選択するか、Hub のアドレスを確認してください。" + "value" : "ペースト" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Этот ключ доступа принадлежит другому хабу. Выберите ключ для этого хаба или проверьте адрес." + "value" : "Вставить" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "此通行密钥属于其他 Hub。请选择此 Hub 的通行密钥,或检查 Hub 地址。" + "value" : "粘贴" } } } }, - "%@: Update the runner to view quotas." : { + "Reconnect" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%@:クォータを表示するには runner を更新してください。" + "value" : "再接続" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "%@: обновите runner для просмотра квот." + "value" : "Переподключиться" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "%@:更新 runner 以查看配额。" + "value" : "重新连接" } } } }, - "%lld%% remaining · %lld%% used" : { + "Reset Text Size" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "残り %1$lld%% · 使用済み %2$lld%%" + "value" : "文字サイズをリセット" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Осталось %1$lld%% · использовано %2$lld%%" + "value" : "Сбросить размер шрифта" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "剩余 %1$lld%% · 已用 %2$lld%%" + "value" : "重置字号" } } } }, - "CLI account quotas" : { + "Restart Shell" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "CLI アカウントのクォータ" + "value" : "シェルを再起動" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Квоты аккаунтов CLI" + "value" : "Перезапустить оболочку" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "CLI 账户配额" + "value" : "重启 Shell" } } } }, - "Custom endpoint / API key" : { + "Send Screen to Chat" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "カスタムエンドポイント / API キー" + "value" : "画面をチャットに送る" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Свой адрес API / ключ API" + "value" : "Отправить экран в чат" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "自定义端点 / API 密钥" + "value" : "发送屏幕到聊天" } } } }, - "Last loaded quotas" : { + "Send to Chat" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "前回取得したクォータ" + "value" : "チャットに送る" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Последние загруженные квоты" + "value" : "Отправить в чат" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "上次加载的配额" + "value" : "发送到聊天" } } } }, - "Loading quotas" : { + "Shell" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "クォータを読み込み中" + "value" : "シェル" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Загрузка квот" + "value" : "Оболочка" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "正在加载配额" + "value" : "Shell" } } } }, - "No online machines reported CLI accounts." : { + "Shell exited" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "CLI アカウントを報告したオンラインのマシンはありません。" + "value" : "シェルが終了しました" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Ни одна машина в сети не сообщила об аккаунтах CLI." + "value" : "Оболочка завершила работу" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "没有在线机器报告 CLI 账户。" + "value" : "Shell 已退出" } } } }, - "Not signed in" : { + "Shell exited (%@)" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "未ログイン" + "value" : "シェルが終了しました (%@)" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Вход не выполнен" + "value" : "Оболочка завершила работу (%@)" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "未登录" + "value" : "Shell 已退出 (%@)" } } } }, - "Only the hub owner can view CLI account quotas." : { + "Shell exited (code %lld)" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "CLI アカウントのクォータを表示できるのはハブの所有者のみです。" + "value" : "シェルが終了しました (コード %lld)" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Просматривать квоты аккаунтов CLI может только владелец хаба." + "value" : "Оболочка завершила работу (код %lld)" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "仅 Hub 所有者可查看 CLI 账户配额。" + "value" : "Shell 已退出 (退出码 %lld)" } } } }, - "Quota unavailable" : { + "Show keyboard" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "クォータを取得できません" + "value" : "キーボードを表示" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Квота недоступна" + "value" : "Показать клавиатуру" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "配额不可用" + "value" : "显示键盘" } } } }, - "Refresh quotas" : { + "Smaller Text" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "クォータを更新" + "value" : "文字を小さく" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Обновить квоты" + "value" : "Уменьшить шрифт" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "刷新配额" + "value" : "减小字号" } } } }, - "Resets %@" : { + "Terminal Mode" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%@ にリセット" + "value" : "ターミナルモード" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Сброс %@" + "value" : "Режим терминала" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "%@ 重置" + "value" : "终端模式" } } } }, - "Update the hub to view CLI account quotas." : { + "Terminal actions" : { "extractionState" : "manual", "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "CLI アカウントのクォータを表示するにはハブを更新してください。" + "value" : "ターミナル操作" } }, "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Обновите хаб для просмотра квот аккаунтов CLI." + "value" : "Действия терминала" } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "更新 Hub 以查看 CLI 账户配额。" + "value" : "终端操作" } } } diff --git a/ios/HapiTests/HomeFilterPresentationTests.swift b/ios/HapiTests/HomeFilterPresentationTests.swift index 491e77a7983..6eca918a9a9 100644 --- a/ios/HapiTests/HomeFilterPresentationTests.swift +++ b/ios/HapiTests/HomeFilterPresentationTests.swift @@ -204,6 +204,68 @@ final class HomeFilterPresentationTests: XCTestCase { } } + /// Folded and open groups under a project header: a folded leader rolls + /// member unread onto its title, an open one shows only its member count. + func testGroupLayoutSpecimens() async throws { + let suite = "home-group-specimens-\(UUID())" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let now = Int(Date.now.timeIntervalSince1970 * 1_000) + func session(_ id: String, _ name: String, flavor: String = "claude", path: String = "/work/neo-twoyi", + leader: String? = nil, worktree: String? = nil, minutesAgo: Int, + thinking: Bool = false, waiting: Bool = false) -> SessionSummary { + var row = HomeFilterTestData.summary(id, machine: "mac") + row.metadata?.name = name + row.metadata?.flavor = flavor + row.metadata?.path = worktree.map { "/work/neo-twoyi-wt/\($0)" } ?? path + row.metadata?.groupLeaderId = leader + row.metadata?.worktree = worktree.map { WorktreeMetadata(basePath: path, branch: $0, name: $0) } + row.updatedAt = now - minutesAgo * 60_000 + row.thinking = thinking + row.pendingRequestsCount = waiting ? 1 : 0 + row.pendingRequestKinds = waiting ? [.permission] : [] + // Unseen content: members of both groups have unread replies. + row.contentRevision = ["f1", "f2", "f3", "o1", "o2"].contains(id) ? 2 : nil + return row + } + let sessions = HomeFilterTestSessions([ + session("folded", "silike: 对齐 UIKit/SwiftUI 外观与 iOS 规范", minutesAgo: 0), + session("f1", "Audit tab bar", leader: "folded", worktree: "1203-a1", minutesAgo: 1, waiting: true), + session("f2", "Port toolbar", leader: "folded", worktree: "1203-a2", minutesAgo: 2, thinking: true), + session("f3", "Fix list insets", leader: "folded", worktree: "1203-a3", minutesAgo: 3, thinking: true), + session("f4", "Check sheets", leader: "folded", worktree: "1203-a4", minutesAgo: 4, thinking: true), + session("plain", "湘办通闪退:/proc/maps 中 exec 映射", minutesAgo: 26), + session("asking", "分析 Web 版在 Safari 的启动失败", flavor: "codex", minutesAgo: 27, waiting: true), + session("open", "调研:用户态网络栈(web 联网 + iOS)", minutesAgo: 46), + session("o1", "Finish Android VpnService support", leader: "open", worktree: "1203-198f", + minutesAgo: 46, thinking: true), + session("o2", "Build the numbered iOS VpnService", flavor: "codex", path: "/work/ios-twoyi-13", + leader: "open", minutesAgo: 60), + session("o3", "Review and validate work/net-m", flavor: "codex", leader: "open", worktree: "1203-b7be", + minutesAgo: 4), + ]) + let model = SessionListModel( + sessionStore: sessions, + machineStore: HomeFilterTestMachines([HomeFilterTestData.machine("mac", host: "mac")]), + lastSeenStore: LastSeenStore(), + openGroupStore: SessionGroupOpenStore(scope: "test", defaults: defaults), + hubUrl: "test" + ) + model.toggleMemberList(leaderId: "open", currentlyOpen: false) + let folded = try XCTUnwrap(model.listSnapshot.recentItems.lazy.compactMap { item -> SessionGroupSummaryUI? in + if case .session(let row, let group, _) = item, row.id == "folded" { return group } + return nil + }.first) + XCTAssertEqual(folded.status, SessionGroupStatus(waiting: 1, working: 3, unread: 3)) + for (name, theme) in [("groups-dark", HapiTheme.dark), ("groups-light", HapiTheme.light)] { + let window = try makeWindow(Harness(model: model, navigation: Navigation(), theme: theme), width: 402) + defer { window.isHidden = true } + try await settle() + XCTAssertNotNil(findCollection(window)) + try capture(window, name: name) + } + } + private func makeWindow(_ view: V, width: CGFloat) throws -> UIWindow { let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) let window = UIWindow(windowScene: scene) diff --git a/ios/HapiTests/MarkdownTableLayoutTests.swift b/ios/HapiTests/MarkdownTableLayoutTests.swift new file mode 100644 index 00000000000..84959ba3c44 --- /dev/null +++ b/ios/HapiTests/MarkdownTableLayoutTests.swift @@ -0,0 +1,89 @@ +import HapiUI +import SwiftUI +import UIKit +import XCTest +@testable import Hapi + +/// Table rows must grow with cells that wrap at the column width cap, +/// instead of keeping a one-line height while the text overflows below. +@MainActor +final class MarkdownTableLayoutTests: XCTestCase { + private static let longCell = String( + repeating: "键盘推动布局:先在 gallery 里加一个会被键盘推起的输入框,再对齐 frame 与通知。", + count: 3 + ) + + private static let sample = """ + 第二轮已派出,候选 1、2、4、5 分给原来的三个成员。 + + | 成员 | 这一轮做什么 | + | --- | --- | + | [UIKit gallery 成员](https://example.com) | **1 键盘推动布局**:\(longCell) | + | [UIKit 应用成员](https://example.com) | **2 根页面空导航栏多占 54 pt**(What's New):通知面、连带 Aidoku History 和 Settings。 | + | [SwiftUI 成员](https://example.com) | 短 | + + 两点说明: + + - **键盘的范围**:只对齐应用能观察到的东西(frame、通知、layout guide、inset)。键盘自身的按键绘制不做。 + - **可能的冲突**:应用成员和 SwiftUI 成员都可能碰 UIKit 的导航栏代码。 + - 嵌套:合并时由我处理。 + - [x] 已确认 checkbox item + + 9. 第九项(两位数标记要对齐) + 10. 第十项,换行很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的一行 + 11. 第十一项 + """ + + private func host(_ markdown: String, width: CGFloat, theme: HapiTheme = .dark, + topInset: CGFloat = 0) -> UIHostingController { + UIHostingController(rootView: MarkdownView(markdown: markdown) + .padding(.horizontal, 16) + .padding(.top, topInset) + .frame(width: width, alignment: .leading) + .background(theme.background) + .hapiTypography() + .hapiTheme(theme) + .environment(\.colorScheme, theme.isDark ? .dark : .light) + .ignoresSafeArea()) + } + + private func height(_ markdown: String, width: CGFloat) -> CGFloat { + host(markdown, width: width).sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude)).height + } + + func testRowsGrowWithCellsWrappedAtTheColumnCap() { + let table = { (cell: String) in "| A | B |\n| --- | --- |\n| x | \(cell) |" } + let short = height(table("短"), width: 390) + let long = height(table(Self.longCell), width: 390) + // ~110 CJK characters wrap to 6+ lines inside the 300 pt column. + XCTAssertGreaterThan(long - short, 80, "A wrapped cell must make its row taller") + } + + /// Opt-in specimen: `TEST_RUNNER_HAPI_MARKDOWN_CAPTURE=/tmp/…`. + func testCaptureTableAndListSpecimen() async throws { + let path = ProcessInfo.processInfo.environment["HAPI_MARKDOWN_CAPTURE"] + try XCTSkipIf(path == nil, "Opt in with TEST_RUNNER_HAPI_MARKDOWN_CAPTURE=/tmp/…") + let directory = URL(fileURLWithPath: try XCTUnwrap(path), isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + // Accessibility sizes are covered by TypographySnapshotTests, which + // hosts the transcript in a scroll view like the chat screen does. + for (name, theme) in [("markdown-dark", HapiTheme.dark), ("markdown-light", HapiTheme.light)] { + let width: CGFloat = 390 + let controller = host(Self.sample, width: width, theme: theme, topInset: 60) + let size = controller.sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude)) + let window = UIWindow(windowScene: scene) + window.frame = CGRect(origin: .zero, size: CGSize(width: width, height: ceil(size.height) + 32)) + window.rootViewController = controller + window.makeKeyAndVisible() + defer { window.isHidden = true } + controller.view.frame = window.bounds + controller.view.layoutIfNeeded() + try await Task.sleep(for: .milliseconds(250)) + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try XCTUnwrap(image.pngData()).write(to: directory.appendingPathComponent(name + ".png")) + } + } +} diff --git a/ios/HapiTests/NotificationRoutingTests.swift b/ios/HapiTests/NotificationRoutingTests.swift index 0825a1e9b88..ea86957de77 100644 --- a/ios/HapiTests/NotificationRoutingTests.swift +++ b/ios/HapiTests/NotificationRoutingTests.swift @@ -91,4 +91,51 @@ final class NotificationRoutingTests: XCTestCase { XCTAssertEqual(model.state, .paired(activeHub: hubB)) XCTAssertEqual(model.pendingOpenSessionId, "s-y") } + + func testHubIdRoutesDirectlyInO1WithoutProbingOtherHubs() async throws { + let suiteName = "NotificationRoutingTests-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let hubC = "https://c.example.com" + let registry = HubRegistry(defaults: defaults) + registry.register(hubA) + registry.register(hubC) + registry.register(hubB) + registry.setActiveHub(hubA) + registry.setHubId("hub-a-uuid", for: hubA) + registry.setHubId("hub-b-uuid", for: hubB) + + // Direct tap target resolves hubB in O(1) even while hubA is active. + XCTAssertEqual(PushCoordinator.directTapTarget(forHubId: "hub-b-uuid", registry: registry), hubB) + XCTAssertNil(PushCoordinator.directTapTarget(forHubId: "hub-unknown", registry: registry)) + XCTAssertNil(PushCoordinator.directTapTarget(forHubId: nil, registry: registry)) + + // Action candidates target only hubB — never probing hubA or offline hubC. + let candidates = PushCoordinator.candidateHubs(forHubId: "hub-b-uuid", registry: registry) + XCTAssertEqual(candidates, [hubB]) + + let http = OwnerHTTP() + let runner = PushActionRunner( + hubs: candidates, + credentialStore: try credentials([hubA, hubC, hubB]), + performer: http + ) + guard case .success(let owner) = await runner.locate(sessionId: "s-b") else { + return XCTFail("hub B should respond directly") + } + XCTAssertEqual(owner, hubB) + let lookups = await http.sessionLookups + XCTAssertEqual(lookups, ["b.example.com"]) + + // Unknown / absent hubId falls back to all paired hubs (active first). + XCTAssertEqual( + PushCoordinator.candidateHubs(forHubId: "hub-unknown", registry: registry), + [hubA, hubC, hubB] + ) + XCTAssertEqual( + PushCoordinator.candidateHubs(forHubId: nil, registry: registry), + [hubA, hubC, hubB] + ) + } } diff --git a/ios/HapiTests/SessionGroupListTests.swift b/ios/HapiTests/SessionGroupListTests.swift new file mode 100644 index 00000000000..c61e071bfd6 --- /dev/null +++ b/ios/HapiTests/SessionGroupListTests.swift @@ -0,0 +1,361 @@ +import HapiClient +import HapiProtocol +import XCTest +@testable import Hapi + +@MainActor +final class SessionGroupListTests: XCTestCase { + private func summary( + _ id: String, + name: String, + path: String = "/work/proj", + machine: String? = "mac", + active: Bool = true, + thinking: Bool = false, + updatedAt: Int = 1_000, + lastUserMessageAt: Int? = nil, + pinned: Bool? = nil, + globalPinned: Bool? = nil, + groupLeaderId: String? = nil, + lifecycleState: String? = nil, + worktree: WorktreeMetadata? = nil, + pendingRequestsCount: Int = 0, + pendingRequestKinds: [PendingRequestKind] = [], + contentRevision: Int? = nil, + derivedToolWork: Bool? = nil + ) -> SessionSummary { + SessionSummary( + contentRevision: contentRevision, + id: id, + active: active, + thinking: thinking, + activeAt: 1_000, + updatedAt: updatedAt, + createdAt: updatedAt, + lastUserMessageAt: lastUserMessageAt ?? updatedAt, + pinned: pinned, + globalPinned: globalPinned, + metadata: SessionSummaryMetadata( + name: name, + path: path, + machineId: machine, + flavor: "claude", + worktree: worktree, + groupLeaderId: groupLeaderId, + lifecycleState: lifecycleState + ), + metadataVersion: 1, + agentStateVersion: 1, + todosUpdatedAt: 0, + pendingRequestsCount: pendingRequestsCount, + pendingRequestKinds: pendingRequestKinds, + derivedToolWork: derivedToolWork + ) + } + + private func groupFixture() -> [SessionSummary] { + [ + summary("leader", name: "Release leader", updatedAt: 300), + summary("member-a", name: "Fix login", updatedAt: 200, groupLeaderId: "leader"), + summary("member-b", name: "Update docs", path: "/work/other", machine: "debian", updatedAt: 100, groupLeaderId: "leader"), + ] + } + + /// The member summary carried by the leader's own row. + private func memberBar(in snapshot: SessionListSnapshot, leaderId: String) -> SessionGroupSummaryUI? { + for item in snapshot.pinnedItems + snapshot.recentItems { + if case .session(let row, let group, _) = item, row.id == leaderId { + return group + } + } + return nil + } + + /// The row's precomputed dissolve flag, which the context menu reads. + private func rowCanDissolve(in snapshot: SessionListSnapshot, sessionId: String) -> Bool? { + for item in snapshot.pinnedItems + snapshot.recentItems { + if case .session(let row, _, let canDissolve) = item, row.id == sessionId { + return canDissolve + } + } + return nil + } + + private func members(in snapshot: SessionListSnapshot, leaderId: String) -> [SessionMemberRowUI] { + (snapshot.pinnedItems + snapshot.recentItems).compactMap { item in + if case .groupMember(let member) = item, member.leaderId == leaderId { + return member + } + return nil + } + } + + private func waitUntil(_ condition: @MainActor () -> Bool, file: StaticString = #filePath, line: UInt = #line) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } + XCTAssertTrue(condition(), file: file, line: line) + } + + func testRowSubtitleShowsWorktreeAfterProject() { + let sessions = HomeFilterTestSessions([ + summary("plain", name: "Plain", updatedAt: 300), + summary("named", name: "Named", path: "/work/proj-wt/feature", updatedAt: 200, + worktree: WorktreeMetadata(basePath: "/work/proj", branch: "feature", name: "feature")), + // A blank name falls back to the checkout directory, as on web. + summary("unnamed", name: "Unnamed", path: "/tmp/wt/checkout-2", updatedAt: 100, + worktree: WorktreeMetadata(basePath: "/work/proj", branch: "x", name: " ")), + ]) + let model = HomeFilterTestData.model(sessions: sessions) + XCTAssertEqual(model.rows.map(\.subtitle), ["proj", "proj · feature", "proj · checkout-2"]) + } + + func testProjectHeaderImpliesProjectOnlyWhereSomethingElseFillsTheLine() throws { + let sessions = HomeFilterTestSessions(groupFixture() + [ + summary("plain", name: "Plain", updatedAt: 250), + summary("wt", name: "Worktree", path: "/work/proj-wt/feature", updatedAt: 240, + worktree: WorktreeMetadata(basePath: "/work/proj", branch: "feature", name: "feature")), + ]) + let model = HomeFilterTestData.model(sessions: sessions) + model.toggleMemberList(leaderId: "leader", currentlyOpen: false) + + var sectionRows: [String: (row: SessionRowUI, hasGroup: Bool)] = [:] + for section in model.listSnapshot.projectSections { + for item in section.items { + switch item { + case .session(let row, let group, _): sectionRows[row.id] = (row, group != nil) + case .groupMember(let member): sectionRows[member.id] = (member.row, false) + } + } + } + func detail(_ id: String) throws -> String? { + let entry = try XCTUnwrap(sectionRows[id]) + return entry.row.detailSubtitle(hasGroup: entry.hasGroup) + } + // The leader's member summary and a worktree replace the header's project. + XCTAssertNil(try detail("leader")) + XCTAssertEqual(try detail("wt"), "feature") + // A plain row keeps it rather than leaving an empty line. + XCTAssertEqual(try detail("plain"), "proj") + // A member nested under another project's header keeps its own project. + XCTAssertEqual(try detail("member-a"), "proj") + XCTAssertEqual(try detail("member-b"), "other") + XCTAssertEqual(sectionRows["member-a"]?.row.projectImplied, true) + XCTAssertEqual(sectionRows["member-b"]?.row.projectImplied, false) + // Rows outside project sections (pinned, search) keep the full text. + XCTAssertEqual(model.rows.first { $0.id == "wt" }?.detailSubtitle(hasGroup: false), "proj · feature") + } + + func testFoldsMembersByDefaultPersistsOpenStateAndShowsMemberProjects() throws { + let suite = "session-group-list-\(UUID())" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + + let sessions = HomeFilterTestSessions(groupFixture()) + let machines = HomeFilterTestMachines([ + HomeFilterTestData.machine("mac", host: "MacBook"), + HomeFilterTestData.machine("debian", host: "debian"), + ]) + let model = SessionListModel( + sessionStore: sessions, + machineStore: machines, + lastSeenStore: LastSeenStore(), + openGroupStore: SessionGroupOpenStore(scope: "test", defaults: defaults), + hubUrl: "test" + ) + + XCTAssertEqual(model.rows.map(\.id), ["leader"]) + XCTAssertEqual(model.displayedSessionIds, ["leader"]) + let foldedBar = try XCTUnwrap(memberBar(in: model.listSnapshot, leaderId: "leader")) + XCTAssertEqual(foldedBar.memberCount, 2) + XCTAssertTrue(foldedBar.isExpandable) + XCTAssertFalse(foldedBar.isExpanded) + XCTAssertTrue(members(in: model.listSnapshot, leaderId: "leader").isEmpty) + + model.toggleMemberList(leaderId: "leader", currentlyOpen: false) + XCTAssertEqual(model.displayedSessionIds, ["leader", "member-a", "member-b"]) + let expandedMembers = members(in: model.listSnapshot, leaderId: "leader") + XCTAssertEqual(expandedMembers.map(\.id), ["member-a", "member-b"]) + XCTAssertEqual(expandedMembers.map(\.row.project), ["proj", "other"]) + // Only the last member draws the separator that closes the group. + XCTAssertEqual(expandedMembers.map(\.isLast), [false, true]) + + // Reloading with the same scope restores the explicitly opened group. + let reloaded = SessionListModel( + sessionStore: sessions, + machineStore: machines, + lastSeenStore: LastSeenStore(), + openGroupStore: SessionGroupOpenStore(scope: "test", defaults: defaults), + hubUrl: "test" + ) + XCTAssertEqual(reloaded.displayedSessionIds, ["leader", "member-a", "member-b"]) + } + + func testReportsWaitingWorkingAndUnreadCountsOnFoldedBar() throws { + let sessions = HomeFilterTestSessions([ + summary("leader", name: "Release leader", updatedAt: 400), + summary("waiting", name: "Approve bash", updatedAt: 300, groupLeaderId: "leader", + pendingRequestsCount: 1, pendingRequestKinds: [.permission], contentRevision: 2), + summary("working", name: "Run tests", thinking: true, updatedAt: 200, groupLeaderId: "leader"), + summary("tools", name: "Open tool", updatedAt: 150, groupLeaderId: "leader", derivedToolWork: true), + summary("unread", name: "Finished", updatedAt: 100, groupLeaderId: "leader", contentRevision: 3), + ]) + let model = HomeFilterTestData.model(sessions: sessions) + let bar = try XCTUnwrap(memberBar(in: model.listSnapshot, leaderId: "leader")) + XCTAssertEqual(bar.memberCount, 4) + XCTAssertEqual(bar.status, SessionGroupStatus(waiting: 1, working: 2, unread: 2)) + } + + func testSearchKeepsLeaderContainerRanksByBestMemberAndDoesNotPersistFilterFolds() throws { + let sessions = HomeFilterTestSessions([ + summary("path-only", name: "Unrelated", path: "/work/proj/zebra", updatedAt: 900), + summary("leader", name: "Release leader", path: "/work/proj/zebra", updatedAt: 300), + summary("weak-member", name: "Other work", path: "/work/proj/zebra", updatedAt: 800, groupLeaderId: "leader"), + summary("exact-member", name: "zebra", path: "/work/proj/zebra", updatedAt: 100, groupLeaderId: "leader"), + ]) + let model = HomeFilterTestData.model(sessions: sessions) + + // Manually open then fold before searching. + model.toggleMemberList(leaderId: "leader", currentlyOpen: false) + model.toggleMemberList(leaderId: "leader", currentlyOpen: true) + XCTAssertEqual(model.displayedSessionIds, ["path-only", "leader"]) + + model.searchQuery = "zebra" + XCTAssertEqual(model.displayedSessionIds, ["leader", "exact-member", "weak-member", "path-only"]) + XCTAssertTrue(try XCTUnwrap(memberBar(in: model.listSnapshot, leaderId: "leader")).isExpanded) + + // Folding during search is transient and ends with the search. + model.toggleMemberList(leaderId: "leader", currentlyOpen: true) + XCTAssertEqual(model.displayedSessionIds, ["leader", "path-only"]) + model.searchQuery = "" + XCTAssertEqual(model.displayedSessionIds, ["path-only", "leader"]) + model.searchQuery = "zebra" + XCTAssertEqual(model.displayedSessionIds, ["leader", "exact-member", "weak-member", "path-only"]) + } + + func testShowFilterLeavesMembersAsOrdinaryRowsWhenLeaderIsHidden() { + let sessions = HomeFilterTestSessions([ + summary("leader", name: "Archived leader", active: false, updatedAt: 300, lifecycleState: "archived"), + summary("member", name: "Active member", active: true, updatedAt: 200, groupLeaderId: "leader"), + ]) + let model = HomeFilterTestData.model(sessions: sessions) + XCTAssertEqual(model.rows.map(\.id), ["leader"]) + + model.setStatus(.active) + XCTAssertEqual(model.rows.map(\.id), ["member"]) + XCTAssertEqual(model.displayedSessionIds, ["member"]) + XCTAssertNil(memberBar(in: model.listSnapshot, leaderId: "leader")) + } + + func testPinnedMembersOrderingGlobalPinBreakoutAndUnpinReopensGroup() async throws { + var rows = groupFixture() + rows[2].pinned = true // member-b project-pinned + let sessions = HomeFilterTestSessions(rows) + let model = HomeFilterTestData.model(sessions: sessions) + + model.toggleMemberList(leaderId: "leader", currentlyOpen: false) + let expanded = members(in: model.listSnapshot, leaderId: "leader") + XCTAssertEqual(expanded.map(\.id), ["member-b", "member-a"]) + + // Globally pinning a member moves it to the top-level Pinned section. + model.toggleMemberList(leaderId: "leader", currentlyOpen: true) // fold leader + model.setPinMode(sessionId: "member-a", mode: .global) + await waitUntil { model.rows.map(\.id) == ["member-a", "leader"] } + XCTAssertEqual(model.listSnapshot.pinnedItems.compactMap(\.sessionId), ["member-a"]) + + // Unpinning a globally pinned member returns it and opens its leader's group. + model.setPinMode(sessionId: "member-a", mode: .none) + await waitUntil { model.displayedSessionIds == ["leader", "member-b", "member-a"] } + } + + func testPinnedLeaderKeepsMembersInsidePinnedSection() { + var rows = groupFixture() + rows[0].pinned = true + let sessions = HomeFilterTestSessions(rows) + let model = HomeFilterTestData.model(sessions: sessions) + model.toggleMemberList(leaderId: "leader", currentlyOpen: false) + + XCTAssertEqual(model.listSnapshot.pinnedItems.compactMap(\.sessionId), ["leader", "member-a", "member-b"]) + XCTAssertTrue(model.listSnapshot.recentItems.isEmpty) + } + + func testSelectingAMemberOpensItsGroupEvenAfterManualFold() { + let sessions = HomeFilterTestSessions(groupFixture()) + let model = HomeFilterTestData.model(sessions: sessions) + model.toggleMemberList(leaderId: "leader", currentlyOpen: false) + model.toggleMemberList(leaderId: "leader", currentlyOpen: true) + XCTAssertEqual(model.displayedSessionIds, ["leader"]) + + model.selectedSessionId = "member-a" + XCTAssertEqual(model.displayedSessionIds, ["leader", "member-a", "member-b"]) + } + + func testDissolvePromptActionFailureAndGlobalPinnedAvailability() async throws { + var rows = groupFixture() + rows[1].thinking = true + rows[2].metadata?.worktree = WorktreeMetadata(basePath: "/work/other", branch: "docs", name: "docs") + rows[1].globalPinned = true + rows[2].globalPinned = true + let sessions = HomeFilterTestSessions(rows) + + var archived: [String] = [] + var failMember = true + let dissolveStore = SessionGroupDissolveStore(scope: "test", defaults: nil) + let ops = SessionGroupDissolveOperations( + archiveSession: { @MainActor id in + archived.append(id) + if id == "member-a" && failMember { + throw APIError(status: 500, code: "runner busy") + } + if let index = sessions.sessions.firstIndex(where: { $0.id == id }) { + sessions.sessions[index].active = false + sessions.sessions[index].metadata?.lifecycleState = SessionLifecycle.archived + } + }, + fetchSessions: { @MainActor in sessions.sessions }, + refreshSessions: {} + ) + let model = SessionListModel( + sessionStore: sessions, + machineStore: HomeFilterTestMachines(), + lastSeenStore: LastSeenStore(), + dissolveStore: dissolveStore, + dissolveOps: ops, + nowMs: { 10_000 }, + hubUrl: "test" + ) + + // Even with every member globally pinned (non-expandable bar), dissolve stays reachable. + let bar = try XCTUnwrap(memberBar(in: model.listSnapshot, leaderId: "leader")) + XCTAssertFalse(bar.isExpandable) + XCTAssertEqual(rowCanDissolve(in: model.listSnapshot, sessionId: "leader"), true) + + let prompt = try XCTUnwrap(model.dissolvePrompt(forLeaderId: "leader")) + XCTAssertEqual(prompt.count, 3) + XCTAssertEqual(prompt.impact.working, 1) + XCTAssertEqual(prompt.impact.worktree, 1) + XCTAssertTrue(prompt.description.contains("Release leader")) + + // First attempt fails on member-a and leaves leader running. + model.dissolveGroup(leaderId: "leader") + await waitUntil { !model.dissolvingLeaderIds.contains("leader") && model.actionError != nil } + XCTAssertEqual(model.actionErrorTitle, String(localized: "Archive could not be confirmed")) + XCTAssertFalse(archived.contains("leader")) + + // Mark member-a archived on the server; unconfirmed retry still dissolves member-a then leader. + if let index = sessions.sessions.firstIndex(where: { $0.id == "member-a" }) { + sessions.sessions[index].active = false + sessions.sessions[index].metadata?.lifecycleState = SessionLifecycle.archived + } + failMember = false + archived.removeAll() + model.actionError = nil + model.actionErrorTitle = nil + model.dissolveGroup(leaderId: "leader") + await waitUntil { !model.dissolvingLeaderIds.contains("leader") && archived == ["member-a", "leader"] } + XCTAssertNil(model.actionError) + XCTAssertFalse(model.canDissolveGroup(leaderId: "leader")) + XCTAssertEqual(rowCanDissolve(in: model.listSnapshot, sessionId: "leader"), false) + XCTAssertNil(memberBar(in: model.listSnapshot, leaderId: "leader")) + } +} diff --git a/ios/HapiTests/SessionGroupPresentationTests.swift b/ios/HapiTests/SessionGroupPresentationTests.swift new file mode 100644 index 00000000000..fdca7012cc6 --- /dev/null +++ b/ios/HapiTests/SessionGroupPresentationTests.swift @@ -0,0 +1,216 @@ +import HapiClient +import HapiProtocol +import HapiUI +import Observation +import SwiftUI +import UIKit +import XCTest +@testable import Hapi + +/// Renders the real `SessionListView` with grouped leaders and members inside +/// a `UIWindow`, checking expand/collapse item counts, scroll stability, +/// compact/large-text/Chinese rendering, and split selection on nested members. +@MainActor +final class SessionGroupPresentationTests: XCTestCase { + @Observable + fileprivate final class Navigation { + var path: [String] = [] + } + + private struct Harness: View { + let model: SessionListModel + let navigation: Navigation + var theme: HapiTheme = .light + var size: DynamicTypeSize = .large + var locale = Locale(identifier: "en") + + var body: some View { + @Bindable var navigation = navigation + NavigationStack(path: $navigation.path) { + SessionListView(model: model) { navigation.path.append($0) } + .navigationTitle("Sessions") + .navigationBarTitleDisplayMode(.inline) + .navigationDestination(for: String.self) { id in Text(verbatim: id) } + } + .hapiTypography() + .hapiTheme(theme) + .environment(\.dynamicTypeSize, size) + .environment(\.locale, locale) + .environment(\.colorScheme, theme.isDark ? .dark : .light) + .preferredColorScheme(theme.isDark ? .dark : .light) + } + } + + private func makeGroupedSessions() -> [SessionSummary] { + let now = Int(Date.now.timeIntervalSince1970 * 1_000) + return [ + SessionSummary( + contentRevision: 2, + id: "leader", + active: true, + thinking: false, + activeAt: now, + updatedAt: now - 60_000, + createdAt: now - 300_000, + lastUserMessageAt: now - 60_000, + metadata: SessionSummaryMetadata(name: "Release 0.37 leader", path: "/workspace/hapi", machineId: "mac", flavor: "claude"), + metadataVersion: 1, + agentStateVersion: 1, + todosUpdatedAt: 0, + pendingRequestsCount: 0 + ), + SessionSummary( + contentRevision: 4, + id: "member-a", + active: true, + thinking: false, + activeAt: now, + updatedAt: now - 30_000, + createdAt: now - 200_000, + lastUserMessageAt: now - 30_000, + metadata: SessionSummaryMetadata( + name: "Fix login redirect", + path: "/workspace/hapi", + machineId: "mac", + flavor: "codex", + groupLeaderId: "leader" + ), + metadataVersion: 1, + agentStateVersion: 1, + todosUpdatedAt: 0, + pendingRequestsCount: 1, + pendingRequestKinds: [.permission] + ), + SessionSummary( + id: "member-b", + active: true, + thinking: true, + activeAt: now, + updatedAt: now - 10_000, + createdAt: now - 100_000, + lastUserMessageAt: now - 10_000, + metadata: SessionSummaryMetadata( + name: "Update iOS tests", + path: "/workspace/docs", + machineId: "debian", + flavor: "claude", + worktree: WorktreeMetadata(basePath: "/workspace/docs", branch: "ios-groups", name: "ios-groups"), + groupLeaderId: "leader" + ), + metadataVersion: 1, + agentStateVersion: 1, + todosUpdatedAt: 0, + pendingRequestsCount: 0 + ), + SessionSummary( + id: "solo", + active: true, + thinking: false, + activeAt: now, + updatedAt: now - 500_000, + createdAt: now - 500_000, + lastUserMessageAt: now - 500_000, + metadata: SessionSummaryMetadata(name: "Solo session", path: "/workspace/hapi", machineId: "mac", flavor: "claude"), + metadataVersion: 1, + agentStateVersion: 1, + todosUpdatedAt: 0, + pendingRequestsCount: 0 + ), + ] + } + + func testExpandingAndCollapsingGroupUpdatesItemsWithoutResettingList() async throws { + let sessions = HomeFilterTestSessions(makeGroupedSessions()) + let machines = HomeFilterTestMachines([ + HomeFilterTestData.machine("mac", host: "MacBook Pro"), + HomeFilterTestData.machine("debian", host: "debian"), + ]) + let model = HomeFilterTestData.model(sessions: sessions, machines: machines) + let window = try makeWindow(Harness(model: model, navigation: Navigation()), width: 390) + defer { window.isHidden = true } + try await settle() + + let list = try XCTUnwrap(findCollection(window)) + // Folded: leader (carrying the member summary) + solo = 2 items + XCTAssertEqual(itemCount(list), 2) + + model.toggleMemberList(leaderId: "leader", currentlyOpen: false) + try await settle() + // Expanded: leader + 2 members + solo = 4 items + let sameList = try XCTUnwrap(findCollection(window)) + XCTAssertTrue(sameList === list, "Toggling a group must keep list identity") + XCTAssertEqual(itemCount(sameList), 4) + + model.toggleMemberList(leaderId: "leader", currentlyOpen: true) + try await settle() + XCTAssertEqual(itemCount(sameList), 2) + } + + func testGroupLayoutSpecimensAcrossThemesWidthsAndLocales() async throws { + let sessions = HomeFilterTestSessions(makeGroupedSessions()) + let machines = HomeFilterTestMachines([ + HomeFilterTestData.machine("mac", host: "MacBook Pro"), + HomeFilterTestData.machine("debian", host: "debian"), + ]) + let model = HomeFilterTestData.model(sessions: sessions, machines: machines) + let cases: [(String, HapiTheme, DynamicTypeSize, CGFloat, String)] = [ + ("light", .light, .large, 402, "en"), + ("dark", .dark, .large, 402, "en"), + ("compact", .light, .large, 320, "en"), + ("large-text", .light, .accessibility3, 390, "zh-Hans"), + ("chinese", .light, .large, 390, "zh-Hans"), + ] + for (name, theme, size, width, localeId) in cases { + let window = try makeWindow( + Harness(model: model, navigation: Navigation(), theme: theme, size: size, locale: Locale(identifier: localeId)), + width: width + ) + defer { window.isHidden = true } + if model.displayedSessionIds.contains("member-a") { + model.toggleMemberList(leaderId: "leader", currentlyOpen: true) + } + try await settle() + let list = try XCTUnwrap(findCollection(window)) + XCTAssertEqual(itemCount(list), 2) + XCTAssertLessThanOrEqual(list.frame.width, width + 1) + try capture(window, name: "\(name)-folded") + + model.toggleMemberList(leaderId: "leader", currentlyOpen: false) + try await settle() + XCTAssertEqual(itemCount(list), 4) + try capture(window, name: "\(name)-expanded") + } + } + + private func makeWindow(_ view: V, width: CGFloat) throws -> UIWindow { + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + window.frame = CGRect(x: 0, y: 0, width: width, height: 874) + window.rootViewController = UIHostingController(rootView: view) + window.makeKeyAndVisible() + window.layoutIfNeeded() + return window + } + + private func itemCount(_ list: UICollectionView) -> Int { + (0.. UICollectionView? { + if let list = view as? UICollectionView { return list } + return view.subviews.lazy.compactMap(findCollection).first + } + + private func settle() async throws { + try await Task.sleep(for: .milliseconds(350)) + } + + private func capture(_ window: UIWindow, name: String) throws { + guard let path = ProcessInfo.processInfo.environment["HAPI_GROUP_CAPTURE"] else { return } + let directory = URL(fileURLWithPath: path, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let renderer = UIGraphicsImageRenderer(bounds: window.bounds) + let image = renderer.image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) } + try XCTUnwrap(image.pngData()).write(to: directory.appendingPathComponent("\(name).png")) + } +} diff --git a/ios/HapiTests/SessionListFilterTests.swift b/ios/HapiTests/SessionListFilterTests.swift index 07cdf8acc96..398faf69250 100644 --- a/ios/HapiTests/SessionListFilterTests.swift +++ b/ios/HapiTests/SessionListFilterTests.swift @@ -293,6 +293,48 @@ final class SessionListFilterTests: XCTestCase { XCTAssertNotNil(SessionConnectionNotice(state: state, showsCachedSessions: false).message) } } + + func testProjectGroupsAreDefaultMachineAwareDisambiguatedAndCollapsible() { + let s1 = SessionSummary( + id: "s1", active: true, thinking: false, activeAt: 3000, updatedAt: 3000, + metadata: SessionSummaryMetadata(name: "Work HAPI", path: "/Users/dev/work/hapi", machineId: "mac-1", flavor: "codex"), + metadataVersion: 1, agentStateVersion: 1, todosUpdatedAt: 0, pendingRequestsCount: 0 + ) + let s2 = SessionSummary( + id: "s2", active: true, thinking: false, activeAt: 2000, updatedAt: 2000, + metadata: SessionSummaryMetadata(name: "OSS HAPI", path: "/Users/dev/oss/hapi", machineId: "mac-1", flavor: "claude"), + metadataVersion: 1, agentStateVersion: 1, todosUpdatedAt: 0, pendingRequestsCount: 0 + ) + let s3 = SessionSummary( + id: "s3", active: true, thinking: false, activeAt: 1000, updatedAt: 1000, + metadata: SessionSummaryMetadata(name: "Linux HAPI", path: "/Users/dev/work/hapi", machineId: "linux-1", flavor: "codex"), + metadataVersion: 1, agentStateVersion: 1, todosUpdatedAt: 0, pendingRequestsCount: 0 + ) + let sessions = HomeFilterTestSessions([s1, s2, s3]) + let machines = HomeFilterTestMachines([ + HomeFilterTestData.machine("mac-1", host: "mac.local", name: "Mac Studio"), + HomeFilterTestData.machine("linux-1", host: "devbox", name: "DevBox"), + ]) + let model = HomeFilterTestData.model(sessions: sessions, machines: machines) + + let initial = model.listSnapshot + XCTAssertEqual(initial.projectSections.count, 3) + XCTAssertEqual(initial.projectSections.map(\.title), ["work/hapi", "oss/hapi", "hapi"]) + XCTAssertEqual(initial.projectSections.map(\.machineLabel), ["Mac Studio", "Mac Studio", "DevBox"]) + XCTAssertTrue(initial.projectSections.allSatisfy { !$0.isCollapsed }) + XCTAssertEqual(initial.displayedSessionIds, ["s1", "s2", "s3"]) + + let firstSectionId = initial.projectSections[0].id + model.toggleProjectSection(firstSectionId) + let collapsed = model.listSnapshot + XCTAssertTrue(collapsed.projectSections[0].isCollapsed) + XCTAssertEqual(collapsed.displayedSessionIds, ["s2", "s3"]) + + // Selecting a session inside a collapsed section auto-expands it. + model.selectedSessionId = "s1" + XCTAssertFalse(model.listSnapshot.projectSections[0].isCollapsed) + XCTAssertEqual(model.listSnapshot.displayedSessionIds, ["s1", "s2", "s3"]) + } } /// In-memory observable stores: no networking, Keychain or disk snapshots. diff --git a/ios/HapiTests/TerminalViewTests.swift b/ios/HapiTests/TerminalViewTests.swift new file mode 100644 index 00000000000..228685c6a13 --- /dev/null +++ b/ios/HapiTests/TerminalViewTests.swift @@ -0,0 +1,202 @@ +import HapiClient +import HapiProtocol +import HapiUI +import UIKit +import XCTest +@testable import Hapi + +@MainActor +final class TerminalViewTests: XCTestCase { + private actor StubHTTP: HTTPPerforming { + func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + let url = try XCTUnwrap(request.url) + let response = try XCTUnwrap(HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)) + return (Data("{}".utf8), response) + } + } + + func testCoreTextCanvasRendersColorsBoxDrawingAndCJKAcrossThemes() { + let emulator = TerminalEmulator(cols: 60, rows: 16) + emulator.feed( + "\u{1b}[1;38;2;97;175;239m╭────────────────────────╮\r\n" + + "│ \u{1b}[32mHAPI\u{1b}[0m 中文终端 \u{1b}[7mREADY\u{1b}[27m │\r\n" + + "╰────────────────────────╯\u{1b}[0m\r\n" + + "\u{1b}[4;33m█▀▄░▒▓\u{1b}[0m \u{1b}[38;5;208m256-color\u{1b}[0m\r\n" + ) + + for variant in [HapiTheme.Variant.light, .dark, .oled] { + let palette = TerminalPalette.forTheme(variant) + let view = CoreTextTerminalCanvasView(emulator: emulator, palette: palette, fontSize: 13) + view.frame = CGRect(x: 0, y: 0, width: 390, height: 320) + view.layoutIfNeeded() + + let renderer = UIGraphicsImageRenderer(bounds: view.bounds) + let image = renderer.image { ctx in + view.draw(view.bounds) + _ = ctx + } + XCTAssertEqual(Int(image.size.width), 390) + XCTAssertEqual(Int(image.size.height), 320) + XCTAssertNotNil(image.cgImage) + } + } + + func testCoreTextCanvasReportsGridSizeAndForwardsUIKeyInput() { + let emulator = TerminalEmulator(cols: 40, rows: 12) + let view = CoreTextTerminalCanvasView(emulator: emulator, palette: .forTheme(.dark), fontSize: 13) + + var reportedGrids: [(Int, Int)] = [] + view.onGridSizeChange = { cols, rows in + reportedGrids.append((cols, rows)) + } + var sentInputs: [String] = [] + view.onInput = { text in + sentInputs.append(text) + } + + view.frame = CGRect(x: 0, y: 0, width: 390, height: 400) + view.layoutSubviews() + let phoneGrid = reportedGrids.last + XCTAssertNotNil(phoneGrid) + + view.frame = CGRect(x: 0, y: 0, width: 800, height: 700) + view.layoutSubviews() + let padGrid = reportedGrids.last + XCTAssertNotNil(padGrid) + if let p = phoneGrid, let i = padGrid { + XCTAssertGreaterThan(i.0, p.0) + XCTAssertGreaterThan(i.1, p.1) + } + + view.insertText("ls -la") + view.insertText("\n") + view.deleteBackward() + XCTAssertEqual(sentInputs, ["ls -la", "\r", "\u{7f}"]) + } + + func testCoreTextCanvasExposesVoiceOverAccessibilityRows() { + let emulator = TerminalEmulator(cols: 40, rows: 8) + emulator.feed("first line\r\nsecond line\r\nthird line") + + let view = CoreTextTerminalCanvasView(emulator: emulator, palette: .forTheme(.dark), fontSize: 13) + view.frame = CGRect(x: 0, y: 0, width: 360, height: 240) + view.layoutSubviews() + view.syncWithEmulator() + + XCTAssertEqual(view.accessibilityElementCount(), 3) + let first = view.accessibilityElement(at: 0) as? UIAccessibilityElement + let second = view.accessibilityElement(at: 1) as? UIAccessibilityElement + let third = view.accessibilityElement(at: 2) as? UIAccessibilityElement + XCTAssertEqual(first?.accessibilityLabel, "first line") + XCTAssertEqual(second?.accessibilityLabel, "second line") + XCTAssertEqual(third?.accessibilityLabel, "third line") + } + + func testHubSessionRetainsAndRotatesShellTerminalId() throws { + let hub = try XCTUnwrap(HubSession( + hubUrl: "https://hub.example.com", + credentialStore: InMemoryCredentialStore(), + performer: StubHTTP() + )) + defer { hub.shutdown() } + + let id1 = hub.shellTerminalId(for: "sess-a") + let id2 = hub.shellTerminalId(for: "sess-a") + let other = hub.shellTerminalId(for: "sess-b") + XCTAssertEqual(id1, id2) + XCTAssertNotEqual(id1, other) + + let rotated = hub.rotateShellTerminalId(for: "sess-a") + XCTAssertNotEqual(rotated, id1) + XCTAssertEqual(hub.shellTerminalId(for: "sess-a"), rotated) + } + + func testChatModelTerminalCapabilityGatingMatchesHubRules() throws { + let hub = try XCTUnwrap(HubSession( + hubUrl: "https://hub.example.com", + credentialStore: InMemoryCredentialStore(), + performer: StubHTTP() + )) + defer { hub.shutdown() } + + let ptySession = Session( + id: "sess-pty", + namespace: "default", + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: SessionMetadata( + path: "/tmp/repo", + host: "mac", + startingMode: .pty, + capabilities: SessionCapabilities(terminal: true) + ), + metadataVersion: 1, + agentState: nil, + agentStateVersion: 1, + thinking: false, + thinkingAt: 0 + ) + let remoteNoTermSession = Session( + id: "sess-no-term", + namespace: "default", + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: SessionMetadata( + path: "/tmp/repo", + host: "mac", + startingMode: .remote, + capabilities: SessionCapabilities(terminal: false) + ), + metadataVersion: 1, + agentState: nil, + agentStateVersion: 1, + thinking: false, + thinkingAt: 0 + ) + let inactiveSession = Session( + id: "sess-inactive", + namespace: "default", + seq: 1, + createdAt: 1, + updatedAt: 1, + active: false, + activeAt: 1, + metadata: SessionMetadata( + path: "/tmp/repo", + host: "mac", + startingMode: .pty, + capabilities: SessionCapabilities(terminal: true) + ), + metadataVersion: 1, + agentState: nil, + agentStateVersion: 1, + thinking: false, + thinkingAt: 0 + ) + + hub.sessionStore.applySessionEvent(.sessionAdded(namespace: "default", sessionId: ptySession.id, data: .session(ptySession))) + hub.sessionStore.applySessionEvent(.sessionAdded(namespace: "default", sessionId: remoteNoTermSession.id, data: .session(remoteNoTermSession))) + hub.sessionStore.applySessionEvent(.sessionAdded(namespace: "default", sessionId: inactiveSession.id, data: .session(inactiveSession))) + + let ptyModel = ChatModel(session: hub, sessionId: "sess-pty") + XCTAssertTrue(ptyModel.canOpenShellTerminal) + XCTAssertTrue(ptyModel.canViewAgentTerminal) + XCTAssertTrue(ptyModel.canOpenTerminal) + + let noTermModel = ChatModel(session: hub, sessionId: "sess-no-term") + XCTAssertFalse(noTermModel.canOpenShellTerminal) + XCTAssertFalse(noTermModel.canViewAgentTerminal) + XCTAssertFalse(noTermModel.canOpenTerminal) + + let inactiveModel = ChatModel(session: hub, sessionId: "sess-inactive") + XCTAssertFalse(inactiveModel.canOpenShellTerminal) + XCTAssertFalse(inactiveModel.canViewAgentTerminal) + XCTAssertFalse(inactiveModel.canOpenTerminal) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift index 386dc1fa114..7ebe07b3fde 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift @@ -100,7 +100,7 @@ public struct HubPairingService: Sendable { } let client = makeUnauthenticatedClient(baseURL: baseURL) - try await checkHealth(client) + let health = try await checkHealth(client) // Token exchange. let auth: AuthResponse @@ -120,7 +120,8 @@ public struct HubPairingService: Sendable { credential: .accessToken(token), jwt: auth.token, jwtObtainedAt: Int(now().timeIntervalSince1970 * 1000) - ) + ), + hubId: health.hubId ) } @@ -143,6 +144,7 @@ public struct HubPairingService: Sendable { authenticator: any PasskeyAuthenticating ) async throws -> PairedHub { var expectedHub: String? + var checkedHealth: HubHealthResponse? if let rawHubUrl { guard let normalized = HubURLNormalization.normalize(rawHubUrl), let baseURL = URL(string: normalized), @@ -150,7 +152,7 @@ public struct HubPairingService: Sendable { (try? PasskeyHubBinding.origin(baseURL)) != nil else { throw PairingFailure.invalidHubURL } - try await checkHealth(makeUnauthenticatedClient(baseURL: baseURL)) + checkedHealth = try await checkHealth(makeUnauthenticatedClient(baseURL: baseURL)) expectedHub = normalized } @@ -182,7 +184,7 @@ public struct HubPairingService: Sendable { guard let baseURL = URL(string: hub) else { throw PairingFailure.invalidHubURL } let client = makeUnauthenticatedClient(baseURL: baseURL) if expectedHub == nil { - try await checkHealth(client) + checkedHealth = try await checkHealth(client) } let login: PasskeyLoginResponse @@ -203,7 +205,8 @@ public struct HubPairingService: Sendable { credential: .passkeySession(login.passkeySession), jwt: login.token, jwtObtainedAt: Int(now().timeIntervalSince1970 * 1000) - ) + ), + hubId: checkedHealth?.hubId ) } @@ -220,7 +223,8 @@ public struct HubPairingService: Sendable { } /// Reachability + protocol compatibility. - private func checkHealth(_ client: APIClient) async throws { + @discardableResult + private func checkHealth(_ client: APIClient) async throws -> HubHealthResponse { let health: HubHealthResponse do { health = try await client.health() @@ -240,18 +244,22 @@ public struct HubPairingService: Sendable { supportedVersion: ProtocolVersion.supported ) } + return health } /// Persists the record — credentials first: a hub registered without /// credentials would restore as paired-but-dead — then registers the hub /// and makes it active. - private func persist(_ credentials: HubCredentials) throws -> PairedHub { + private func persist(_ credentials: HubCredentials, hubId: String? = nil) throws -> PairedHub { do { try credentialStore.store(credentials) } catch { throw PairingFailure.storageFailure } registry.register(credentials.hubUrl) + if let hubId { + registry.setHubId(hubId, for: credentials.hubUrl) + } registry.setActiveHub(credentials.hubUrl) return PairedHub(hubUrl: credentials.hubUrl, claims: credentials.jwt.flatMap(JWT.claims(from:))) } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubRegistry.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubRegistry.swift index c77a254256d..053c5b47752 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubRegistry.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubRegistry.swift @@ -45,6 +45,7 @@ public enum HubURLNormalization { public final class HubRegistry: @unchecked Sendable { public static let hubsDefaultsKey = "run.hapi.hubs" public static let activeHubDefaultsKey = "run.hapi.activeHub" + public static let hubIdsDefaultsKey = "run.hapi.hubIds" private let defaults: UserDefaults /// Serializes read-modify-write cycles on the stored array. @@ -114,6 +115,10 @@ public final class HubRegistry: @unchecked Sendable { guard let index = hubs.firstIndex(of: normalized) else { return } hubs.remove(at: index) defaults.set(hubs, forKey: Self.hubsDefaultsKey) + var map = storedHubIds() + if map.removeValue(forKey: normalized) != nil { + defaults.set(map, forKey: Self.hubIdsDefaultsKey) + } if defaults.string(forKey: Self.activeHubDefaultsKey) == normalized { if let next = hubs.first { defaults.set(next, forKey: Self.activeHubDefaultsKey) @@ -123,7 +128,59 @@ public final class HubRegistry: @unchecked Sendable { } } + /// Associates a hub's stable `hubId` with a paired hub URL for O(1) push + /// routing. Ignored when `raw` is not currently registered or `hubId` is blank. + public func setHubId(_ hubId: String, for raw: String) { + let trimmed = hubId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, + let normalized = HubURLNormalization.normalize(raw) else { return } + lock.lock() + defer { lock.unlock() } + guard storedHubs().contains(normalized) else { return } + var map = storedHubIds() + if map[normalized] != trimmed { + map[normalized] = trimmed + defaults.set(map, forKey: Self.hubIdsDefaultsKey) + } + } + + /// The stored `hubId` for a paired hub URL, if known. + public func hubId(for raw: String) -> String? { + guard let normalized = HubURLNormalization.normalize(raw) else { return nil } + lock.lock() + defer { lock.unlock() } + return storedHubIds()[normalized] + } + + /// Paired hub URLs matching `hubId`, ordered with the active hub first + /// (covers rare dual-URL pairings of the same hub) and registration order + /// otherwise. Returns empty when no paired hub carries `hubId`. + public func hubUrls(forHubId hubId: String) -> [String] { + let trimmed = hubId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return [] } + lock.lock() + defer { lock.unlock() } + let hubs = storedHubs() + let map = storedHubIds() + let active = defaults.string(forKey: Self.activeHubDefaultsKey) + var matches = hubs.filter { map[$0] == trimmed } + if let active, let idx = matches.firstIndex(of: active), idx > 0 { + matches.remove(at: idx) + matches.insert(active, at: 0) + } + return matches + } + + /// Best matching paired hub URL for `hubId` (active hub preferred if multiple). + public func hubUrl(forHubId hubId: String) -> String? { + hubUrls(forHubId: hubId).first + } + private func storedHubs() -> [String] { defaults.stringArray(forKey: Self.hubsDefaultsKey) ?? [] } + + private func storedHubIds() -> [String: String] { + defaults.dictionary(forKey: Self.hubIdsDefaultsKey) as? [String: String] ?? [:] + } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift index 5c8e17628ca..6b3408f97c6 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatInteractor.swift @@ -450,6 +450,30 @@ public final class ChatInteractor { setComposerText(appendTranscript(composerText, transcript: transcript)) } + /// Send an explicit prompt (e.g., formatted diff review comments) through + /// the optimistic send pipeline without disturbing any unsent composer draft. + public func sendPromptText(_ rawText: String, as mode: MessageDeliveryMode? = nil) { + guard !isSending, !scratchlistBusy else { return } + let text = rawText.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty else { return } + let deliveryMode = mode ?? (followUpDefault == nil ? .queue : .default) + isSending = true + let localId = makeLocalId() + let createdAt = now() + Task { [weak self] in + guard let self else { return } + await self.performSend( + text: text, + localId: localId, + createdAt: createdAt, + deliveryMode: deliveryMode, + attachments: nil, + scheduledAt: nil, + isRetry: false + ) + } + } + /// Screen-level notices (attachment prep failures, mic permission) ride /// the same event channel as interaction failures. public func postNotice(_ message: String) { @@ -574,7 +598,8 @@ public final class ChatInteractor { } catch let error as APIError where error.status == 409 && error.code == "session_inactive" { return await resumeAndRetry(store: store, request: request, localId: localId, fromSessionId: target) } catch { - await store.updateStatus(localId: localId, status: .failed) + // SSE can already have echoed/consumed the message before the HTTP request fails/times out. + await store.updateStatus(localId: localId, status: .failed, onlyFrom: .sending) return nil } } @@ -617,7 +642,7 @@ public final class ChatInteractor { permissionMode: sessionStore.detail(for: fromSessionId)?.permissionMode ) } catch { - await store.updateStatus(localId: localId, status: .failed) + await store.updateStatus(localId: localId, status: .failed, onlyFrom: .sending) emit(.notice("Session is inactive and could not be resumed")) return nil } @@ -647,7 +672,7 @@ public final class ChatInteractor { await targetStore.updateStatus(localId: localId, status: successStatus(), onlyFrom: .sending) accepted = true } catch { - await targetStore.updateStatus(localId: localId, status: .failed) + await targetStore.updateStatus(localId: localId, status: .failed, onlyFrom: .sending) } if targetSessionId != sessionId { emit(.sessionSuperseded(sessionId: targetSessionId)) @@ -842,6 +867,30 @@ public final class ChatInteractor { ) } + /// Recent non-empty user prompts in this window (newest first) for hardware + /// keyboard `↑`/`↓` recall. Prefers `translatedFrom` when a prompt was + /// auto-translated so the user recalls what they actually typed. + public var sentUserPrompts: [String] { + guard let messages = windowState?.messages, !messages.isEmpty else { return [] } + var prompts: [String] = [] + prompts.reserveCapacity(min(messages.count, 50)) + for row in messages.reversed() { + if row.isQueuedForInvocation { continue } + guard let normalized = normalizeDecryptedMessage(row.asDecryptedMessage), + case .user(let text, _) = normalized.content else { continue } + let original = normalized.meta?.objectValue?["translatedFrom"]?.stringValue? + .trimmingCharacters(in: .whitespacesAndNewlines) + let candidate = (original?.isEmpty == false ? original : nil) + ?? text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !candidate.isEmpty else { continue } + if prompts.last != candidate { + prompts.append(candidate) + if prompts.count >= 50 { break } + } + } + return prompts + } + // MARK: - Permissions /// Per-request optimistic permission state. A settled request (gone from diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift index d9fedc9e66b..52fab542db9 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ChatPipeline.swift @@ -30,6 +30,16 @@ import HapiProtocol /// app-side `ChatModel` is the single caller and awaits each run to /// completion, so runs never interleave in practice; the actor makes that a /// guarantee rather than a convention. +public struct ChatPipelineOutput: Equatable, Sendable { + public let blocks: [VisibleChatBlock] + public let latestUsage: LatestUsage? + + public init(blocks: [VisibleChatBlock], latestUsage: LatestUsage?) { + self.blocks = blocks + self.latestUsage = latestUsage + } +} + public actor ChatPipeline { private struct NormalizeCacheEntry { /// The exact row instance the cached result was computed from. @@ -51,6 +61,24 @@ public actor ChatPipeline { hasMoreMessages: Bool, directSendLocalIds: Set = [] ) -> [VisibleChatBlock] { + runWithUsage( + messages: messages, + agentState: agentState, + hasMoreMessages: hasMoreMessages, + directSendLocalIds: directSendLocalIds + ).blocks + } + + /// Runs the full chat projection and surfaces the reducer's latest token + /// usage (driving the context-window meter in the chat composer). + public func runWithUsage( + messages: [WindowMessage], + agentState: AgentState?, + hasMoreMessages: Bool, + directSendLocalIds: Set = [] + ) -> ChatPipelineOutput { + let signpost = HapiSignpost.begin("ChatPipelineRun") + defer { HapiSignpost.end(signpost) } // Composer-owned rows out, except sends the idle agent is about to // consume (`ChatInteractor.directSendLocalIds`); duplicate ids keep // the first occurrence (merge output cannot contain duplicates — @@ -102,7 +130,7 @@ public actor ChatPipeline { if case .toolGroup(let group) = block { return group } return nil } - return visible + return ChatPipelineOutput(blocks: visible, latestUsage: reduced.latestUsage) } private static func filterEmptyReasoning(_ blocks: [ChatBlock]) -> [ChatBlock] { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ComposerPromptRecall.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ComposerPromptRecall.swift new file mode 100644 index 00000000000..80a9d673c52 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ComposerPromptRecall.swift @@ -0,0 +1,65 @@ +import Foundation + +/// Shell-style prompt history recall for hardware keyboards (`↑` / `↓` when +/// the composer is empty). Pure value type so it can be tested deterministically. +public struct ComposerPromptRecall: Equatable, Sendable { + /// Current 0-based index into deduplicated newest-first prompt history, or + /// `nil` when editing a live draft. + public private(set) var index: Int? + private var stashedDraft = "" + + public init() {} + + public var isActive: Bool { index != nil } + + /// Handles hardware `↑`. Enters recall only when the live draft is empty so + /// multiline drafts keep normal caret navigation. + public mutating func stepUp(currentText: String, history: [String]) -> String? { + let entries = Self.deduplicated(history) + guard !entries.isEmpty else { return nil } + if let current = index { + let next = min(current + 1, entries.count - 1) + index = next + return entries[next] + } + guard currentText.isEmpty else { return nil } + stashedDraft = currentText + index = 0 + return entries[0] + } + + /// Handles hardware `↓`. Only consumes the key while recall is active; + /// stepping past index 0 exits recall and restores the stashed draft. + public mutating func stepDown(history: [String]) -> String? { + guard let current = index else { return nil } + let entries = Self.deduplicated(history) + if current > 0, current - 1 < entries.count { + let next = current - 1 + index = next + return entries[next] + } + index = nil + let restored = stashedDraft + stashedDraft = "" + return restored + } + + /// Exits recall (called on manual typing or after submitting a message). + public mutating func reset() { + index = nil + stashedDraft = "" + } + + private static func deduplicated(_ history: [String]) -> [String] { + var result: [String] = [] + result.reserveCapacity(history.count) + for raw in history { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { continue } + if result.last != trimmed { + result.append(trimmed) + } + } + return result + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Chat/ContextWindowMetrics.swift b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ContextWindowMetrics.swift new file mode 100644 index 00000000000..f3678c9a250 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Chat/ContextWindowMetrics.swift @@ -0,0 +1,208 @@ +import Foundation +import HapiProtocol + +/// Pure context-window usage presentation model (mirrors `web/src/chat/modelConfig.ts` +/// and `web/src/components/AssistantChat/StatusBar.tsx`) plus elapsed-duration +/// formatting for active turns. +public struct ContextWindowMetrics: Equatable, Sendable { + public enum Severity: Equatable, Sendable { + case normal + case warning + case danger + } + + public static let warningThresholdPercent = 70 + public static let dangerThresholdPercent = 90 + private static let headroomTokens = 10_000 + private static let defaultClaudeWindow = 200_000 + private static let largeClaudeWindow = 1_000_000 + private static let defaultCodexWindow = 258_400 + private static let defaultPiWindow = 200_000 + + public let contextSize: Int + public let maxContextSize: Int? + public let inputTokens: Int + public let outputTokens: Int + public let cacheRead: Int + public let cacheCreation: Int + public let model: String? + + public init( + contextSize: Int, + maxContextSize: Int?, + inputTokens: Int, + outputTokens: Int, + cacheRead: Int, + cacheCreation: Int, + model: String? + ) { + self.contextSize = contextSize + self.maxContextSize = maxContextSize + self.inputTokens = inputTokens + self.outputTokens = outputTokens + self.cacheRead = cacheRead + self.cacheCreation = cacheCreation + self.model = model + } + + public var fractionUsed: Double? { + guard let maxContextSize, maxContextSize > 0 else { return nil } + return min(1, max(0, Double(contextSize) / Double(maxContextSize))) + } + + public var usedPercent: Int? { + guard let fractionUsed else { return nil } + return min(100, max(0, Int((fractionUsed * 100).rounded()))) + } + + public var remainingPercent: Int? { + usedPercent.map { 100 - $0 } + } + + public var severity: Severity { + guard let maxContextSize, maxContextSize > 0 else { return .normal } + let pct = (Double(contextSize) / Double(maxContextSize)) * 100 + if pct >= Double(Self.dangerThresholdPercent) { return .danger } + if pct >= Double(Self.warningThresholdPercent) { return .warning } + return .normal + } + + /// Resolves display metrics from the reducer's latest usage record. + /// Returns `nil` when no usage has been observed or `contextSize <= 0`. + public static func resolve( + usage: LatestUsage?, + sessionModel: String?, + flavor: String? + ) -> ContextWindowMetrics? { + guard let usage else { return nil } + let contextSize = Int(usage.contextSize.rounded()) + guard contextSize > 0 else { return nil } + + let resolvedModel = usage.model?.isEmpty == false ? usage.model : sessionModel + let explicitMax: Int? = if let cw = usage.contextWindow, cw.isFinite, cw > 0 { + Int(cw.rounded()) + } else { + nil + } + let maxContext = explicitMax ?? fallbackBudgetTokens(model: resolvedModel, flavor: flavor) + + return ContextWindowMetrics( + contextSize: contextSize, + maxContextSize: maxContext, + inputTokens: max(0, Int(usage.inputTokens.rounded())), + outputTokens: max(0, Int(usage.outputTokens.rounded())), + cacheRead: max(0, Int(usage.cacheRead.rounded())), + cacheCreation: max(0, Int(usage.cacheCreation.rounded())), + model: resolvedModel + ) + } + + /// Fallback conservative context budget when the server did not report an + /// explicit `contextWindow` (port of `getContextBudgetTokens` in + /// `web/src/chat/modelConfig.ts`). + public static func fallbackBudgetTokens(model: String?, flavor: String?) -> Int? { + if flavor == "codex" { + return max(1, defaultCodexWindow - headroomTokens) + } + if flavor == "pi" { + return max(1, defaultPiWindow - headroomTokens) + } + if flavor == "cursor" { + guard let trimmed = model?.trimmingCharacters(in: .whitespacesAndNewlines), + let window = parseCursorWireContextWindow(trimmed) else { return nil } + return max(1, window - headroomTokens) + } + guard flavor == "claude" else { return nil } + + let trimmed = model?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let windowTokens: Int? + if trimmed.isEmpty { + windowTokens = defaultClaudeWindow + } else if isClaudePreset(trimmed) || trimmed.hasPrefix("claude-") || trimmed.hasSuffix("[1m]") { + let isLarge = isClaudePreset(trimmed) + || trimmed.hasSuffix("[1m]") + || trimmed.hasPrefix("claude-fable") + windowTokens = isLarge ? largeClaudeWindow : defaultClaudeWindow + } else { + windowTokens = nil + } + guard let windowTokens else { return nil } + return max(1, windowTokens - headroomTokens) + } + + private static func isClaudePreset(_ model: String) -> Bool { + switch model { + case "default", "opus", "fable", "sonnet", "haiku": + return true + default: + return false + } + } + + private static func parseCursorWireContextWindow(_ model: String) -> Int? { + guard let open = model.firstIndex(of: "["), + let close = model[open...].firstIndex(of: "]"), + open < close else { return nil } + let inside = model[model.index(after: open).. 0 else { return nil } + return raw.hasSuffix("k") ? value * 1_000 : value + } + return nil + } + + /// Compact token count matching Web (`1.2M`, `45k`, `850`). + public static func formatTokens(_ value: Int) -> String { + if value >= 1_000_000 { + return String(format: "%.1fM", Double(value) / 1_000_000.0) + } + if value >= 1_000 { + return "\(Int((Double(value) / 1_000.0).rounded()))k" + } + return "\(value)" + } + + /// Formats elapsed wall-clock time for an active turn (`0:05`, `1:23`, `1:02:10`). + public static func formatElapsed(sinceMs startedAtMs: Int, nowMs: Int) -> String { + let totalSeconds = max(0, (nowMs - startedAtMs) / 1_000) + let hours = totalSeconds / 3_600 + let minutes = (totalSeconds % 3_600) / 60 + let seconds = totalSeconds % 60 + if hours > 0 { + return String(format: "%d:%02d:%02d", hours, minutes, seconds) + } + return String(format: "%d:%02d", minutes, seconds) + } +} + +/// Aggregated uncommitted git diff stats for the current session (staged + unstaged). +public struct SessionGitDiffStats: Equatable, Sendable { + public let insertions: Int + public let deletions: Int + public let changedFiles: Int + + public init(insertions: Int, deletions: Int, changedFiles: Int) { + self.insertions = insertions + self.deletions = deletions + self.changedFiles = changedFiles + } + + public var hasChanges: Bool { + changedFiles > 0 || insertions > 0 || deletions > 0 + } + + public static func combine(unstaged: DiffSummary, staged: DiffSummary) -> SessionGitDiffStats { + let uniqueFiles = Set(unstaged.files.map(\.file) + staged.files.map(\.file)) + return SessionGitDiffStats( + insertions: unstaged.insertions + staged.insertions, + deletions: unstaged.deletions + staged.deletions, + changedFiles: uniqueFiles.count + ) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Diagnostics/DiagnosticLog.swift b/ios/Packages/HapiKit/Sources/HapiClient/Diagnostics/DiagnosticLog.swift new file mode 100644 index 00000000000..331e2cc3bef --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Diagnostics/DiagnosticLog.swift @@ -0,0 +1,269 @@ +#if canImport(CryptoKit) +import CryptoKit +#endif +import Foundation +#if canImport(OSLog) +import OSLog +#endif + +// MARK: - Secret & origin redaction + +/// Redacts credentials, tokens, pairing URLs, and private hostnames before any +/// diagnostic text leaves the app. Pure Foundation so it builds and tests on +/// Linux as well as Darwin. +public enum DiagnosticRedactor { + private static let patterns: [(regex: NSRegularExpression, replacement: String)] = [ + // Pairing deep links carry the access token in their query or fragment. + (try! NSRegularExpression(pattern: #"hapicompanion://[^\s"'<>]+"#, options: .caseInsensitive), + "hapicompanion://[REDACTED]"), + // Standard JWTs (header.payload.signature). + (try! NSRegularExpression(pattern: #"\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b"#), + "[REDACTED_JWT]"), + // Bearer / authorization headers. + (try! NSRegularExpression(pattern: #"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+"#), + "Bearer [REDACTED]"), + // Query or fragment parameters carrying credentials. + (try! NSRegularExpression(pattern: #"(?i)\b(token|code|passkeySession|secret|password|pushKey|apiKey|authorization)=[^&\s#"'<>]+"#), + "$1=[REDACTED]"), + ] + + /// Scrubs secrets from arbitrary error or log text. + public static func redact(_ text: String) -> String { + var result = text + for entry in patterns { + let range = NSRange(result.startIndex.. String { + guard let components = URLComponents(string: raw), + let scheme = components.scheme?.lowercased(), + let host = components.host, !host.isEmpty else { + return "[redacted-hub]" + } + let tag = shortHash(host.lowercased()) + if let port = components.port { + return "\(scheme)://hub-\(tag):\(port)" + } + return "\(scheme)://hub-\(tag)" + } + + private static func shortHash(_ input: String) -> String { + #if canImport(CryptoKit) + let digest = SHA256.hash(data: Data(input.utf8)) + return String(digest.prefix(3).map { String(format: "%02x", $0) }.joined()) + #else + var hash: UInt64 = 0xcbf2_9ce4_8422_2325 + for byte in input.utf8 { + hash ^= UInt64(byte) + hash = hash &* 0x0000_0100_0000_01B3 + } + return String(format: "%06llx", hash & 0xFF_FFFF) + #endif + } +} + +// MARK: - Bounded in-memory diagnostic ring buffer + +/// Thread-safe, fixed-capacity ring buffer of scrubbed operational events +/// (SSE transitions, reconnects, push errors, MetricKit hang notices). +/// Never stores message bodies, code, or credentials. +public final class DiagnosticEventLog: @unchecked Sendable { + public struct Entry: Equatable, Sendable { + public let timestamp: Date + public let category: String + public let message: String + + public init(timestamp: Date, category: String, message: String) { + self.timestamp = timestamp + self.category = category + self.message = message + } + } + + public static let shared = DiagnosticEventLog() + public static let defaultCapacity = 50 + private static let maxMessageLength = 200 + + private let lock = NSLock() + private let capacity: Int + private var entries: [Entry] = [] + + public init(capacity: Int = DiagnosticEventLog.defaultCapacity) { + self.capacity = max(1, capacity) + } + + public func record(category: String, _ message: String, at timestamp: Date = Date()) { + let scrubbed = DiagnosticRedactor.redact(message) + let bounded = scrubbed.count > Self.maxMessageLength + ? String(scrubbed.prefix(Self.maxMessageLength)) + "…" + : scrubbed + let entry = Entry(timestamp: timestamp, category: category, message: bounded) + lock.withLock { + entries.append(entry) + if entries.count > capacity { + entries.removeFirst(entries.count - capacity) + } + } + } + + public func snapshot() -> [Entry] { + lock.withLock { entries } + } + + public func clear() { + lock.withLock { entries.removeAll() } + } +} + +// MARK: - Redacted diagnostic report + +public struct DiagnosticSnapshot: Equatable, Sendable { + public var generatedAt: Date + public var appVersion: String + public var osVersion: String + public var platform: String + public var protocolVersion: Int + public var pairedHubCount: Int + public var activeHubRedacted: String? + public var hubHealthStatus: String + public var globalSSEState: String + public var lastResumeVerdict: String? + public var sessionCount: Int + public var onlineMachineCount: Int + public var activeChatOpen: Bool + public var activeChatReconnecting: Bool + public var pushAuthorization: String + public var pushRegisteredHubCount: Int + public var pushLastProblem: String? + public var hangCount: Int + public var crashCount: Int + public var scrollHitchRatio: String? + public var recentEvents: [DiagnosticEventLog.Entry] + + public init( + generatedAt: Date = Date(), + appVersion: String, + osVersion: String, + platform: String, + protocolVersion: Int, + pairedHubCount: Int, + activeHubRedacted: String?, + hubHealthStatus: String, + globalSSEState: String, + lastResumeVerdict: String?, + sessionCount: Int, + onlineMachineCount: Int, + activeChatOpen: Bool, + activeChatReconnecting: Bool, + pushAuthorization: String, + pushRegisteredHubCount: Int, + pushLastProblem: String?, + hangCount: Int = 0, + crashCount: Int = 0, + scrollHitchRatio: String? = nil, + recentEvents: [DiagnosticEventLog.Entry] = [] + ) { + self.generatedAt = generatedAt + self.appVersion = appVersion + self.osVersion = osVersion + self.platform = platform + self.protocolVersion = protocolVersion + self.pairedHubCount = pairedHubCount + self.activeHubRedacted = activeHubRedacted + self.hubHealthStatus = hubHealthStatus + self.globalSSEState = globalSSEState + self.lastResumeVerdict = lastResumeVerdict + self.sessionCount = sessionCount + self.onlineMachineCount = onlineMachineCount + self.activeChatOpen = activeChatOpen + self.activeChatReconnecting = activeChatReconnecting + self.pushAuthorization = pushAuthorization + self.pushRegisteredHubCount = pushRegisteredHubCount + self.pushLastProblem = pushLastProblem + self.hangCount = hangCount + self.crashCount = crashCount + self.scrollHitchRatio = scrollHitchRatio + self.recentEvents = recentEvents + } + + public func formattedReport() -> String { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime] + + var lines: [String] = [ + "HAPI Diagnostics (Redacted)", + "Generated: \(formatter.string(from: generatedAt))", + "App: \(appVersion) · \(platform) \(osVersion) · protocol v\(protocolVersion)", + "", + "Connection", + "- Paired hubs: \(pairedHubCount)", + "- Active hub: \(activeHubRedacted ?? "none")", + "- Hub health: \(DiagnosticRedactor.redact(hubHealthStatus))", + "- Global SSE: \(globalSSEState) (last resume: \(lastResumeVerdict ?? "none"))", + "- Sessions: \(sessionCount) · Online machines: \(onlineMachineCount)", + "- Open chat: \(activeChatOpen ? (activeChatReconnecting ? "open (reconnecting)" : "open") : "none")", + "", + "Push", + "- Authorization: \(pushAuthorization)", + "- Registered hubs: \(pushRegisteredHubCount) / \(pairedHubCount)", + ] + if let problem = pushLastProblem, !problem.isEmpty { + lines.append("- Last problem: \(DiagnosticRedactor.redact(problem))") + } + lines.append("") + lines.append("MetricKit") + lines.append("- Hangs recorded: \(hangCount) · Crashes recorded: \(crashCount)") + if let hitch = scrollHitchRatio { + lines.append("- Scroll hitch ratio: \(hitch)") + } + if !recentEvents.isEmpty { + lines.append("") + lines.append("Recent events (\(recentEvents.count))") + for entry in recentEvents { + lines.append("[\(formatter.string(from: entry.timestamp))] [\(entry.category)] \(DiagnosticRedactor.redact(entry.message))") + } + } + return lines.joined(separator: "\n") + } +} + +// MARK: - Lightweight OSSignposter wrapper (no-op on Linux) + +public enum HapiSignpost { + #if canImport(OSLog) + private static let signposter = OSSignposter(subsystem: "run.hapi.companion", category: "perf") + + public struct IntervalToken: @unchecked Sendable { + fileprivate let name: StaticString + fileprivate let state: OSSignpostIntervalState + } + + public static func begin(_ name: StaticString) -> IntervalToken { + let id = signposter.makeSignpostID() + let state = signposter.beginInterval(name, id: id) + return IntervalToken(name: name, state: state) + } + + public static func end(_ token: IntervalToken) { + signposter.endInterval(token.name, token.state) + } + #else + public struct IntervalToken: Sendable {} + + public static func begin(_ name: StaticString) -> IntervalToken { + IntervalToken() + } + + public static func end(_ token: IntervalToken) {} + #endif +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/DeviceEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/DeviceEndpoints.swift index 01cf1958dd6..648daf7b595 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/DeviceEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/DeviceEndpoints.swift @@ -11,29 +11,34 @@ extension APIClient { /// `POST /api/devices/register` (upsert). /// /// iOS extends the FCM body with `platform: "ios"` (the hub routes those - /// tokens through APNs instead of FCM) and the per-install end-to-end + /// tokens through APNs instead of FCM), the per-install end-to-end /// `pushKey` (base64 of 32 random bytes, see ``PushDeviceKey``) the hub - /// uses to encrypt every ``PushEnvelope``. + /// uses to encrypt every ``PushEnvelope``, and optional per-device + /// `preferences` controlling which event categories trigger push delivery. + @discardableResult public func registerDevice( token: String, deviceId: String, pushKey: String, - platform: String = "ios" - ) async throws { + platform: String = "ios", + preferences: PushNotificationPreferences? = nil + ) async throws -> DeviceRegisterResponse { struct DeviceRegisterRequest: Encodable { let token: String let platform: String let deviceId: String let pushKey: String + let preferences: PushNotificationPreferences? } - try await requestVoid( + return try await request( .post, "/api/devices/register", body: DeviceRegisterRequest( token: token, platform: platform, deviceId: deviceId, - pushKey: pushKey + pushKey: pushKey, + preferences: preferences ) ) } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/LocalSessionImportEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/LocalSessionImportEndpoints.swift new file mode 100644 index 00000000000..30364bee2c6 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/LocalSessionImportEndpoints.swift @@ -0,0 +1,41 @@ +import Foundation +import HapiProtocol + +/// Local CLI session discovery & import endpoints (`claude`, `codex`, `cursor`, +/// `opencode`, `pi`). +extension APIClient { + /// `GET /api//sessions?machineId=...&cwd=...` + public func listLocalSessions( + source: LocalSessionSource, + machineId: String? = nil, + cwd: String? = nil + ) async throws -> LocalSessionsListResponse { + var query: [URLQueryItem] = [] + if let machineId, !machineId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + query.append(URLQueryItem(name: "machineId", value: machineId)) + } + if let cwd, !cwd.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + query.append(URLQueryItem(name: "cwd", value: cwd)) + } + return try await request(.get, source.listPath, query: query) + } + + /// `POST /api//import-sessions` (or `/api/codex/sync-session` for Codex). + public func importLocalSessions( + source: LocalSessionSource, + sessionIds: [String], + machineId: String? = nil, + cwd: String? = nil + ) async throws -> LocalSessionImportResponse { + struct ImportBody: Encodable { + let sessionIds: [String] + let machineId: String? + let cwd: String? + } + return try await request( + .post, + source.importPath, + body: ImportBody(sessionIds: sessionIds, machineId: machineId, cwd: cwd) + ) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift index 1e86cfb7abe..c569da4ecb3 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/SessionEndpoints.swift @@ -187,4 +187,48 @@ extension APIClient { public func sessionCodexModels(sessionId: String) async throws -> CodexModelsResponse { try await request(.get, "/api/sessions/\(encodePathComponent(sessionId))/codex-models") } + + // MARK: - Content search & external refs + + /// `GET /api/sessions/content-search?query=...&limit=...` — full-text + /// message search across all sessions in the current namespace. + public func searchSessionsContent( + query: String, + limit: Int = 30 + ) async throws -> SessionsContentSearchResponse { + try await request( + .get, + "/api/sessions/content-search", + query: [ + URLQueryItem(name: "query", value: query), + URLQueryItem(name: "limit", value: String(limit)), + ] + ) + } + + /// `GET /api/sessions/:id/content-search?query=...&limit=...` — full-text + /// message search within a single session. + public func searchSessionContent( + sessionId: String, + query: String, + limit: Int = 100 + ) async throws -> SessionContentMatchesResponse { + try await request( + .get, + "/api/sessions/\(encodePathComponent(sessionId))/content-search", + query: [ + URLQueryItem(name: "query", value: query), + URLQueryItem(name: "limit", value: String(limit)), + ] + ) + } + + /// `GET /api/sessions/:id/external-refs` — linked GitHub PRs and their cached status. + public func sessionExternalRefs(sessionId: String) async throws -> [ExternalRef] { + let response: SessionExternalRefsResponse = try await request( + .get, + "/api/sessions/\(encodePathComponent(sessionId))/external-refs" + ) + return response.externalRefs + } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Files/DiffReviewStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Files/DiffReviewStore.swift new file mode 100644 index 00000000000..b27b08e2aed --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Files/DiffReviewStore.swift @@ -0,0 +1,201 @@ +import Foundation +import Observation + +/// Line side/kind of a diff review comment. +public enum DiffReviewLineKind: String, Codable, Equatable, Sendable { + case addition + case deletion + case context +} + +/// A single inline review comment attached to a diff line in a session. +public struct DiffReviewComment: Identifiable, Codable, Equatable, Sendable { + public let id: String + public let path: String + public let staged: Bool + /// 1-based line number (`newNumber` for additions/context, `oldNumber` for deletions). + public let lineNumber: Int + public let lineKind: DiffReviewLineKind + public let hunkHeader: String? + /// The selected diff line plus surrounding context lines with `+/-` prefixes. + public let snippet: String + public var comment: String + public let createdAt: Date + + public init( + id: String = UUID().uuidString, + path: String, + staged: Bool, + lineNumber: Int, + lineKind: DiffReviewLineKind, + hunkHeader: String? = nil, + snippet: String, + comment: String, + createdAt: Date = Date() + ) { + self.id = id + self.path = path + self.staged = staged + self.lineNumber = lineNumber + self.lineKind = lineKind + self.hunkHeader = hunkHeader + self.snippet = snippet + self.comment = comment + self.createdAt = createdAt + } + + /// Stable lookup key matching `DiffTextView.lineKey(lineNumber:kind:)`. + public var lineKey: String { + "\(lineNumber):\(lineKind.rawValue)" + } +} + +/// Session-scoped draft store for inline diff review comments, persisted in +/// `UserDefaults` so drafts survive navigating between files or app restarts +/// until the user sends or clears them. +@MainActor @Observable +public final class DiffReviewStore { + private let defaults: UserDefaults + private let storageKey: String + private var bySession: [String: [DiffReviewComment]] = [:] + + public init(scope: String, defaults: UserDefaults = .standard) { + self.defaults = defaults + self.storageKey = "hapi.diffReview.v1.\(scope)" + self.bySession = Self.load(from: defaults, key: storageKey) + } + + public func comments(forSession sessionId: String) -> [DiffReviewComment] { + bySession[sessionId] ?? [] + } + + public func comments(forSession sessionId: String, path: String, staged: Bool) -> [DiffReviewComment] { + comments(forSession: sessionId).filter { $0.path == path && $0.staged == staged } + } + + public func comment( + forSession sessionId: String, + path: String, + staged: Bool, + lineNumber: Int, + lineKind: DiffReviewLineKind + ) -> DiffReviewComment? { + comments(forSession: sessionId).first { + $0.path == path && $0.staged == staged && $0.lineNumber == lineNumber && $0.lineKind == lineKind + } + } + + public func commentedLineKeys(forSession sessionId: String, path: String, staged: Bool) -> Set { + Set(comments(forSession: sessionId, path: path, staged: staged).map(\.lineKey)) + } + + /// Insert or replace the comment on `(path, staged, lineNumber, lineKind)`. + /// A blank comment deletes any existing entry for that line. + public func upsert(_ draft: DiffReviewComment, sessionId: String) { + let trimmed = draft.comment.trimmingCharacters(in: .whitespacesAndNewlines) + var list = bySession[sessionId] ?? [] + let existingIndex = list.firstIndex { + $0.path == draft.path + && $0.staged == draft.staged + && $0.lineNumber == draft.lineNumber + && $0.lineKind == draft.lineKind + } + if trimmed.isEmpty { + if let existingIndex { + list.remove(at: existingIndex) + } + } else { + var normalized = draft + normalized.comment = trimmed + if let existingIndex { + list[existingIndex] = normalized + } else { + list.append(normalized) + } + } + if list.isEmpty { + bySession.removeValue(forKey: sessionId) + } else { + bySession[sessionId] = list + } + save() + } + + public func delete(id: String, sessionId: String) { + guard var list = bySession[sessionId] else { return } + list.removeAll { $0.id == id } + if list.isEmpty { + bySession.removeValue(forKey: sessionId) + } else { + bySession[sessionId] = list + } + save() + } + + public func clear(sessionId: String) { + guard bySession.removeValue(forKey: sessionId) != nil else { return } + save() + } + + /// Formats draft comments grouped by file path into a structured review + /// prompt ready to send to the coding agent. + public static func formatReviewPrompt(_ comments: [DiffReviewComment]) -> String { + guard !comments.isEmpty else { return "" } + var orderedPaths: [String] = [] + var grouped: [String: [DiffReviewComment]] = [:] + for item in comments { + if grouped[item.path] == nil { + orderedPaths.append(item.path) + } + grouped[item.path, default: []].append(item) + } + + var sections: [String] = [ + "Please review and address the following diff comments:" + ] + for path in orderedPaths { + let fileComments = (grouped[path] ?? []).sorted { lhs, rhs in + if lhs.lineNumber != rhs.lineNumber { return lhs.lineNumber < rhs.lineNumber } + return lhs.createdAt < rhs.createdAt + } + var lines: [String] = ["### `\(path)`"] + for item in fileComments { + let kindLabel: String = switch item.lineKind { + case .addition: "added" + case .deletion: "removed" + case .context: "context" + } + let sideLabel = item.staged ? "staged, \(kindLabel)" : kindLabel + lines.append("") + lines.append("**Line \(item.lineNumber)** (\(sideLabel)):") + let snippet = item.snippet.trimmingCharacters(in: .newlines) + if !snippet.isEmpty { + lines.append("```diff") + lines.append(snippet) + lines.append("```") + } + lines.append(item.comment) + } + sections.append(lines.joined(separator: "\n")) + } + return sections.joined(separator: "\n\n") + } + + private func save() { + if bySession.isEmpty { + defaults.removeObject(forKey: storageKey) + return + } + if let data = try? JSONEncoder().encode(bySession) { + defaults.set(data, forKey: storageKey) + } + } + + private static func load(from defaults: UserDefaults, key: String) -> [String: [DiffReviewComment]] { + guard let data = defaults.data(forKey: key), + let decoded = try? JSONDecoder().decode([String: [DiffReviewComment]].self, from: data) else { + return [:] + } + return decoded + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Push/PushPayload.swift b/ios/Packages/HapiKit/Sources/HapiClient/Push/PushPayload.swift index 00d02efa5c1..6e1139f8604 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Push/PushPayload.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Push/PushPayload.swift @@ -73,6 +73,9 @@ public struct PushPayload: Equatable, Sendable { public var notifySummary: PushNotifySummary? /// Hub coalescing tag (`FcmSendPayload.tag`), when present. public var tag: String? + /// Stable UUID identifying the originating hub for O(1) multi-hub routing. + /// Absent on pushes sent by older hubs. + public var hubId: String? /// The contract version this client implements. public static let contractVersion = "1" @@ -145,7 +148,8 @@ public struct PushPayload: Equatable, Sendable { severity: PushSeverity? = nil, contractVersion: String? = nil, notifySummary: PushNotifySummary? = nil, - tag: String? = nil + tag: String? = nil, + hubId: String? = nil ) { self.type = type self.rawType = rawType @@ -159,6 +163,7 @@ public struct PushPayload: Equatable, Sendable { self.contractVersion = contractVersion self.notifySummary = notifySummary self.tag = tag + self.hubId = hubId } // MARK: - Parsing @@ -183,7 +188,8 @@ public struct PushPayload: Equatable, Sendable { severity: data["severity"].flatMap(PushSeverity.init(rawValue:)), contractVersion: nonBlank(data["contractVersion"]), notifySummary: data["notifySummary"].flatMap(parseNotifySummary), - tag: nonBlank(data["tag"]) + tag: nonBlank(data["tag"]), + hubId: nonBlank(data["hubId"]) ) } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/SSE/ReconnectPolicy.swift b/ios/Packages/HapiKit/Sources/HapiClient/SSE/ReconnectPolicy.swift index d9b9c3533eb..5509f0172d3 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/SSE/ReconnectPolicy.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/SSE/ReconnectPolicy.swift @@ -13,6 +13,19 @@ public enum SSETimings { /// than this. One missed heartbeat interval after an OS suspend is /// already enough to distrust the socket (no FIN/RST ever surfaces). public static let foregroundResumeStalenessMs = 45_000 + /// On app-foreground, if an open socket has been silent for at least this + /// duration (but under `foregroundResumeStalenessMs`), run an active + /// liveness probe and tighten the next-frame deadline so half-open sockets + /// killed during brief OS suspension recover quickly instead of waiting 90 s. + public static let foregroundResumeProbeAfterMs = 5_000 + /// Timeout for the active foreground liveness probe. + public static let foregroundResumeProbeTimeoutMs = 5_000 + /// Tightened post-resume heartbeat deadline (30 s hub heartbeat + 5 s grace) + /// when a socket resumes after brief background silence. + public static let foregroundResumeHeartbeatGraceMs = 35_000 + /// An in-flight connect attempt older than this when returning to foreground + /// is abandoned immediately instead of waiting out the full 10 s timeout. + public static let foregroundResumeConnectingStalenessMs = 3_000 /// Staleness check interval. Checks are skipped while suspended. public static let watchdogTickMs = 10_000 /// An attempt that has not reached OPEN within 10 s is likely hung on a diff --git a/ios/Packages/HapiKit/Sources/HapiClient/SSE/SSEClient.swift b/ios/Packages/HapiKit/Sources/HapiClient/SSE/SSEClient.swift index 7797395c11b..ec968807b8f 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/SSE/SSEClient.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/SSE/SSEClient.swift @@ -41,6 +41,11 @@ public struct SSEClientConfiguration: Sendable { /// Jitter draw added to every backoff delay. Injectable so tests are /// deterministic; defaults to uniform over the policy's jitter range. public var jitterMs: @Sendable () -> Int + /// Optional active liveness probe run when returning to foreground after a + /// brief silence (`5 s ..< 45 s`). Returning `false` (e.g. hub reports 404 + /// for `subscriptionId` or transport error) tears the socket down immediately + /// instead of waiting for the 90 s staleness watchdog. + public var foregroundLivenessProbe: (@Sendable (_ subscriptionId: String?) async -> Bool)? public init( baseUrl: URL, @@ -49,7 +54,8 @@ public struct SSEClientConfiguration: Sendable { visibility: String = "visible", acceptEncodingIdentity: Bool = false, reconnectPolicy: ReconnectPolicy = ReconnectPolicy(), - jitterMs: (@Sendable () -> Int)? = nil + jitterMs: (@Sendable () -> Int)? = nil, + foregroundLivenessProbe: (@Sendable (_ subscriptionId: String?) async -> Bool)? = nil ) { self.baseUrl = baseUrl self.tokenProvider = tokenProvider @@ -59,6 +65,7 @@ public struct SSEClientConfiguration: Sendable { self.reconnectPolicy = reconnectPolicy let range = reconnectPolicy.jitterRangeMs self.jitterMs = jitterMs ?? { Int.random(in: range) } + self.foregroundLivenessProbe = foregroundLivenessProbe } } @@ -156,6 +163,7 @@ public actor SSEClient { private var pathTask: Task? private var currentAttemptTask: Task? private var sleepTask: Task? + private var foregroundProbeTask: Task? private var resumeWaiters: [CheckedContinuation] = [] private var stopped = false @@ -169,6 +177,7 @@ public actor SSEClient { private(set) var handshakeSeen = false private(set) var connectStartedAtMs = 0 private(set) var lastActivityAtMs = 0 + private var foregroundCheckDeadlineMs: Int? public init( configuration: SSEClientConfiguration, @@ -218,6 +227,9 @@ public actor SSEClient { suspended = false drainResumeWaiters() sleepTask?.cancel() + foregroundProbeTask?.cancel() + foregroundProbeTask = nil + foregroundCheckDeadlineMs = nil currentAttemptTask?.cancel() pathTask?.cancel() pathTask = nil @@ -235,23 +247,85 @@ public actor SSEClient { // A pending backoff sleep is abandoned; the run loop parks at the // top until resume() and then retries immediately. sleepTask?.cancel() + foregroundProbeTask?.cancel() + foregroundProbeTask = nil + foregroundCheckDeadlineMs = nil } /// App returned to foreground. A parked retry runs immediately. When a - /// connection survived suspension, `staleThresholdCheck` distrusts it if - /// it has been silent for ≥ 45 s (`SSETimings.foregroundResumeStalenessMs`) - /// — an OS suspend can kill the socket without any error surfacing — and - /// reconnects immediately. + /// connection survived suspension: + /// - an in-flight connect attempt older than 3 s is abandoned immediately; + /// - an open socket silent ≥ 45 s (`SSETimings.foregroundResumeStalenessMs`) + /// is torn down and rebuilt immediately; + /// - an open socket silent for 5–45 s runs an active liveness probe (if + /// configured) with a 5 s timeout and tightens the next-frame deadline to + /// one heartbeat interval + grace (35 s) so half-open sockets recover fast. public func resume(staleThresholdCheck: Bool = true) { guard !stopped, suspended else { return } suspended = false drainResumeWaiters() - if staleThresholdCheck, transportOpen, - clock.nowMs() - lastActivityAtMs >= SSETimings.foregroundResumeStalenessMs { + let now = clock.nowMs() + if staleThresholdCheck, !transportOpen, currentAttemptTask != nil, + now - connectStartedAtMs >= SSETimings.foregroundResumeConnectingStalenessMs { currentAttemptTask?.cancel() + return + } + guard staleThresholdCheck, transportOpen else { return } + let silenceMs = now - lastActivityAtMs + if silenceMs >= SSETimings.foregroundResumeStalenessMs { + currentAttemptTask?.cancel() + } else if silenceMs >= SSETimings.foregroundResumeProbeAfterMs { + foregroundCheckDeadlineMs = max( + now + SSETimings.foregroundResumeProbeTimeoutMs, + lastActivityAtMs + SSETimings.foregroundResumeHeartbeatGraceMs + ) + if let probe = configuration.foregroundLivenessProbe { + startForegroundProbe( + probe: probe, + subscriptionId: subscriptionId, + activityAtStart: lastActivityAtMs + ) + } + } + } + + private func startForegroundProbe( + probe: @escaping @Sendable (_ subscriptionId: String?) async -> Bool, + subscriptionId: String?, + activityAtStart: Int + ) { + foregroundProbeTask?.cancel() + let clock = self.clock + foregroundProbeTask = Task { [weak self] in + let isAlive = await withTaskGroup(of: Bool?.self, returning: Bool?.self) { group in + group.addTask { + await probe(subscriptionId) + } + group.addTask { + do { + try await clock.sleep(ms: SSETimings.foregroundResumeProbeTimeoutMs) + return false + } catch { + return nil + } + } + defer { group.cancelAll() } + for await outcome in group { + if let outcome { return outcome } + } + return nil + } + guard !Task.isCancelled, isAlive == false else { return } + await self?.handleForegroundProbeFailure(activityAtStart: activityAtStart) } } + private func handleForegroundProbeFailure(activityAtStart: Int) { + guard !stopped, !suspended, transportOpen, lastActivityAtMs == activityAtStart else { return } + foregroundCheckDeadlineMs = nil + currentAttemptTask?.cancel() + } + /// Seeds the resume cursor before `start()` (e.g. one persisted from a /// previous process, keyed to this same subscription filter set — never /// seed a cursor recorded under a different scope/hub/namespace). @@ -349,15 +423,23 @@ public actor SSEClient { // MARK: - One connection attempt private func performAttempt(request: URLRequest) async -> AttemptExit { + let signpost = HapiSignpost.begin("SSEAttempt") + defer { HapiSignpost.end(signpost) } connectStartedAtMs = clock.nowMs() lastActivityAtMs = connectStartedAtMs transportOpen = false handshakeSeen = false + foregroundProbeTask?.cancel() + foregroundProbeTask = nil + foregroundCheckDeadlineMs = nil let attemptTask = Task { await self.readAttempt(request: request) } currentAttemptTask = attemptTask let watchdogTask = Task { await self.runWatchdog(killing: attemptTask) } let exit = await attemptTask.value watchdogTask.cancel() + foregroundProbeTask?.cancel() + foregroundProbeTask = nil + foregroundCheckDeadlineMs = nil currentAttemptTask = nil transportOpen = false handshakeSeen = false @@ -384,8 +466,14 @@ public actor SSEClient { lastActivityAtMs = clock.nowMs() case .bytes(let data): // Any received bytes — heartbeats, comments, partial - // frames — count as activity for the staleness clock. + // frames — count as activity for the staleness clock and + // prove the connection survived suspension. lastActivityAtMs = clock.nowMs() + if foregroundCheckDeadlineMs != nil || foregroundProbeTask != nil { + foregroundCheckDeadlineMs = nil + foregroundProbeTask?.cancel() + foregroundProbeTask = nil + } for frame in parser.consume(data) { handleFrame(frame) } @@ -427,9 +515,14 @@ public actor SSEClient { handshakeSeen = true subscriptionId = payload?.subscriptionId setState(.connected) + let verdict = payload?.resume ?? .gap + DiagnosticEventLog.shared.record( + category: "sse", + "Connected scope=\(configuration.scope == .global ? "global" : "session") resume=\(verdict == .ok ? "ok" : "gap")" + ) // Absent verdict = older hub = cannot prove continuity: gap. continuation?.yield(.handshake( - resume: payload?.resume ?? .gap, + resume: verdict, subscriptionId: payload?.subscriptionId )) } else { @@ -459,7 +552,8 @@ public actor SSEClient { attemptTask.cancel() return } - } else if now - lastActivityAtMs >= SSETimings.stalenessThresholdMs { + } else if now - lastActivityAtMs >= SSETimings.stalenessThresholdMs + || (foregroundCheckDeadlineMs.map { now >= $0 } ?? false) { attemptTask.cancel() return } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Settings/AgentProfileStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Settings/AgentProfileStore.swift new file mode 100644 index 00000000000..1c326f38162 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Settings/AgentProfileStore.swift @@ -0,0 +1,98 @@ +import Foundation +import HapiProtocol +import Observation + +/// A locally saved agent configuration preset (flavor + model + effort + permission mode) +/// for quick one-tap switching in New Session and Session Settings. +public struct AgentProfile: Identifiable, Codable, Equatable, Sendable { + public let id: String + public var name: String + public var flavor: String + public var model: String? + public var effort: String? + public var permissionMode: PermissionMode? + + public init( + id: String = UUID().uuidString, + name: String, + flavor: String, + model: String? = nil, + effort: String? = nil, + permissionMode: PermissionMode? = nil + ) { + self.id = id + self.name = name + self.flavor = flavor + self.model = model + self.effort = effort + self.permissionMode = permissionMode + } + + /// Compact human summary such as `"sonnet · high · default"`. + public var summaryText: String { + var parts: [String] = [] + if let model, !model.isEmpty { parts.append(model) } + if let effort, !effort.isEmpty { parts.append(effort) } + if let permissionMode { parts.append(permissionMode.rawValue) } + return parts.joined(separator: " · ") + } +} + +/// App-wide `UserDefaults`-backed store for local agent configuration presets. +@MainActor @Observable +public final class AgentProfileStore { + public static let shared = AgentProfileStore() + public static let storageKey = "hapi.agentProfiles.v1" + + public private(set) var profiles: [AgentProfile] + + private let defaults: UserDefaults? + + public init(defaults: UserDefaults? = .standard) { + self.defaults = defaults + self.profiles = Self.load(from: defaults) + } + + public func profiles(forFlavor flavor: String) -> [AgentProfile] { + profiles.filter { $0.flavor.caseInsensitiveCompare(flavor) == .orderedSame } + } + + public func save(_ profile: AgentProfile) { + let trimmed = profile.name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + var normalized = profile + normalized.name = trimmed + if let idx = profiles.firstIndex(where: { $0.id == normalized.id }) { + profiles[idx] = normalized + } else { + profiles.append(normalized) + } + profiles.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } + persist() + } + + public func delete(id: String) { + profiles.removeAll { $0.id == id } + persist() + } + + private func persist() { + guard let defaults else { return } + if profiles.isEmpty { + defaults.removeObject(forKey: Self.storageKey) + return + } + if let data = try? JSONEncoder().encode(profiles) { + defaults.set(data, forKey: Self.storageKey) + } + } + + private static func load(from defaults: UserDefaults?) -> [AgentProfile] { + guard let defaults, + let data = defaults.data(forKey: storageKey), + let decoded = try? JSONDecoder().decode([AgentProfile].self, from: data) else { + return [] + } + return decoded + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Settings/QuotaPace.swift b/ios/Packages/HapiKit/Sources/HapiClient/Settings/QuotaPace.swift new file mode 100644 index 00000000000..698b9ee510d --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Settings/QuotaPace.swift @@ -0,0 +1,113 @@ +import Foundation +import HapiProtocol + +/// Projected consumption pace for a rate-limit quota window (modeled on +/// linear burn-rate extrapolation once enough of the window has elapsed). +public enum QuotaPace: Equatable, Sendable { + case unknown + case onTrack + case tight + case runsOut(Date) + case reached + + /// Infer a quota window's total duration in seconds from the hub-provided + /// `window` token (e.g. `"5h"`, `"weekly"`, `"24h"`, `"7d"`), falling back + /// to the bucket `id` or human `label`. + public static func inferWindowSeconds(window: String?, id: String = "", label: String = "") -> TimeInterval? { + for candidate in [window, id, label] { + guard let raw = candidate?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), + !raw.isEmpty else { + continue + } + if let seconds = parseDurationToken(raw) { + return seconds + } + } + return nil + } + + /// Evaluate the burn-rate pace for a quota bucket as of `now`. + public static func evaluate( + usedPercent: Double, + resetDate: Date?, + windowSeconds: TimeInterval?, + now: Date = Date() + ) -> QuotaPace { + guard usedPercent.isFinite else { return .unknown } + if usedPercent >= 100 { return .reached } + guard usedPercent > 0, + let resetDate, + let windowSeconds, + windowSeconds > 0 else { + return .unknown + } + + let remainingSeconds = resetDate.timeIntervalSince(now) + guard remainingSeconds > 0 else { return .unknown } + + let elapsed = windowSeconds - remainingSeconds + // Wait for a minimal sample (at least 60s, up to 1% of the window capped at 1h) + // so early bursts don't produce noisy projections. + let minimumElapsed = max(60, min(windowSeconds * 0.01, 3_600)) + guard elapsed >= minimumElapsed, elapsed < windowSeconds else { + return .unknown + } + + let projectedAtReset = (usedPercent / elapsed) * windowSeconds + if projectedAtReset > 100 { + let secondsUntilEmpty = ((100 - usedPercent) / usedPercent) * elapsed + guard secondsUntilEmpty.isFinite, secondsUntilEmpty > 0 else { return .reached } + let runsOutAt = now.addingTimeInterval(secondsUntilEmpty) + if runsOutAt < resetDate { + return .runsOut(runsOutAt) + } + } + return projectedAtReset >= 90 ? .tight : .onTrack + } + + /// Convenience wrapper over `UsageQuotasResponse.Bucket`. + public static func evaluate(_ bucket: UsageQuotasResponse.Bucket, now: Date = Date()) -> QuotaPace { + let duration = inferWindowSeconds(window: bucket.window, id: bucket.id, label: bucket.label) + return evaluate( + usedPercent: bucket.usedPercent, + resetDate: bucket.resetDate, + windowSeconds: duration, + now: now + ) + } + + private static func parseDurationToken(_ text: String) -> TimeInterval? { + if text.contains("five_hour") || text.contains("5-hour") || text.contains("5 hour") { + return 5 * 3_600 + } + if text.contains("seven_day") || text.contains("7-day") || text.contains("7 day") || text.contains("weekly") { + return 7 * 86_400 + } + if text.contains("daily") || text.contains("1-day") || text.contains("1 day") { + return 86_400 + } + if text.contains("monthly") || text.contains("30-day") || text.contains("30 day") { + return 30 * 86_400 + } + if text.contains("hourly") { + return 3_600 + } + + let pattern = #"(?:^|[^a-z0-9])(\d+)\s*(m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days|w|wk|week|weeks)(?:$|[^a-z0-9])"# + guard let regex = try? NSRegularExpression(pattern: pattern), + let match = regex.firstMatch(in: text, range: NSRange(text.startIndex.. 0 else { + return nil + } + + let unit = text[unitRange] + if unit.hasPrefix("m") { return value * 60 } + if unit.hasPrefix("h") { return value * 3_600 } + if unit.hasPrefix("d") { return value * 86_400 } + if unit.hasPrefix("w") { return value * 7 * 86_400 } + return nil + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Settings/QuotaPresentation.swift b/ios/Packages/HapiKit/Sources/HapiClient/Settings/QuotaPresentation.swift new file mode 100644 index 00000000000..ca3e8ddff5c --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Settings/QuotaPresentation.swift @@ -0,0 +1,234 @@ +import Foundation +import HapiProtocol + +/// Condenses multi-line CLI stderr dumps, JSON error blobs, and stack traces +/// into a single human-readable line so partial fetch failures never flood +/// compact cards or banners. +public enum ConciseErrorSummary { + /// Extract a single concise line from a potentially noisy error payload. + public static func concise(_ raw: String, maxLength: Int = 120) -> String { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return "" } + + if let extracted = extractJSONErrorMessage(from: trimmed) { + return clamp(collapseWhitespace(extracted), maxLength: maxLength) + } + + let normalized = trimmed + .replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + let lines = normalized + .split(separator: "\n", omittingEmptySubsequences: false) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + + let chosen = lines.first(where: { !isNoiseLine($0) }) ?? lines.first ?? trimmed + return clamp(collapseWhitespace(chosen), maxLength: maxLength) + } + + /// True when the raw error contains extra lines or characters beyond the + /// concise summary, warranting an optional expand control. + public static func hasExtraDetail(raw: String, concise: String) -> Bool { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return false } + return collapseWhitespace(trimmed) != concise || trimmed.contains("\n") + } + + private static func isNoiseLine(_ line: String) -> Bool { + if line == "{" || line == "}" || line == "[" || line == "]" { + return true + } + if line.allSatisfy({ $0 == "-" || $0 == "=" || $0 == "*" }) { + return true + } + if line.hasPrefix("at ") || line.hasPrefix("Traceback (most recent call last)") { + return true + } + return false + } + + private static func extractJSONErrorMessage(from text: String) -> String? { + guard let braceIndex = text.firstIndex(of: "{") else { return nil } + let prefix = text[.. String? { + guard case .object(let dict) = value else { return nil } + for key in ["message", "detail", "error_description"] { + if case .string(let text)? = dict[key], + !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return text + } + } + if let nested = dict["error"] { + switch nested { + case .string(let text) where !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty: + return text + case .object: + if let inner = findMessage(in: nested) { + return inner + } + default: + break + } + } + return nil + } + + private static func collapseWhitespace(_ text: String) -> String { + text.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ") + } + + private static func clamp(_ text: String, maxLength: Int) -> String { + guard maxLength > 1, text.count > maxLength else { return text } + let cutoff = text.index(text.startIndex, offsetBy: maxLength - 1) + var head = String(text[.. Bool { + !machine.supported + || (machine.accounts.isEmpty && machine.error?.contains("RPC method not available") == true) + } + + public static func isAccountHealthy(_ account: UsageQuotasResponse.Account) -> Bool { + if !account.buckets.isEmpty { + return true + } + if let credits = account.creditsLabel?.trimmingCharacters(in: .whitespacesAndNewlines), + !credits.isEmpty { + return true + } + return account.status == "ok" || account.status == "custom_provider" + } + + public static func partitionAccounts( + _ accounts: [UsageQuotasResponse.Account] + ) -> QuotaAccountPartition { + var healthy: [UsageQuotasResponse.Account] = [] + var unavailable: [UsageQuotasResponse.Account] = [] + for account in accounts { + if isAccountHealthy(account) { + healthy.append(account) + } else { + unavailable.append(account) + } + } + return QuotaAccountPartition(healthy: healthy, unavailable: unavailable) + } + + public static func isMachineHealthy(_ machine: UsageQuotasResponse.Machine) -> Bool { + guard !isRunnerUnsupported(machine) else { return false } + let accounts = partitionAccounts(machine.visibleAccounts) + return !accounts.healthy.isEmpty + } + + /// Build a display plan from the hub's online machine list. + /// + /// - When `preferredMachineId` matches an entry in `machines`, that machine + /// becomes the primary focus and all other machines are moved into + /// `otherMachines` so unrelated machine failures never clutter a chat's + /// context sheet. + /// - Otherwise, healthy machines are shown first and failing/unsupported + /// machines are grouped into `unavailableMachines`. + public static func plan( + machines: [UsageQuotasResponse.Machine], + preferredMachineId: String? = nil + ) -> QuotaDisplayPlan { + let relevant = machines.filter { + !$0.supported || $0.error?.isEmpty == false || !$0.visibleAccounts.isEmpty + } + if let preferredId = preferredMachineId?.trimmingCharacters(in: .whitespacesAndNewlines), + !preferredId.isEmpty, + let preferred = relevant.first(where: { $0.machineId == preferredId }) { + let others = relevant.filter { $0.machineId != preferredId } + if isMachineHealthy(preferred) { + return QuotaDisplayPlan( + primaryMachines: [preferred], + unavailableMachines: [], + otherMachines: others + ) + } + return QuotaDisplayPlan( + primaryMachines: [], + unavailableMachines: [preferred], + otherMachines: others + ) + } + + var primary: [UsageQuotasResponse.Machine] = [] + var unavailable: [UsageQuotasResponse.Machine] = [] + for machine in relevant { + if isMachineHealthy(machine) { + primary.append(machine) + } else { + unavailable.append(machine) + } + } + return QuotaDisplayPlan( + primaryMachines: primary, + unavailableMachines: unavailable, + otherMachines: [] + ) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Settings/SettingsPrefs.swift b/ios/Packages/HapiKit/Sources/HapiClient/Settings/SettingsPrefs.swift index 35ecce46308..131a7be392a 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Settings/SettingsPrefs.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Settings/SettingsPrefs.swift @@ -1,4 +1,5 @@ import Foundation +import HapiProtocol import Observation /// Theme choice (web `ThemeMode` twin; Android @@ -113,3 +114,53 @@ public final class LanguagePrefs { defaults.set(language.storageKey, forKey: Self.languageKey) } } + +/// Chat reading/transcript preferences persisted in `UserDefaults`. +@MainActor @Observable +public final class ReadingPrefs { + public private(set) var autoExpandReasoning: Bool + + private let defaults: UserDefaults + + public static let autoExpandReasoningKey = "settings.autoExpandReasoning" + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + self.autoExpandReasoning = defaults.bool(forKey: Self.autoExpandReasoningKey) + } + + public func setAutoExpandReasoning(_ enabled: Bool) { + autoExpandReasoning = enabled + defaults.set(enabled, forKey: Self.autoExpandReasoningKey) + } +} + +/// Per-device push event filter persisted in `UserDefaults`. Sent to each +/// paired hub on `POST /api/devices/register`; unreadable/absent storage +/// degrades to all categories enabled. +@MainActor @Observable +public final class PushNotificationPrefs { + public private(set) var preferences: PushNotificationPreferences + + private let defaults: UserDefaults + + public static let preferencesKey = "settings.pushPreferences" + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + if let data = defaults.data(forKey: Self.preferencesKey), + let decoded = try? JSONDecoder().decode(PushNotificationPreferences.self, from: data) { + self.preferences = decoded + } else { + self.preferences = .allEnabled + } + } + + public func setPreferences(_ preferences: PushNotificationPreferences) { + guard self.preferences != preferences else { return } + self.preferences = preferences + if let encoded = try? JSONEncoder().encode(preferences) { + defaults.set(encoded, forKey: Self.preferencesKey) + } + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift index ea7be7b4385..7c87dccb987 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift @@ -63,9 +63,14 @@ public actor MessageWindowController { private let provider: any MessagesProviding private let snapshots: WindowSnapshotStore? private let historyRetentionLimit: Int + private let persistDebounce: Duration private var stateValue: MessageWindowState private var observers: [UUID: AsyncStream.Continuation] = [:] + private var pendingPersist: PersistedMessageWindow? + private var persistGeneration = 0 + private var persistTask: Task? + private var didWriteSnapshotOnce = false // MARK: - Lifecycle @@ -74,12 +79,14 @@ public actor MessageWindowController { provider: any MessagesProviding, snapshots: WindowSnapshotStore? = nil, initialState: MessageWindowState? = nil, - historyRetentionLimit: Int = MessageWindowConstants.historyWindowSize + historyRetentionLimit: Int = MessageWindowConstants.historyWindowSize, + persistDebounce: Duration = .milliseconds(500) ) { self.sessionId = sessionId self.provider = provider self.snapshots = snapshots self.historyRetentionLimit = historyRetentionLimit + self.persistDebounce = persistDebounce self.stateValue = initialState ?? MessageWindowLogic.createState(sessionId: sessionId) self.stateValue.historyRetentionLimit = historyRetentionLimit } @@ -139,6 +146,8 @@ public actor MessageWindowController { /// trailing run is requested and awaited, so the caller returns only /// after a sync that STARTED at or after this call. public func syncTail(ensureAfterCurrent: Bool = false, allowingHistoryReset: Bool = false) async { + let signpost = HapiSignpost.begin("MessageWindowSyncTail") + defer { HapiSignpost.end(signpost) } if allowingHistoryReset { let epoch = controllerEpoch if let runningTask { await runningTask.value } @@ -921,13 +930,51 @@ public actor MessageWindowController { return status != "completed" && status != "failed" } + /// Flushes any debounced snapshot write to disk (app background / shutdown / tests). + public func flushPersistence() async { + persistTask?.cancel() + persistTask = nil + await flushPendingPersistence(prune: true) + } + private func persist() { guard let snapshots else { return } let state = stateValue + persistGeneration += 1 + persistTask?.cancel() + persistTask = nil if MessageWindowLogic.shouldPersist(state) { - snapshots.save(sessionId: sessionId, snapshot: MessageWindowLogic.toPersisted(state)) + pendingPersist = MessageWindowLogic.toPersisted(state) + let delay = persistDebounce + persistTask = Task { [weak self] in + do { + try await Task.sleep(for: delay) + } catch { + return // superseded by a newer persist() or flushPersistence() + } + guard let self else { return } + let shouldPrune = await !self.didWriteSnapshotOnce + await self.flushPendingPersistence(prune: shouldPrune) + } } else { - snapshots.delete(sessionId: sessionId) + pendingPersist = nil + let id = sessionId + Task.detached(priority: .utility) { + snapshots.delete(sessionId: id) + } + } + } + + private func flushPendingPersistence(prune: Bool) async { + guard let snapshots, let snapshot = pendingPersist else { return } + let flushedGeneration = persistGeneration + let id = sessionId + await Task.detached(priority: .utility) { + snapshots.save(sessionId: id, snapshot: snapshot, pruneNow: prune) + }.value + didWriteSnapshotOnce = true + if persistGeneration == flushedGeneration { + pendingPersist = nil } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowControllers.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowControllers.swift index 6e7b0d6f9fc..fc750d6d7bc 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowControllers.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowControllers.swift @@ -59,4 +59,11 @@ public actor MessageWindowControllers { public func clear(sessionId: String) async { await controllers[sessionId]?.clear() } + + /// Flushes debounced window snapshots for all open sessions (app background / shutdown). + public func flushPersistence() async { + for controller in controllers.values { + await controller.flushPersistence() + } + } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/ProjectGroupCollapseStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/ProjectGroupCollapseStore.swift new file mode 100644 index 00000000000..3fabcb460b6 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/ProjectGroupCollapseStore.swift @@ -0,0 +1,144 @@ +import Foundation +import Observation + +/// Pure helpers for building unambiguous `(machine, path)` project group keys +/// and disambiguated titles when two paths on the same machine share a basename +/// (e.g. `/Users/dev/work/hapi` and `/Users/dev/oss/hapi` → `work/hapi`, `oss/hapi`). +public enum ProjectGroupIdentity { + public static let unknownMachineKey = "__unknown__" + public static let otherPathKey = "__other__" + + public static func normalizedPath(_ raw: String?) -> String? { + guard var trimmed = raw?.trimmingCharacters(in: .whitespacesAndNewlines), + !trimmed.isEmpty else { return nil } + while trimmed.count > 1 && (trimmed.hasSuffix("/") || trimmed.hasSuffix("\\")) { + trimmed.removeLast() + } + return trimmed.isEmpty ? nil : trimmed + } + + /// Stable grouping key combining machine identity and normalized workspace path + /// so identical paths on different machines never collide. + public static func groupKey(machineId: String?, path: String?) -> String { + let machine = (machineId?.trimmingCharacters(in: .whitespacesAndNewlines)).flatMap { $0.isEmpty ? nil : $0 } + ?? unknownMachineKey + let cleanPath = normalizedPath(path) ?? otherPathKey + return "\(machine)|\(cleanPath)" + } + + public static func pathComponents(_ path: String) -> [String] { + path.split(whereSeparator: { $0 == "/" || $0 == "\\" }).map(String.init) + } + + /// Compute human titles for a set of `(key, machineId, normalizedPath)` groups. + /// When multiple groups on the same machine share the same basename, appends the + /// shortest distinguishing parent path prefix (`parent/basename`). + public static func disambiguatedTitles( + for groups: [(key: String, machineId: String?, path: String?)], + otherLabel: String = "Other" + ) -> [String: String] { + struct Entry { + let key: String + let machineBucket: String + let components: [String] + } + + var entries: [Entry] = [] + var titles: [String: String] = [:] + + for group in groups { + guard let path = normalizedPath(group.path) else { + titles[group.key] = otherLabel + continue + } + let components = pathComponents(path) + guard let last = components.last else { + titles[group.key] = path + continue + } + let machineBucket = (group.machineId?.trimmingCharacters(in: .whitespacesAndNewlines)) + .flatMap { $0.isEmpty ? nil : $0 } ?? unknownMachineKey + entries.append(Entry(key: group.key, machineBucket: machineBucket, components: components)) + titles[group.key] = last + } + + // Group by (machineBucket, basename) to find same-machine basename collisions. + var collisions: [String: [Entry]] = [:] + for entry in entries { + guard let base = entry.components.last else { continue } + let bucketKey = "\(entry.machineBucket)|\(base.lowercased())" + collisions[bucketKey, default: []].append(entry) + } + + for (_, group) in collisions where group.count > 1 { + // Increase suffix depth (2, 3, ...) until each colliding path gets a unique label. + var depth = 2 + let maxDepth = group.map { $0.components.count }.max() ?? 2 + while depth <= maxDepth { + let candidates = group.map { entry -> (String, String) in + let slice = entry.components.suffix(min(depth, entry.components.count)) + return (entry.key, slice.joined(separator: "/")) + } + let uniqueLabels = Set(candidates.map(\.1)) + if uniqueLabels.count == group.count || depth == maxDepth { + for (key, label) in candidates { + titles[key] = label + } + break + } + depth += 1 + } + } + + return titles + } +} + +/// Persisted set of collapsed project section keys (`machineId|path`) in the +/// Home session list, scoped per hub/namespace. Default state is expanded. +@MainActor @Observable +public final class ProjectGroupCollapseStore { + public private(set) var collapsedKeys: Set + + private let defaults: UserDefaults? + private let storageKey: String + + public init(scope: String, defaults: UserDefaults? = .standard) { + self.defaults = defaults + self.storageKey = "hapi.projectGroupCollapsed.v1.\(scope)" + let stored = defaults?.stringArray(forKey: storageKey) ?? [] + self.collapsedKeys = Set(stored) + } + + public func isCollapsed(_ key: String) -> Bool { + collapsedKeys.contains(key) + } + + public func toggle(_ key: String) { + if collapsedKeys.contains(key) { + collapsedKeys.remove(key) + } else { + collapsedKeys.insert(key) + } + persist() + } + + public func expand(_ key: String) { + guard collapsedKeys.remove(key) != nil else { return } + persist() + } + + public func collapse(_ key: String) { + guard collapsedKeys.insert(key).inserted else { return } + persist() + } + + private func persist() { + guard let defaults else { return } + if collapsedKeys.isEmpty { + defaults.removeObject(forKey: storageKey) + } else { + defaults.set(Array(collapsedKeys).sorted(), forKey: storageKey) + } + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionGroups.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionGroups.swift new file mode 100644 index 00000000000..4fd3d1192bb --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionGroups.swift @@ -0,0 +1,485 @@ +import Foundation +import HapiProtocol +import Observation + +/// Result of laying out two-level session groups (`web/src/lib/sessionGroups.ts`). +/// +/// A session that spawns peers (`spawn_peer`) leads a group; spawned sessions +/// carry hub-owned `metadata.groupLeaderId`. The list nests members under their +/// leader instead of showing them as rows of their own. +public struct SessionGroupLayout: Equatable, Sendable { + /// Rows the list sections work with: ungrouped sessions, globally-pinned + /// members, and leaders (including filtered-out leaders kept as containers + /// for matching members). + public let topLevel: [SessionSummary] + /// Visible members to nest under each leader, in the order of `visible`. + public let membersByLeader: [String: [SessionSummary]] + /// Inverse map from nested member id to its leader id. + public let leaderIdByMember: [String: String] + + public init( + topLevel: [SessionSummary], + membersByLeader: [String: [SessionSummary]], + leaderIdByMember: [String: String] + ) { + self.topLevel = topLevel + self.membersByLeader = membersByLeader + self.leaderIdByMember = leaderIdByMember + } +} + +/// Counts of group members needing attention or still active +/// (`web/src/lib/sessionGroups.ts` `SessionGroupStatus`). +public struct SessionGroupStatus: Equatable, Hashable, Sendable { + /// Active members waiting on an approval or an answer. + public var waiting: Int + /// Active working members (thinking, background tasks, open tool work, or fresh running job). + public var working: Int + /// Members with unread content. + public var unread: Int + + public init(waiting: Int = 0, working: Int = 0, unread: Int = 0) { + self.waiting = waiting + self.working = working + self.unread = unread + } +} + +/// What dissolving a group interrupts, counted over the sessions it would archive +/// (`web/src/lib/sessionGroups.ts` `GroupDissolveImpact`). +public struct GroupDissolveImpact: Equatable, Hashable, Sendable { + public var waiting: Int + public var working: Int + public var unread: Int + /// Sessions in a git worktree, where unmerged work is easy to leave behind. + public var worktree: Int + + public init(waiting: Int = 0, working: Int = 0, unread: Int = 0, worktree: Int = 0) { + self.waiting = waiting + self.working = working + self.unread = unread + self.worktree = worktree + } +} + +/// Pure session-group layout, ranking, and summarization helpers +/// (faithful port of `web/src/lib/sessionGroups.ts` and `SessionList.tsx`). +public enum SessionGroups { + /// Partition `visible` into top-level rows and members nested under their leader. + /// + /// - Parameters: + /// - known: Every session the list may show under the current status filter, + /// before search, unread, and machine filters. A leader absent from `known` + /// (deleted or hidden by Show) leaves its members as ordinary rows. + /// - visible: The sessions that passed all active filters and search. + public static func layout( + known: [SessionSummary], + visible: [SessionSummary] + ) -> SessionGroupLayout { + var knownById: [String: SessionSummary] = [:] + knownById.reserveCapacity(known.count) + for session in known { + knownById[session.id] = session + } + let visibleIds = Set(visible.map(\.id)) + + var topLevel: [SessionSummary] = [] + var membersByLeader: [String: [SessionSummary]] = [:] + var leaderIdByMember: [String: String] = [:] + var containers: [SessionSummary] = [] + + for session in visible { + guard let leader = resolveLeader(for: session, knownById: knownById) else { + topLevel.append(session) + continue + } + leaderIdByMember[session.id] = leader.id + if membersByLeader[leader.id] != nil { + membersByLeader[leader.id]?.append(session) + } else { + membersByLeader[leader.id] = [session] + // A matching member keeps its filtered-out leader as the row it nests under. + if !visibleIds.contains(leader.id) { + containers.append(leader) + } + } + } + + return SessionGroupLayout( + topLevel: topLevel + containers, + membersByLeader: membersByLeader, + leaderIdByMember: leaderIdByMember + ) + } + + private static func resolveLeader( + for session: SessionSummary, + knownById: [String: SessionSummary] + ) -> SessionSummary? { + // A globally pinned member stays in the pinned section where it was put. + if session.globalPinned == true { return nil } + guard let leaderId = session.metadata?.groupLeaderId, + !leaderId.isEmpty, + leaderId != session.id + else { return nil } + guard let leader = knownById[leaderId] else { return nil } + // A leader that is itself a member would hide its own members, so it does not count. + if let leadersLeader = leader.metadata?.groupLeaderId, !leadersLeader.isEmpty { + return nil + } + return leader + } + + /// Every member of every leader across `sessions`, regardless of filters or pins + /// (`collectGroupMembers` in `web/src/lib/sessionGroups.ts`). + public static func collectMembers(from sessions: [SessionSummary]) -> [String: [SessionSummary]] { + var membersByLeader: [String: [SessionSummary]] = [:] + for session in sessions { + guard let leaderId = session.metadata?.groupLeaderId, + !leaderId.isEmpty, + leaderId != session.id + else { continue } + membersByLeader[leaderId, default: []].append(session) + } + return membersByLeader + } + + /// Summarize member states for the folded/expanded group bar. + public static func summarizeMembers( + _ members: [SessionSummary], + isUnread: (SessionSummary) -> Bool, + nowMs: Int = Int(Date().timeIntervalSince1970 * 1000) + ) -> SessionGroupStatus { + var status = SessionGroupStatus() + for member in members { + if member.active && member.pendingRequestsCount > 0 { + status.waiting += 1 + } else if member.hasAgentForegroundWork + || (member.active && member.derivedToolWork == true) + || member.hasInProgressJob(nowMs: nowMs) + { + status.working += 1 + } + if isUnread(member) { + status.unread += 1 + } + } + return status + } + + /// Summarize what dissolving `sessions` would interrupt. + public static func summarizeDissolve( + _ sessions: [SessionSummary], + nowMs: Int = Int(Date().timeIntervalSince1970 * 1000) + ) -> GroupDissolveImpact { + let base = summarizeMembers(sessions, isUnread: { _ in false }, nowMs: nowMs) + let worktree = sessions.filter { $0.metadata?.worktree != nil }.count + return GroupDissolveImpact( + waiting: base.waiting, + working: base.working, + unread: base.unread, + worktree: worktree + ) + } + + /// Promote each leader's search score to the maximum of its own score and + /// its matching members' scores, so search ranks a group by its best match. + public static func boostSearchScores( + _ index: SessionListSearch.ScoreIndex, + layout: SessionGroupLayout + ) -> SessionListSearch.ScoreIndex { + guard !layout.membersByLeader.isEmpty else { return index } + var scores = index.scores + for (leaderId, members) in layout.membersByLeader { + var best = scores[leaderId] ?? 0 + for member in members { + if let memberScore = scores[member.id], memberScore > best { + best = memberScore + } + } + if best > 0 { + scores[leaderId] = best + } + } + return SessionListSearch.ScoreIndex(scores: scores) + } + + /// Order a leader's nested members: project-pinned members lead, then + /// search relevance (when searching) or the list's configured sort order. + public static func sortMembers( + _ members: [SessionSummary], + order: SessionListOrder, + searchScores: SessionListSearch.ScoreIndex? = nil + ) -> [SessionSummary] { + members.sorted { lhs, rhs in + if (lhs.pinned == true) != (rhs.pinned == true) { + return lhs.pinned == true + } + if let searchScores { + let left = searchScores.scores[lhs.id] ?? 0 + let right = searchScores.scores[rhs.id] ?? 0 + if left != right { return left > right } + return sessionOrderPrecedes(lhs, rhs) + } + return sessionSummaryPrecedes(lhs, rhs, order: order) + } + } + + /// Sessions that dissolving a group will archive: every archivable or + /// unconfirmed member, followed by the leader if archivable or unconfirmed. + public static func dissolveTargets( + leader: SessionSummary, + allMembers: [SessionSummary], + unconfirmed: Set + ) -> (members: [SessionSummary], includeLeader: Bool, live: [SessionSummary]) { + let members = allMembers.filter { $0.isArchivable || unconfirmed.contains($0.id) } + let includeLeader = leader.isArchivable || unconfirmed.contains(leader.id) + let live = includeLeader ? members + [leader] : members + return (members, includeLeader, live) + } +} + +/// Persisted open member lists per hub and namespace +/// (mirrors web `hapi.open-session-groups.v1:`). +/// Member lists start folded by default; only explicit opens are saved. +@MainActor @Observable +public final class SessionGroupOpenStore { + public private(set) var openLeaderIds: Set + + private let defaults: UserDefaults? + private let storageKey: String + + public static let keyPrefix = "hapi.open-session-groups.v1:" + + /// Pass `defaults: nil` for in-memory test isolation. + public init(scope: String, defaults: UserDefaults? = .standard) { + self.defaults = defaults + self.storageKey = Self.keyPrefix + scope + if let saved = defaults?.stringArray(forKey: self.storageKey) { + self.openLeaderIds = Set(saved) + } else { + self.openLeaderIds = [] + } + } + + public func isOpen(_ leaderId: String) -> Bool { + openLeaderIds.contains(leaderId) + } + + public func setOpen(_ open: Bool, leaderId: String) { + var next = openLeaderIds + if open { + next.insert(leaderId) + } else { + next.remove(leaderId) + } + guard next != openLeaderIds else { return } + openLeaderIds = next + persist() + } + + /// Migrate open state when a leader session is reopened under a superseding id. + public func move(from oldLeaderId: String, to newLeaderId: String) { + guard oldLeaderId != newLeaderId, openLeaderIds.contains(oldLeaderId) else { return } + var next = openLeaderIds + next.remove(oldLeaderId) + next.insert(newLeaderId) + openLeaderIds = next + persist() + } + + private func persist() { + guard let defaults else { return } + if openLeaderIds.isEmpty { + defaults.removeObject(forKey: storageKey) + } else { + defaults.set(Array(openLeaderIds).sorted(), forKey: storageKey) + } + } +} + +/// Persisted unconfirmed dissolve-archive requests per hub and namespace +/// (mirrors web `hapi.dissolve-unconfirmed.v1:` in `DissolveGroupButton.tsx`). +/// +/// A runner-owned session can read as inactive and archived before its runner +/// confirmed cleanup, so the list alone cannot tell that the request still has +/// to be retried. Keeping this per hub + namespace ensures a reload does not +/// lose the retry. +@MainActor @Observable +public final class SessionGroupDissolveStore { + public private(set) var unconfirmedByLeader: [String: Set] + + private let defaults: UserDefaults? + private let storageKey: String + + public static let keyPrefix = "hapi.dissolve-unconfirmed.v1:" + + /// Pass `defaults: nil` for in-memory test isolation. + public init(scope: String, defaults: UserDefaults? = .standard) { + self.defaults = defaults + self.storageKey = Self.keyPrefix + scope + self.unconfirmedByLeader = Self.load(from: defaults, key: self.storageKey) + } + + public func unconfirmedIds(forLeaderId leaderId: String) -> Set { + unconfirmedByLeader[leaderId] ?? [] + } + + public func markUnconfirmed(sessionId: String, leaderId: String) { + var ids = unconfirmedByLeader[leaderId] ?? [] + guard ids.insert(sessionId).inserted else { return } + unconfirmedByLeader[leaderId] = ids + persist() + } + + public func clearUnconfirmed(sessionId: String, leaderId: String) { + guard var ids = unconfirmedByLeader[leaderId], ids.remove(sessionId) != nil else { return } + if ids.isEmpty { + unconfirmedByLeader.removeValue(forKey: leaderId) + } else { + unconfirmedByLeader[leaderId] = ids + } + persist() + } + + public func moveLeader(from oldLeaderId: String, to newLeaderId: String) { + guard oldLeaderId != newLeaderId, var ids = unconfirmedByLeader.removeValue(forKey: oldLeaderId) else { + return + } + if ids.remove(oldLeaderId) != nil { + ids.insert(newLeaderId) + } + unconfirmedByLeader[newLeaderId, default: []].formUnion(ids) + persist() + } + + private static func load(from defaults: UserDefaults?, key: String) -> [String: Set] { + guard let data = defaults?.data(forKey: key), + let raw = try? JSONDecoder().decode([String: [String]].self, from: data) + else { return [:] } + var result: [String: Set] = [:] + for (leaderId, ids) in raw where !ids.isEmpty { + result[leaderId] = Set(ids) + } + return result + } + + private func persist() { + guard let defaults else { return } + if unconfirmedByLeader.isEmpty { + defaults.removeObject(forKey: storageKey) + } else { + let encodable = unconfirmedByLeader.mapValues { Array($0).sorted() } + if let data = try? JSONEncoder().encode(encodable) { + defaults.set(data, forKey: storageKey) + } + } + } +} + +/// Orchestrates dissolving a session group: archive members first, re-verify +/// with the hub that no member joined/reopened/is starting, then archive the +/// leader (mirrors `web/src/components/DissolveGroupButton.tsx`). +@MainActor +public enum GroupDissolver { + public enum Outcome: Equatable, Sendable { + case nothingToDissolve + case succeeded + case membersFailed(failed: Int, total: Int) + case uncheckedMembers + case membersRunning(count: Int) + case leaderFailed(total: Int) + } + + public static func dissolve( + leader: SessionSummary, + allMembers: [SessionSummary], + store: SessionGroupDissolveStore, + archiveSession: @escaping @Sendable (String) async throws -> Void, + fetchSessions: @escaping @Sendable () async throws -> [SessionSummary], + refreshSessions: @escaping @MainActor () async -> Void, + nowMs: @escaping @MainActor () -> Int = { Int(Date().timeIntervalSince1970 * 1000) } + ) async -> Outcome { + let unconfirmed = store.unconfirmedIds(forLeaderId: leader.id) + let targets = SessionGroups.dissolveTargets( + leader: leader, + allMembers: allMembers, + unconfirmed: unconfirmed + ) + guard !targets.live.isEmpty else { + return .nothingToDissolve + } + + // Members first. A member that could not be stopped may still be + // working, and its reply reaches the operator through the leader, + // so the leader keeps running until every member is archived. + // Recorded before each request and cleared only by its success. + for member in targets.members { + store.markUnconfirmed(sessionId: member.id, leaderId: leader.id) + } + + var failed = 0 + if !targets.members.isEmpty { + let memberIds = targets.members.map(\.id) + await withTaskGroup(of: (String, Bool).self) { group in + for id in memberIds { + group.addTask { + do { + try await archiveSession(id) + return (id, true) + } catch { + return (id, false) + } + } + } + for await (id, succeeded) in group { + if succeeded { + store.clearUnconfirmed(sessionId: id, leaderId: leader.id) + } else { + failed += 1 + } + } + } + } + + await refreshSessions() + + if failed > 0 { + return .membersFailed(failed: failed, total: targets.members.count) + } + if !targets.includeLeader { + return .succeeded + } + + // Ask the hub again: the leader may have spawned another member + // since confirmation, and an archived member can be reopened from + // another client under the same id. + let latest: [SessionSummary] + do { + latest = try await fetchSessions() + } catch { + return .uncheckedMembers + } + + let now = nowMs() + let running = latest.filter { session in + session.id != leader.id + && session.metadata?.groupLeaderId == leader.id + && (session.isArchivable || session.isStarting(nowMs: now)) + }.count + if running > 0 { + return .membersRunning(count: running) + } + + store.markUnconfirmed(sessionId: leader.id, leaderId: leader.id) + do { + try await archiveSession(leader.id) + store.clearUnconfirmed(sessionId: leader.id, leaderId: leader.id) + await refreshSessions() + return .succeeded + } catch { + await refreshSessions() + return .leaderFailed(total: targets.live.count) + } + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListSearch.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListSearch.swift index 67c8c71f401..87911641aa7 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListSearch.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListSearch.swift @@ -32,6 +32,10 @@ public enum SessionListSearch { public struct ScoreIndex: Equatable, Sendable { public let scores: [String: Double] + public init(scores: [String: Double]) { + self.scores = scores + } + public func matches(_ sessionId: String) -> Bool { scores[sessionId] != nil } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/WindowSnapshotStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/WindowSnapshotStore.swift index 3c54300664b..1bf183350f1 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/WindowSnapshotStore.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/WindowSnapshotStore.swift @@ -24,12 +24,20 @@ import HapiProtocol public struct WindowSnapshotStore: Sendable { public let directory: URL public let maxSessions: Int + /// Maximum total bytes across all retained window snapshots. + public let maxTotalBytes: Int + public static let defaultMaxTotalBytes = 16 * 1024 * 1024 private static let suffix = ".window.json" - public init(directory: URL, maxSessions: Int = 10) { + public init( + directory: URL, + maxSessions: Int = 10, + maxTotalBytes: Int = WindowSnapshotStore.defaultMaxTotalBytes + ) { self.directory = directory self.maxSessions = maxSessions + self.maxTotalBytes = maxTotalBytes } /// Default location: `Caches/hapi-message-windows` (purgeable by the OS — @@ -40,12 +48,20 @@ public struct WindowSnapshotStore: Sendable { return WindowSnapshotStore(directory: caches.appendingPathComponent("hapi-message-windows")) } - public func save(sessionId: String, snapshot: PersistedMessageWindow) { + public func save(sessionId: String, snapshot: PersistedMessageWindow, pruneNow: Bool = true) { do { - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let data = try HapiJSON.encoder.encode(snapshot) - try data.write(to: fileURL(for: sessionId), options: .atomic) - prune() + let target = fileURL(for: sessionId) + // Never let a single oversized snapshot blow the cache budget and evict other sessions. + if data.count > maxTotalBytes { + try? FileManager.default.removeItem(at: target) + return + } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try data.write(to: target, options: .atomic) + if pruneNow { + prune() + } } catch { // Best-effort persistence, mirroring the web store. } @@ -70,20 +86,39 @@ public struct WindowSnapshotStore: Sendable { try? FileManager.default.removeItem(at: fileURL(for: sessionId)) } - /// Drop the least-recently-written files beyond ``maxSessions``. - private func prune() { + /// Drop the least-recently-written files beyond ``maxSessions`` or ``maxTotalBytes``. + public func prune() { guard let contents = try? FileManager.default.contentsOfDirectory( at: directory, - includingPropertiesForKeys: [.contentModificationDateKey] + includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey] ) else { return } let snapshots = contents.filter { $0.lastPathComponent.hasSuffix(Self.suffix) } - guard snapshots.count > maxSessions else { return } - func modificationDate(_ url: URL) -> Date { - (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) - ?? .distantPast + guard !snapshots.isEmpty else { return } + struct Entry { + let url: URL + let modified: Date + let size: Int } - for stale in snapshots.sorted(by: { modificationDate($0) > modificationDate($1) }).dropFirst(maxSessions) { - try? FileManager.default.removeItem(at: stale) + let entries: [Entry] = snapshots.map { url in + let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey]) + return Entry( + url: url, + modified: values?.contentModificationDate ?? .distantPast, + size: values?.fileSize ?? 0 + ) + }.sorted { $0.modified > $1.modified } + + var keptCount = 0 + var keptBytes = 0 + for entry in entries { + let fitsCount = keptCount < maxSessions + let fitsBytes = keptBytes + entry.size <= maxTotalBytes + if fitsCount && fitsBytes { + keptCount += 1 + keptBytes += entry.size + } else { + try? FileManager.default.removeItem(at: entry.url) + } } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalInputHelpers.swift b/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalInputHelpers.swift new file mode 100644 index 00000000000..ac9d05735a4 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalInputHelpers.swift @@ -0,0 +1,119 @@ +import Foundation + +/// Sticky Ctrl / Alt modifier state shared by the touch quick-key bar and +/// raw keyboard input (`web/src/components/QuickKeys/QuickKeys.tsx` parity). +public struct TerminalModifierState: Equatable, Sendable { + public var ctrl: Bool + public var alt: Bool + + public init(ctrl: Bool = false, alt: Bool = false) { + self.ctrl = ctrl + self.alt = alt + } + + public var hasActiveModifier: Bool { ctrl || alt } +} + +/// Terminal special keys mapped to VT100/xterm escape sequences. +public enum TerminalSpecialKey: Equatable, Sendable { + case escape + case tab + case shiftTab + case enter + case backspace + case deleteForward + case arrowUp + case arrowDown + case arrowLeft + case arrowRight + case home + case end + case pageUp + case pageDown + + /// Wire byte sequence respecting `DECCKM` (application cursor keys mode). + public func sequence(applicationCursorKeys: Bool = false) -> String { + switch self { + case .escape: return "\u{1b}" + case .tab: return "\t" + case .shiftTab: return "\u{1b}[Z" + case .enter: return "\r" + case .backspace: return "\u{7f}" + case .deleteForward: return "\u{1b}[3~" + case .arrowUp: return applicationCursorKeys ? "\u{1b}OA" : "\u{1b}[A" + case .arrowDown: return applicationCursorKeys ? "\u{1b}OB" : "\u{1b}[B" + case .arrowRight: return applicationCursorKeys ? "\u{1b}OC" : "\u{1b}[C" + case .arrowLeft: return applicationCursorKeys ? "\u{1b}OD" : "\u{1b}[D" + case .home: return applicationCursorKeys ? "\u{1b}OH" : "\u{1b}[H" + case .end: return applicationCursorKeys ? "\u{1b}OF" : "\u{1b}[F" + case .pageUp: return "\u{1b}[5~" + case .pageDown: return "\u{1b}[6~" + } + } +} + +public enum TerminalInputEncoding { + /// Applies Ctrl/Alt modifiers to an input sequence, matching web's + /// `applyModifierState` plus standard control punctuation (`Ctrl+Space`, + /// `Ctrl+[`, `Ctrl+\`, `Ctrl+]`, `Ctrl+^`, `Ctrl+_`). + public static func applyModifiers(_ sequence: String, state: TerminalModifierState) -> String { + guard !sequence.isEmpty else { return sequence } + var result = sequence + + if state.ctrl, result.unicodeScalars.count == 1, let scalar = result.unicodeScalars.first { + if let ctrlByte = controlByte(for: scalar) { + result = String(UnicodeScalar(ctrlByte)) + } + } + if state.alt { + result = "\u{1b}\(result)" + } + return result + } + + /// Maps a single ASCII scalar pressed with Control to its C0 control byte. + public static func controlByte(for scalar: UnicodeScalar) -> UInt8? { + let v = scalar.value + if v == 0x20 || v == 0x40 { // Space or @ -> NUL + return 0x00 + } + if v >= 0x61 && v <= 0x7A { // a..z -> 1..26 + return UInt8(v - 0x60) + } + if v >= 0x41 && v <= 0x5F { // A..Z, [, \, ], ^, _ -> 1..31 + return UInt8(v - 0x40) + } + if v == 0x3F { // ? -> DEL + return 0x7F + } + return nil + } + + private static let pasteEnd = "\u{1b}[201~" + + /// Normalizes newlines to CR and optionally wraps in bracketed-paste markers + /// (`DECSET 2004`) while stripping embedded paste-end escapes for safety. + public static func encodePaste(_ text: String, bracketedPasteMode: Bool) -> String { + let normalized = text + .replacingOccurrences(of: "\r\n", with: "\r") + .replacingOccurrences(of: "\n", with: "\r") + guard bracketedPasteMode else { return normalized } + // Strip ESC[201~ inside untrusted pasted text so paste cannot prematurely + // break out of bracketed paste and execute shell commands. Repeat until + // none is left: one pass would let `ESC[20ESC[201~1~` rebuild the + // terminator from the pieces around the removed one. + var safe = normalized + while safe.contains(pasteEnd) { + safe = safe.replacingOccurrences(of: pasteEnd, with: "") + } + return "\u{1b}[200~\(safe)\(pasteEnd)" + } + + /// Formats a terminal text excerpt for pasting into the chat composer. + public static func formatExcerptForChat(_ selection: String) -> String { + let trimmed = selection.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return "" } + let fence = trimmed.contains("```") ? "~~~~" : "```" + return "\(fence)text\n\(trimmed)\n\(fence)" + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalSocketClient.swift b/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalSocketClient.swift new file mode 100644 index 00000000000..40157c0f080 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalSocketClient.swift @@ -0,0 +1,486 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +// MARK: - Wire payloads & public events + +public enum TerminalConnectionState: Equatable, Sendable { + case idle + case connecting + case connected + case error(String) +} + +public enum TerminalSocketEvent: Equatable, Sendable { + case stateChanged(TerminalConnectionState) + case shellReady(terminalId: String) + case shellOutput(terminalId: String, data: String) + case shellExit(terminalId: String, code: Int?, signal: String?) + case shellError(terminalId: String, message: String) + case agentOutput(sessionId: String, data: String) +} + +// MARK: - Injectable WebSocket transport seam (pure Foundation, Linux-safe) + +public protocol TerminalWebSocketConnection: Sendable { + func send(text: String) async throws + func receive() async throws -> String + func close() +} + +public protocol TerminalWebSocketTransport: Sendable { + func connect(url: URL) async throws -> any TerminalWebSocketConnection +} + +#if !os(Linux) +/// Production WebSocket transport over `URLSessionWebSocketTask`. +public final class URLSessionTerminalWebSocketTransport: TerminalWebSocketTransport, @unchecked Sendable { + private let session: URLSession + + public init(session: URLSession? = nil) { + if let session { + self.session = session + } else { + let config = URLSessionConfiguration.default + config.waitsForConnectivity = false + self.session = URLSession(configuration: config) + } + } + + public func connect(url: URL) async throws -> any TerminalWebSocketConnection { + var request = URLRequest(url: url) + request.timeoutInterval = 20 + let task = session.webSocketTask(with: request) + // Allow large bursty terminal repaints (TUI redraws / scrollback replays up to 4 MiB). + task.maximumMessageSize = 4 * 1024 * 1024 + task.resume() + return URLSessionTerminalWebSocketConnection(task: task) + } +} + +private final class URLSessionTerminalWebSocketConnection: TerminalWebSocketConnection, @unchecked Sendable { + private let task: URLSessionWebSocketTask + + init(task: URLSessionWebSocketTask) { + self.task = task + } + + func send(text: String) async throws { + try await task.send(.string(text)) + } + + func receive() async throws -> String { + while true { + let message = try await task.receive() + switch message { + case .string(let text): + return text + case .data(let data): + if let text = String(data: data, encoding: .utf8) { + return text + } + @unknown default: + continue + } + } + } + + func close() { + task.cancel(with: .normalClosure, reason: nil) + } +} +#endif + +// MARK: - TerminalSocketClient + +/// Engine.IO v4 / Socket.IO v4 client for Hub's `/terminal` namespace. +/// +/// Supports both interactive user shell terminals (`terminal:*`) and live agent +/// PTY streams (`agent-terminal:*`), with automatic JWT refresh on auth errors, +/// Engine.IO ping/pong heartbeats, and bounded reconnect backoff. +public actor TerminalSocketClient { + public struct Configuration: Sendable { + public var baseURL: URL + /// Returns a JWT (or nil if unavailable). `rejectedToken` is the token + /// the hub just refused with an auth `connect_error`: the provider must + /// refresh past it rather than hand back the same cached token. + public var tokenProvider: @Sendable (_ rejectedToken: String?) async -> String? + public var reconnectInitialDelayMs: Int + public var reconnectMaxDelayMs: Int + + public init( + baseURL: URL, + tokenProvider: @escaping @Sendable (_ rejectedToken: String?) async -> String?, + reconnectInitialDelayMs: Int = 1_000, + reconnectMaxDelayMs: Int = 5_000 + ) { + self.baseURL = baseURL + self.tokenProvider = tokenProvider + self.reconnectInitialDelayMs = reconnectInitialDelayMs + self.reconnectMaxDelayMs = reconnectMaxDelayMs + } + } + + private let configuration: Configuration + private let transport: any TerminalWebSocketTransport + + private var connection: (any TerminalWebSocketConnection)? + private var runTask: Task? + private var watchdogTask: Task? + private var continuation: AsyncStream.Continuation? + private var namespaceConnected = false + private var stopped = false + private var currentState: TerminalConnectionState = .idle + private var pendingOutbound: [String] = [] + + public init(configuration: Configuration, transport: any TerminalWebSocketTransport) { + self.configuration = configuration + self.transport = transport + } + + #if !os(Linux) + public init(configuration: Configuration) { + self.configuration = configuration + self.transport = URLSessionTerminalWebSocketTransport() + } + #endif + + /// Starts the connection loop and returns an event stream. Calling `start()` + /// again tears down any previous connection first. + public func start() -> AsyncStream { + stopInternal(emitIdle: false) + stopped = false + let (stream, continuation) = AsyncStream.makeStream() + self.continuation = continuation + runTask = Task { [weak self] in + await self?.runLoop() + } + return stream + } + + /// Gracefully disconnects from `/terminal` and closes the event stream. + public func stop() { + stopInternal(emitIdle: true) + } + + private func stopInternal(emitIdle: Bool) { + stopped = true + namespaceConnected = false + pendingOutbound.removeAll() + watchdogTask?.cancel() + watchdogTask = nil + runTask?.cancel() + runTask = nil + if let conn = connection { + connection = nil + Task { + try? await conn.send(text: TerminalSocketCodec.disconnectFrame) + conn.close() + } + } + if emitIdle { + emitState(.idle) + } + continuation?.finish() + continuation = nil + } + + // MARK: - Shell Terminal commands (`terminal:*`) + + public func createShell(sessionId: String, terminalId: String, cols: Int, rows: Int) async { + struct Payload: Encodable { + let sessionId: String + let terminalId: String + let cols: Int + let rows: Int + } + await emitEvent( + "terminal:create", + payload: Payload(sessionId: sessionId, terminalId: terminalId, cols: cols, rows: rows) + ) + } + + public func writeShell(terminalId: String, data: String) async { + struct Payload: Encodable { + let terminalId: String + let data: String + } + await emitEvent("terminal:write", payload: Payload(terminalId: terminalId, data: data)) + } + + public func resizeShell(terminalId: String, cols: Int, rows: Int) async { + struct Payload: Encodable { + let terminalId: String + let cols: Int + let rows: Int + } + await emitEvent("terminal:resize", payload: Payload(terminalId: terminalId, cols: cols, rows: rows)) + } + + public func closeShell(terminalId: String) async { + struct Payload: Encodable { + let terminalId: String + } + await emitEvent("terminal:close", payload: Payload(terminalId: terminalId)) + } + + // MARK: - Agent Terminal commands (`agent-terminal:*`) + + public func subscribeAgent(sessionId: String) async { + struct Payload: Encodable { let sessionId: String } + await emitEvent("agent-terminal:subscribe", payload: Payload(sessionId: sessionId)) + } + + public func unsubscribeAgent(sessionId: String) async { + struct Payload: Encodable { let sessionId: String } + await emitEvent("agent-terminal:unsubscribe", payload: Payload(sessionId: sessionId)) + } + + public func resizeAgent(sessionId: String, cols: Int, rows: Int) async { + struct Payload: Encodable { + let sessionId: String + let cols: Int + let rows: Int + } + await emitEvent("agent-terminal:resize", payload: Payload(sessionId: sessionId, cols: cols, rows: rows)) + } + + public func sendAgentInput(sessionId: String, data: String) async { + guard !data.isEmpty else { return } + struct Payload: Encodable { + let sessionId: String + let data: String + } + await emitEvent("agent-terminal:input", payload: Payload(sessionId: sessionId, data: data)) + } + + private func emitEvent(_ event: String, payload: P) async { + guard let frame = try? TerminalSocketCodec.encodeEvent(event, payload: payload) else { return } + if namespaceConnected, let conn = connection { + do { + try await conn.send(text: frame) + } catch { + // The receive loop owns disconnect/reconnect transitions. + } + } else { + // Buffer commands issued right around connect so initial create/subscribe + // does not race the namespace handshake. + if pendingOutbound.count >= 64 { + pendingOutbound.removeFirst() + } + pendingOutbound.append(frame) + } + } + + // MARK: - Connection loop + + private func runLoop() async { + guard let wsURL = TerminalSocketCodec.webSocketURL(from: configuration.baseURL) else { + emitState(.error("Invalid hub URL")) + return + } + + var attempt = 0 + var rejectedToken: String? + + while !stopped && !Task.isCancelled { + emitState(.connecting) + + guard let token = await configuration.tokenProvider(rejectedToken), !token.isEmpty else { + emitState(.error("Missing terminal credentials.")) + attempt += 1 + await sleepBackoff(attempt: attempt) + continue + } + let usedForceRefresh = rejectedToken != nil + rejectedToken = nil + + let conn: any TerminalWebSocketConnection + do { + conn = try await transport.connect(url: wsURL) + } catch { + if stopped || Task.isCancelled { break } + emitState(.error(error.localizedDescription)) + attempt += 1 + await sleepBackoff(attempt: attempt) + continue + } + + if stopped || Task.isCancelled { + conn.close() + break + } + connection = conn + namespaceConnected = false + + var authRejected = false + var pingDeadlineMs = 45_000 + var didConnectSuccessfully = false + + receiveLoop: while !stopped && !Task.isCancelled { + let raw: String + do { + raw = try await conn.receive() + } catch { + if !stopped && !Task.isCancelled { + emitState(.error("Disconnected")) + } + break receiveLoop + } + + let frame = TerminalSocketCodec.decode(raw) + switch frame { + case .engineOpen(let open): + pingDeadlineMs = max(10_000, open.pingIntervalMs + open.pingTimeoutMs + 5_000) + armWatchdog(timeoutMs: pingDeadlineMs, connection: conn) + do { + let connectFrame = try TerminalSocketCodec.encodeConnect(token: token) + try await conn.send(text: connectFrame) + } catch { + break receiveLoop + } + + case .enginePing: + armWatchdog(timeoutMs: pingDeadlineMs, connection: conn) + try? await conn.send(text: TerminalSocketCodec.pongFrame) + + case .engineClose: + break receiveLoop + + case .enginePong, .engineNoop, .ignored: + break + + case .namespaceConnected: + namespaceConnected = true + didConnectSuccessfully = true + attempt = 0 + emitState(.connected) + await flushPendingOutbound(on: conn) + + case .namespaceDisconnected: + namespaceConnected = false + break receiveLoop + + case .namespaceConnectError(let message): + namespaceConnected = false + if !usedForceRefresh && Self.looksLikeAuthFailure(message) { + authRejected = true + rejectedToken = token + } else { + emitState(.error(message)) + } + break receiveLoop + + case .event(let name, let payloadJSON): + handleServerEvent(name: name, payloadJSON: payloadJSON) + } + } + + watchdogTask?.cancel() + watchdogTask = nil + namespaceConnected = false + if connection != nil { + connection = nil + conn.close() + } + + if stopped || Task.isCancelled { break } + if authRejected { + // Retry immediately once with a freshly refreshed JWT. + continue + } + if didConnectSuccessfully { + attempt = 1 + } else { + attempt += 1 + } + await sleepBackoff(attempt: attempt) + } + } + + private func flushPendingOutbound(on conn: any TerminalWebSocketConnection) async { + guard !pendingOutbound.isEmpty else { return } + let queued = pendingOutbound + pendingOutbound.removeAll() + for frame in queued { + try? await conn.send(text: frame) + } + } + + private func armWatchdog(timeoutMs: Int, connection conn: any TerminalWebSocketConnection) { + watchdogTask?.cancel() + watchdogTask = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(timeoutMs)) + guard !Task.isCancelled else { return } + await self?.handleWatchdogTimeout(connection: conn) + } + } + + private func handleWatchdogTimeout(connection conn: any TerminalWebSocketConnection) { + guard !stopped else { return } + conn.close() + } + + private func sleepBackoff(attempt: Int) async { + let base = max(50, configuration.reconnectInitialDelayMs) + let cap = max(base, configuration.reconnectMaxDelayMs) + let shift = min(max(0, attempt - 1), 6) + let delay = min(cap, base * (1 << shift)) + try? await Task.sleep(for: .milliseconds(delay)) + } + + private func emitState(_ next: TerminalConnectionState) { + guard next != currentState else { return } + currentState = next + continuation?.yield(.stateChanged(next)) + } + + private static func looksLikeAuthFailure(_ message: String) -> Bool { + let lower = message.lowercased() + return lower.contains("token") || lower.contains("auth") || lower.contains("unauthorized") + } + + private func handleServerEvent(name: String, payloadJSON: Data) { + let decoder = JSONDecoder() + switch name { + case "terminal:ready": + struct ReadyPayload: Decodable { let terminalId: String } + if let p = try? decoder.decode(ReadyPayload.self, from: payloadJSON) { + continuation?.yield(.shellReady(terminalId: p.terminalId)) + } + + case "terminal:output": + struct OutputPayload: Decodable { let terminalId: String; let data: String } + if let p = try? decoder.decode(OutputPayload.self, from: payloadJSON) { + continuation?.yield(.shellOutput(terminalId: p.terminalId, data: p.data)) + } + + case "terminal:exit": + struct ExitPayload: Decodable { let terminalId: String; let code: Int?; let signal: String? } + if let p = try? decoder.decode(ExitPayload.self, from: payloadJSON) { + continuation?.yield(.shellExit(terminalId: p.terminalId, code: p.code, signal: p.signal)) + } + + case "terminal:error": + struct ErrorPayload: Decodable { let terminalId: String; let message: String } + if let p = try? decoder.decode(ErrorPayload.self, from: payloadJSON) { + continuation?.yield(.shellError(terminalId: p.terminalId, message: p.message)) + } + + case "agent-terminal:output": + struct AgentOutputPayload: Decodable { + let sessionId: String? + let terminalId: String? + let data: String + } + if let p = try? decoder.decode(AgentOutputPayload.self, from: payloadJSON) { + if let terminalId = p.terminalId, terminalId != "agent" { return } + continuation?.yield(.agentOutput(sessionId: p.sessionId ?? "", data: p.data)) + } + + default: + break + } + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalSocketCodec.swift b/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalSocketCodec.swift new file mode 100644 index 00000000000..e10df684d3b --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Terminal/TerminalSocketCodec.swift @@ -0,0 +1,214 @@ +import Foundation + +/// Engine.IO v4 + Socket.IO v4 `/terminal` text-frame codec. +/// +/// Mirrors `socket.io-parser@4.2.4` and `@socket.io/bun-engine` so `HapiClient` +/// talks directly to Hub's `/terminal` namespace over `URLSessionWebSocketTask` +/// (`ws(s):///socket.io/?EIO=4&transport=websocket`) with zero external +/// dependencies. +public enum TerminalSocketCodec { + public static let namespace = "/terminal" + + /// Builds `ws(s):///socket.io/?EIO=4&transport=websocket` from an HTTP(S) hub origin. + public static func webSocketURL(from baseURL: URL) -> URL? { + guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false), + let scheme = components.scheme?.lowercased() else { + return nil + } + switch scheme { + case "https", "wss": + components.scheme = "wss" + case "http", "ws": + components.scheme = "ws" + default: + return nil + } + components.path = "/socket.io/" + components.queryItems = [ + URLQueryItem(name: "EIO", value: "4"), + URLQueryItem(name: "transport", value: "websocket"), + ] + components.fragment = nil + return components.url + } + + // MARK: - Outbound frames + + /// Engine.IO pong (`3`). + public static let pongFrame = "3" + + /// Socket.IO CONNECT to `/terminal` with `{ "token": "" }`. + public static func encodeConnect(token: String) throws -> String { + let payload = try encodeJSON(["token": token]) + return "40\(namespace),\(payload)" + } + + /// Socket.IO DISCONNECT from `/terminal`. + public static let disconnectFrame = "41\(namespace)," + + /// Socket.IO EVENT on `/terminal`: `42/terminal,["",]`. + public static func encodeEvent(_ event: String, payload: Payload) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let payloadData = try encoder.encode(payload) + let eventData = try encoder.encode(event) + guard let eventJSON = String(data: eventData, encoding: .utf8), + let payloadJSON = String(data: payloadData, encoding: .utf8) else { + throw TerminalSocketCodecError.encodingFailed + } + return "42\(namespace),[\(eventJSON),\(payloadJSON)]" + } + + private static func encodeJSON(_ value: T) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let data = try encoder.encode(value) + guard let text = String(data: data, encoding: .utf8) else { + throw TerminalSocketCodecError.encodingFailed + } + return text + } + + // MARK: - Inbound frames + + public struct EngineOpenPayload: Equatable, Sendable { + public var sid: String + public var pingIntervalMs: Int + public var pingTimeoutMs: Int + + public init(sid: String, pingIntervalMs: Int = 25_000, pingTimeoutMs: Int = 20_000) { + self.sid = sid + self.pingIntervalMs = pingIntervalMs + self.pingTimeoutMs = pingTimeoutMs + } + } + + public enum InboundFrame: Equatable, Sendable { + case engineOpen(EngineOpenPayload) + case engineClose + case enginePing + case enginePong + case engineNoop + case namespaceConnected(sid: String?) + case namespaceDisconnected + case namespaceConnectError(message: String) + case event(name: String, payloadJSON: Data) + case ignored + } + + /// Decodes a single Engine.IO v4 text WebSocket frame. + public static func decode(_ raw: String) -> InboundFrame { + guard let first = raw.first else { return .ignored } + let body = raw.dropFirst() + switch first { + case "0": + return decodeEngineOpen(body) + case "1": + return .engineClose + case "2": + return .enginePing + case "3": + return .enginePong + case "4": + return decodeSocketIO(body) + case "6": + return .engineNoop + default: + return .ignored + } + } + + private static func decodeEngineOpen(_ body: Substring) -> InboundFrame { + guard let data = body.data(using: .utf8), + let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let sid = obj["sid"] as? String else { + return .ignored + } + let pingInterval = (obj["pingInterval"] as? NSNumber)?.intValue ?? 25_000 + let pingTimeout = (obj["pingTimeout"] as? NSNumber)?.intValue ?? 20_000 + return .engineOpen(EngineOpenPayload( + sid: sid, + pingIntervalMs: pingInterval, + pingTimeoutMs: pingTimeout + )) + } + + private static func decodeSocketIO(_ raw: Substring) -> InboundFrame { + guard let typeChar = raw.first else { return .ignored } + var rest = raw.dropFirst() + + // Binary packet attachment count (`-`), unused by /terminal but skipped safely. + if typeChar == "5" || typeChar == "6" { + guard let dash = rest.firstIndex(of: "-") else { return .ignored } + rest = rest[rest.index(after: dash)...] + } + + // Namespace prefix (`/terminal,`). + let nsp: Substring + if rest.first == "/" { + if let comma = rest.firstIndex(of: ",") { + nsp = rest[..= "0", ch <= "9" { + rest = rest.dropFirst() + } + + switch typeChar { + case "0": // CONNECT + let sid: String? + if let data = rest.data(using: .utf8), + let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { + sid = obj["sid"] as? String + } else { + sid = nil + } + return .namespaceConnected(sid: sid) + + case "1": // DISCONNECT + return .namespaceDisconnected + + case "4": // CONNECT_ERROR + var message = "Connection rejected" + if let data = rest.data(using: .utf8), + let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let msg = obj["message"] as? String, !msg.isEmpty { + message = msg + } + return .namespaceConnectError(message: message) + + case "2": // EVENT: ["event-name", {...}] + guard let data = rest.data(using: .utf8), + let array = try? JSONSerialization.jsonObject(with: data) as? [Any], + let name = array.first as? String else { + return .ignored + } + let payloadObject: Any = array.count > 1 ? array[1] : [String: Any]() + guard JSONSerialization.isValidJSONObject(payloadObject), + let payloadData = try? JSONSerialization.data(withJSONObject: payloadObject) else { + return .ignored + } + return .event(name: name, payloadJSON: payloadData) + + default: + return .ignored + } + } +} + +public enum TerminalSocketCodecError: Error, Equatable, Sendable { + case encodingFailed +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Voice/DictationController.swift b/ios/Packages/HapiKit/Sources/HapiClient/Voice/DictationController.swift index 84c7e5f74ca..458694288c2 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Voice/DictationController.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Voice/DictationController.swift @@ -49,6 +49,29 @@ public protocol DictationRecorder: AnyObject { /// Abandon the take, discarding any captured data. func cancel() + + /// Normalized live microphone input level in `0...1` while recording. + func currentAudioLevel() -> Float + + /// Register a callback fired when the system interrupts recording (call, + /// alarm, Siri, audio route hijack). + func setInterruptionHandler(_ handler: (@MainActor () -> Void)?) +} + +public extension DictationRecorder { + func currentAudioLevel() -> Float { 0 } + func setInterruptionHandler(_ handler: (@MainActor () -> Void)?) {} +} + +/// Failed transcription metadata kept so the user can retry without re-recording. +public struct FailedDictationTake: Equatable, Sendable { + public let message: String + public let autoSend: Bool + + public init(message: String, autoSend: Bool) { + self.message = message + self.autoSend = autoSend + } } /// The mic button / recording chip state machine. @@ -71,6 +94,9 @@ public enum DictationEvent: Equatable, Sendable { /// Final transcript — append to the composer via ``appendTranscript(_:transcript:)``. case transcribed(String) + /// Final transcript requested with immediate send (voice-to-send flow). + case transcribedAndSend(String) + /// The hub has no transcription provider configured. case noProvider @@ -84,7 +110,9 @@ public enum DictationEvent: Equatable, Sendable { /// ``toggle()`` reuses it (or discovers one) and starts the recorder; the second /// stops it and posts the audio to /// `POST /api/voice/transcription`, emitting ``DictationEvent/transcribed(_:)`` +/// (or ``DictationEvent/transcribedAndSend(_:)`` via ``stopAndSend()``) /// with the hub's text. ``cancel()`` abandons the take without uploading. +/// Failed uploads retain the recorded audio in memory for ``retryFailedTranscription()``. /// /// Web reference: `useDictation.ts` (standard mode; the realtime path is out /// of scope for v1). No language override yet — the hub auto-detects; a @@ -95,8 +123,26 @@ public enum DictationEvent: Equatable, Sendable { /// as `ChatInteractor.onEvent`). @MainActor @Observable public final class DictationController { + private struct RetainedAudio { + let audio: Data + let filename: String + let mimeType: String + let provider: String + let autoSend: Bool + } + public private(set) var state: DictationState = .idle + /// Live normalized input level (`0...1`) while recording. + public private(set) var audioLevel: Float = 0 + + /// Rolling window of recent input levels (`0...1`) for waveform bars. + public private(set) var audioLevels: [Float] = Array(repeating: 0, count: 16) + + /// Present after a transcription upload fails while the captured audio is + /// retained in memory for one-tap retry. + public private(set) var failedTake: FailedDictationTake? + /// Hidden until the hub confirms a standard-capable provider. public var isAvailable: Bool { cachedProviderId != nil } @@ -109,6 +155,8 @@ public final class DictationController { /// Reused across takes; refreshed when the composer appears. private var cachedProviderId: String? + @ObservationIgnored private var retainedAudio: RetainedAudio? + @ObservationIgnored private var meteringTask: Task? @ObservationIgnored private var operationRunning = false public init( @@ -119,6 +167,9 @@ public final class DictationController { self.api = api self.recorder = recorder self.now = now + self.recorder.setInterruptionHandler { [weak self] in + self?.handleRecordingInterrupted() + } } /// Silent preflight; no microphone access or notices on chat entry. @@ -132,29 +183,94 @@ public final class DictationController { cachedProviderId = provider } - /// Mic button press: Idle → record, Recording → stop + transcribe. + /// Mic button press: Idle → record, Recording → stop + transcribe into composer. public func toggle() { switch state { case .idle: startRecording() case .recording: - stopAndTranscribe() + stopAndInsert() case .starting, .transcribing: // An operation is already in flight. break } } + /// Finish recording and insert the transcript into the composer for review/editing. + public func stopAndInsert() { + guard case .recording = state else { return } + stopAndTranscribe(autoSend: false) + } + + /// Finish recording, transcribe, and immediately send the prompt. + public func stopAndSend() { + guard case .recording = state else { return } + stopAndTranscribe(autoSend: true) + } + /// Recording chip ✕: discard the take (no upload). public func cancel() { guard case .recording = state else { return } + stopMetering() recorder.cancel() state = .idle } + /// Re-upload the retained failed audio take without re-recording. + public func retryFailedTranscription() { + guard state == .idle, !operationRunning, let retained = retainedAudio else { return } + operationRunning = true + failedTake = nil + state = .transcribing + Task { [weak self] in + guard let self else { return } + defer { self.operationRunning = false } + await self.upload(retained) + } + } + + /// Drop any retained failed audio take. + public func discardFailedTranscription() { + retainedAudio = nil + failedTake = nil + } + + private func handleRecordingInterrupted() { + guard case .recording = state else { return } + stopMetering() + state = .idle + emit(.error("Recording interrupted")) + } + + private func startMetering() { + meteringTask?.cancel() + audioLevel = 0 + audioLevels = Array(repeating: 0, count: 16) + meteringTask = Task { [weak self] in + while !Task.isCancelled { + guard let self, case .recording = self.state else { return } + let level = min(max(self.recorder.currentAudioLevel(), 0), 1) + self.audioLevel = level + var next = self.audioLevels + if !next.isEmpty { next.removeFirst() } + next.append(level) + self.audioLevels = next + try? await Task.sleep(for: .milliseconds(75)) + } + } + } + + private func stopMetering() { + meteringTask?.cancel() + meteringTask = nil + audioLevel = 0 + audioLevels = Array(repeating: 0, count: 16) + } + private func startRecording() { guard !operationRunning else { return } operationRunning = true + discardFailedTranscription() state = .starting Task { [weak self] in guard let self else { return } @@ -167,6 +283,7 @@ public final class DictationController { do { try self.recorder.start() self.state = .recording(startedAtMs: self.now()) + self.startMetering() } catch { self.emit(.error(Self.errorMessage(error, fallback: "Could not start recording"))) self.state = .idle @@ -199,10 +316,11 @@ public final class DictationController { return chosen.id } - private func stopAndTranscribe() { + private func stopAndTranscribe(autoSend: Bool) { guard let provider = cachedProviderId else { return } // unreachable: set before Recording guard !operationRunning else { return } operationRunning = true + stopMetering() state = .transcribing Task { [weak self] in guard let self else { return } @@ -220,19 +338,35 @@ public final class DictationController { self.state = .idle return } - defer { self.state = .idle } - do { - let result = try await self.api.transcribe( - audio: audio, - filename: self.recorder.filename, - mimeType: self.recorder.mimeType, - provider: provider, - language: nil - ) - self.emit(.transcribed(result.text)) - } catch { - self.emit(.error(Self.errorMessage(error, fallback: "Transcription failed"))) - } + let take = RetainedAudio( + audio: audio, + filename: self.recorder.filename, + mimeType: self.recorder.mimeType, + provider: provider, + autoSend: autoSend + ) + await self.upload(take) + } + } + + private func upload(_ take: RetainedAudio) async { + defer { self.state = .idle } + do { + let result = try await self.api.transcribe( + audio: take.audio, + filename: take.filename, + mimeType: take.mimeType, + provider: take.provider, + language: nil + ) + self.retainedAudio = nil + self.failedTake = nil + self.emit(take.autoSend ? .transcribedAndSend(result.text) : .transcribed(result.text)) + } catch { + let message = Self.errorMessage(error, fallback: "Transcription failed") + self.retainedAudio = take + self.failedTake = FailedDictationTake(message: message, autoSend: take.autoSend) + self.emit(.error(message)) } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiRequests.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiRequests.swift index 50b4b541b23..39e459a1bde 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiRequests.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiRequests.swift @@ -171,6 +171,8 @@ public struct SpawnRequest: Codable, Equatable, Sendable { public var collaborationMode: CodexCollaborationMode? public var copilotAgentMode: CopilotAgentMode? public var startingMode: SpawnStartingMode? + /// Session that asked for this spawn (`spawn_peer`); hub derives `groupLeaderId`. + public var parentSessionId: String? public init( directory: String, @@ -185,7 +187,8 @@ public struct SpawnRequest: Codable, Equatable, Sendable { serviceTier: ServiceTier? = nil, collaborationMode: CodexCollaborationMode? = nil, copilotAgentMode: CopilotAgentMode? = nil, - startingMode: SpawnStartingMode? = nil + startingMode: SpawnStartingMode? = nil, + parentSessionId: String? = nil ) { self.directory = directory self.agent = agent @@ -200,6 +203,7 @@ public struct SpawnRequest: Codable, Equatable, Sendable { self.collaborationMode = collaborationMode self.copilotAgentMode = copilotAgentMode self.startingMode = startingMode + self.parentSessionId = parentSessionId } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift index f8b9738571c..fe54fd7ae19 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/ApiResponses.swift @@ -50,15 +50,67 @@ public struct HubCapabilities: Codable, Equatable, Sendable { public struct HubHealthResponse: Codable, Equatable, Sendable { public var status: String public var protocolVersion: Int + /// Stable UUID identifying this hub across restarts, used for O(1) push routing. + /// Absent on older hubs. + public var hubId: String? public var capabilities: HubCapabilities? - public init(status: String, protocolVersion: Int, capabilities: HubCapabilities? = nil) { + public init( + status: String, + protocolVersion: Int, + hubId: String? = nil, + capabilities: HubCapabilities? = nil + ) { self.status = status self.protocolVersion = protocolVersion + self.hubId = hubId self.capabilities = capabilities } } +/// Per-device native push event filter sent with `POST /api/devices/register`. +/// Every category defaults to enabled (`true`). +public struct PushNotificationPreferences: Codable, Equatable, Hashable, Sendable { + public var ready: Bool + public var permissionRequest: Bool + public var inputRequest: Bool + public var modelError: Bool + + public static let allEnabled = PushNotificationPreferences() + + public init( + ready: Bool = true, + permissionRequest: Bool = true, + inputRequest: Bool = true, + modelError: Bool = true + ) { + self.ready = ready + self.permissionRequest = permissionRequest + self.inputRequest = inputRequest + self.modelError = modelError + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.ready = try container.decodeIfPresent(Bool.self, forKey: .ready) ?? true + self.permissionRequest = try container.decodeIfPresent(Bool.self, forKey: .permissionRequest) ?? true + self.inputRequest = try container.decodeIfPresent(Bool.self, forKey: .inputRequest) ?? true + self.modelError = try container.decodeIfPresent(Bool.self, forKey: .modelError) ?? true + } +} + +/// Response of `POST /api/devices/register`. +public struct DeviceRegisterResponse: Codable, Equatable, Sendable { + public var ok: Bool + /// Stable UUID of the hub that accepted the registration, when advertised. + public var hubId: String? + + public init(ok: Bool = true, hubId: String? = nil) { + self.ok = ok + self.hubId = hubId + } +} + /// `inputTranslation` of `GET /api/features`. public struct InputTranslationFeature: Codable, Equatable, Sendable { public var available: Bool diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AttachedJob.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AttachedJob.swift index b0145c18cff..134488b5dc8 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AttachedJob.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/AttachedJob.swift @@ -26,6 +26,8 @@ public struct AttachedJob: Codable, Equatable, Sendable { public var unit: String? public var detail: String? public var heartbeatAt: Int + /// Freshest heartbeat across all running jobs attached to the session. + public var latestRunningHeartbeatAt: Int? public var startedAt: Int public var updatedAt: Int @@ -39,6 +41,7 @@ public struct AttachedJob: Codable, Equatable, Sendable { unit: String? = nil, detail: String? = nil, heartbeatAt: Int, + latestRunningHeartbeatAt: Int? = nil, startedAt: Int, updatedAt: Int ) { @@ -51,6 +54,7 @@ public struct AttachedJob: Codable, Equatable, Sendable { self.unit = unit self.detail = detail self.heartbeatAt = heartbeatAt + self.latestRunningHeartbeatAt = latestRunningHeartbeatAt self.startedAt = startedAt self.updatedAt = updatedAt } @@ -61,6 +65,8 @@ public struct AttachedJob: Codable, Equatable, Sendable { public var isRunning: Bool { status == .running } + public var effectiveHeartbeatAt: Int { latestRunningHeartbeatAt ?? heartbeatAt } + public func isStale(nowMs: Int) -> Bool { nowMs - heartbeatAt > Self.staleAfterMs } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/LocalSessionImportApi.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/LocalSessionImportApi.swift new file mode 100644 index 00000000000..63e34864616 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/LocalSessionImportApi.swift @@ -0,0 +1,183 @@ +import Foundation + +/// CLI history sources exposed by the Hub's local-session import endpoints. +public enum LocalSessionSource: String, CaseIterable, Identifiable, Codable, Sendable { + case claude + case codex + case cursor + case opencode + case pi + + public var id: String { rawValue } + + /// REST route prefix under `/api` (e.g. `claude` → `/api/claude/sessions`). + public var routeBase: String { rawValue } + + public var displayName: String { + switch self { + case .claude: "Claude" + case .codex: "Codex" + case .cursor: "Cursor" + case .opencode: "OpenCode" + case .pi: "Pi" + } + } + + /// Codex uses `/api/codex/sync-session`; all other sources use + /// `/api//import-sessions`. + public var importPath: String { + switch self { + case .codex: "/api/codex/sync-session" + default: "/api/\(routeBase)/import-sessions" + } + } + + public var listPath: String { + "/api/\(routeBase)/sessions" + } +} + +/// Summary row returned by `GET /api//sessions`. +public struct LocalSessionSummaryItem: Codable, Equatable, Identifiable, Sendable { + public let id: String + public let title: String + public let lastUserMessage: String? + public let cwd: String? + public let modifiedAt: Double + public let messageCount: Int? + public let hapiSessionId: String? + public let model: String? + + public init( + id: String, + title: String, + lastUserMessage: String? = nil, + cwd: String? = nil, + modifiedAt: Double, + messageCount: Int? = nil, + hapiSessionId: String? = nil, + model: String? = nil + ) { + self.id = id + self.title = title + self.lastUserMessage = lastUserMessage + self.cwd = cwd + self.modifiedAt = modifiedAt + self.messageCount = messageCount + self.hapiSessionId = hapiSessionId + self.model = model + } + + public var modifiedDate: Date { + let seconds = modifiedAt > 10_000_000_000 ? modifiedAt / 1_000.0 : modifiedAt + return Date(timeIntervalSince1970: seconds) + } + + public var displayTitle: String { + let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { return trimmed } + if let msg = lastUserMessage?.trimmingCharacters(in: .whitespacesAndNewlines), !msg.isEmpty { + return msg + } + return String(id.prefix(12)) + } + + public var directoryName: String? { + guard let cwd, !cwd.isEmpty else { return nil } + return cwd.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) ?? cwd + } +} + +/// Response body of `GET /api//sessions`. +public struct LocalSessionsListResponse: Codable, Equatable, Sendable { + public let success: Bool + public let sessions: [LocalSessionSummaryItem]? + public let machineId: String? + public let error: String? + + public init( + success: Bool, + sessions: [LocalSessionSummaryItem]? = nil, + machineId: String? = nil, + error: String? = nil + ) { + self.success = success + self.sessions = sessions + self.machineId = machineId + self.error = error + } +} + +/// Per-session item inside `POST /api//import-sessions`. +public struct LocalSessionImportItemResult: Codable, Equatable, Sendable { + public struct ErrorDetail: Codable, Equatable, Sendable { + public let code: String? + public let message: String + + public init(code: String? = nil, message: String) { + self.code = code + self.message = message + } + } + + public let sessionId: String? + public let hapiSessionId: String? + public let action: String? + public let appended: Int? + public let error: ErrorDetail? + + public init( + sessionId: String? = nil, + hapiSessionId: String? = nil, + action: String? = nil, + appended: Int? = nil, + error: ErrorDetail? = nil + ) { + self.sessionId = sessionId + self.hapiSessionId = hapiSessionId + self.action = action + self.appended = appended + self.error = error + } +} + +/// Unified response covering both `/api//import-sessions` (`results`) +/// and `/api/codex/sync-session` (`hapiSessionIds`). +public struct LocalSessionImportResponse: Codable, Equatable, Sendable { + public let success: Bool + public let results: [LocalSessionImportItemResult]? + public let hapiSessionIds: [String]? + public let message: String? + public let error: String? + public let machineId: String? + + public init( + success: Bool, + results: [LocalSessionImportItemResult]? = nil, + hapiSessionIds: [String]? = nil, + message: String? = nil, + error: String? = nil, + machineId: String? = nil + ) { + self.success = success + self.results = results + self.hapiSessionIds = hapiSessionIds + self.message = message + self.error = error + self.machineId = machineId + } + + /// First imported HAPI session ID across either wire shape. + public var firstImportedSessionId: String? { + if let id = results?.compactMap(\.hapiSessionId).first(where: { !$0.isEmpty }) { + return id + } + return hapiSessionIds?.first(where: { !$0.isEmpty }) + } + + /// First actionable error message across either wire shape. + public var firstErrorMessage: String? { + if let error, !error.isEmpty { return error } + return results?.compactMap { $0.error?.message }.first(where: { !$0.isEmpty }) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/Session.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/Session.swift index b12a425be86..ad7d3412653 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/Session.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/Session.swift @@ -31,6 +31,7 @@ public struct Session: Codable, Equatable, Sendable { public var thinkingAt: Int public var activeTurnStartedAt: Int? public var backgroundTaskCount: Int? + public var derivedToolWork: Bool? public var todos: [TodoItem]? /// Team-mode state, kept wire-verbatim (no v1 UI consumes its internals). public var teamState: JSONValue? @@ -68,6 +69,7 @@ public struct Session: Codable, Equatable, Sendable { thinkingAt: Int, activeTurnStartedAt: Int? = nil, backgroundTaskCount: Int? = nil, + derivedToolWork: Bool? = nil, todos: [TodoItem]? = nil, teamState: JSONValue? = nil, todosUpdatedAt: Int? = nil, @@ -101,6 +103,7 @@ public struct Session: Codable, Equatable, Sendable { self.thinkingAt = thinkingAt self.activeTurnStartedAt = activeTurnStartedAt self.backgroundTaskCount = backgroundTaskCount + self.derivedToolWork = derivedToolWork self.todos = todos self.teamState = teamState self.todosUpdatedAt = todosUpdatedAt @@ -138,6 +141,7 @@ public struct Session: Codable, Equatable, Sendable { thinkingAt = try container.decode(Int.self, forKey: .thinkingAt) activeTurnStartedAt = try container.decodeIfPresent(Int.self, forKey: .activeTurnStartedAt) backgroundTaskCount = try container.decodeIfPresent(Int.self, forKey: .backgroundTaskCount) + derivedToolWork = try container.decodeIfPresent(Bool.self, forKey: .derivedToolWork) todos = try container.decodeIfPresent([TodoItem].self, forKey: .todos) teamState = try container.decodeIfPresent(JSONValue.self, forKey: .teamState) todosUpdatedAt = try container.decodeIfPresent(Int.self, forKey: .todosUpdatedAt) diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionExtrasApi.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionExtrasApi.swift new file mode 100644 index 00000000000..22c613488dc --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionExtrasApi.swift @@ -0,0 +1,226 @@ +import Foundation + +// MARK: - Content Search (`GET /api/sessions/content-search` & `/:id/content-search`) + +public struct SessionContentMatch: Codable, Equatable, Identifiable, Sendable { + public let messageId: String + public let role: String + public let seq: Int + public let createdAt: Int + public let snippet: String + public let truncated: Bool + + public var id: String { messageId } + + public init( + messageId: String, + role: String, + seq: Int, + createdAt: Int, + snippet: String, + truncated: Bool + ) { + self.messageId = messageId + self.role = role + self.seq = seq + self.createdAt = createdAt + self.snippet = snippet + self.truncated = truncated + } +} + +public struct SessionContentSearchHit: Codable, Equatable, Identifiable, Sendable { + public let session: SessionSummary + public let match: SessionContentMatch + + public var id: String { "\(session.id):\(match.messageId)" } + + public init(session: SessionSummary, match: SessionContentMatch) { + self.session = session + self.match = match + } +} + +public struct SessionsContentSearchResponse: Codable, Equatable, Sendable { + public let results: [SessionContentSearchHit] + public let hasPotentiallyIncompleteResults: Bool + + public init(results: [SessionContentSearchHit], hasPotentiallyIncompleteResults: Bool = false) { + self.results = results + self.hasPotentiallyIncompleteResults = hasPotentiallyIncompleteResults + } +} + +public struct SessionContentMatchesResponse: Codable, Equatable, Sendable { + public let matches: [SessionContentMatch] + public let total: Int + public let hasPotentiallyIncompleteResults: Bool + + public init(matches: [SessionContentMatch], total: Int, hasPotentiallyIncompleteResults: Bool = false) { + self.matches = matches + self.total = total + self.hasPotentiallyIncompleteResults = hasPotentiallyIncompleteResults + } +} + +// MARK: - External Refs & PR Chip (`GET /api/sessions/:id/external-refs`) + +public struct ExternalRef: Codable, Equatable, Identifiable, Sendable { + public let kind: String + public let repo: String + public let number: Int + public let url: String + public let role: String + public let source: String? + public let linkedAt: Int? + public let openState: String? + public let checks: String? + public let merge: String? + public let statusCheckedAt: Int? + public let estateCode: String? + + public var id: String { "\(kind):\(repo)#\(number)" } + + public init( + kind: String = "github_pr", + repo: String, + number: Int, + url: String, + role: String = "primary", + source: String? = nil, + linkedAt: Int? = nil, + openState: String? = nil, + checks: String? = nil, + merge: String? = nil, + statusCheckedAt: Int? = nil, + estateCode: String? = nil + ) { + self.kind = kind + self.repo = repo + self.number = number + self.url = url + self.role = role + self.source = source + self.linkedAt = linkedAt + self.openState = openState + self.checks = checks + self.merge = merge + self.statusCheckedAt = statusCheckedAt + self.estateCode = estateCode + } +} + +public struct SessionExternalRefsResponse: Codable, Equatable, Sendable { + public let externalRefs: [ExternalRef] + + public init(externalRefs: [ExternalRef]) { + self.externalRefs = externalRefs + } +} + +/// Presentation tone matching `shared/src/prChipDisplay.ts`. +public enum PrChipTone: String, Equatable, Sendable { + case ok + case pending + case needsWork = "needs_work" + case merged + case muted + case unknown +} + +/// Resolved GitHub PR chip metadata for display above the chat composer. +public struct PrChipDisplay: Equatable, Sendable { + public let repo: String + public let number: Int + public let url: String + public let label: String? + public let tone: PrChipTone + public let stale: Bool + + public init( + repo: String, + number: Int, + url: String, + label: String?, + tone: PrChipTone, + stale: Bool + ) { + self.repo = repo + self.number = number + self.url = url + self.label = label + self.tone = tone + self.stale = stale + } + + public static let defaultStaleMs = 2 * 60 * 60 * 1_000 + + /// Pick the primary GitHub PR ref (or first GitHub PR ref if none marked primary). + public static func primary( + from refs: [ExternalRef], + staleMs: Int = defaultStaleMs, + nowMs: Int = Int(Date().timeIntervalSince1970 * 1_000) + ) -> PrChipDisplay? { + let prs = refs.filter { $0.kind == "github_pr" } + guard let chosen = prs.first(where: { $0.role == "primary" }) ?? prs.first else { + return nil + } + return resolve(from: chosen, staleMs: staleMs, nowMs: nowMs) + } + + /// Resolve display tone & label from a cached forge snapshot (`prChipDisplay.ts` parity). + public static func resolve( + from ref: ExternalRef, + staleMs: Int = defaultStaleMs, + nowMs: Int = Int(Date().timeIntervalSince1970 * 1_000) + ) -> PrChipDisplay { + let hasSnapshot = ref.openState != nil || ref.checks != nil || ref.merge != nil || ref.estateCode != nil + let stale: Bool + if hasSnapshot { + if let checkedAt = ref.statusCheckedAt { + stale = (nowMs - checkedAt) > staleMs + } else { + stale = true + } + } else { + stale = false + } + + let resolved = resolveForge(ref) + if !hasSnapshot { + return PrChipDisplay(repo: ref.repo, number: ref.number, url: ref.url, label: nil, tone: .muted, stale: false) + } + if stale { + return PrChipDisplay(repo: ref.repo, number: ref.number, url: ref.url, label: resolved?.label, tone: .unknown, stale: true) + } + return PrChipDisplay( + repo: ref.repo, + number: ref.number, + url: ref.url, + label: resolved?.label, + tone: resolved?.tone ?? .muted, + stale: false + ) + } + + private static func resolveForge(_ ref: ExternalRef) -> (tone: PrChipTone, label: String)? { + // Terminal states first: merged/closed/draft take precedence over stale checks/merge flags. + switch ref.openState { + case "merged": return (.merged, "merged") + case "closed": return (.muted, "closed") + case "draft": return (.muted, "draft") + default: break + } + if ref.checks == "fail" { return (.needsWork, "checks failed") } + if ref.merge == "conflicting" { return (.needsWork, "conflicts") } + if ref.merge == "blocked" { return (.needsWork, "merge blocked") } + if ref.checks == "pending" { return (.pending, "checks running") } + if ref.merge == "unstable" { return (.pending, "unstable") } + if ref.merge == "behind" { return (.pending, "behind base") } + if ref.merge == "clean" && ref.checks == "pass" { return (.ok, "ready to merge") } + if ref.merge == "clean" { return (.ok, "mergeable") } + if ref.checks == "pass" { return (.ok, "checks passed") } + if ref.openState == "open" { return (.ok, "open") } + return nil + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionLifecycle.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionLifecycle.swift new file mode 100644 index 00000000000..40950319db0 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionLifecycle.swift @@ -0,0 +1,50 @@ +import Foundation + +/// `metadata.lifecycleState` vocabulary (`shared/src/sessionLifecycle.ts`). +public enum SessionLifecycle { + public static let running = "running" + public static let idle = "idle" + public static let archived = "archived" + + /// True for lifecycle states that mean a CLI/runner still owns the session. + public static func isLive(_ value: String?) -> Bool { + value == running || value == idle + } +} + +public extension SessionSummary { + /// A spawned session the hub created whose agent has not connected yet + /// (web `STARTING_MEMBER_WINDOW_MS`, 2 minutes). + static let startingMemberWindowMs = 2 * 60 * 1000 + + /// Same liveness the hub archive route accepts (`web/src/components/ProjectGroupRow.tsx`). + var isArchivable: Bool { + active || SessionLifecycle.isLive(metadata?.lifecycleState) + } + + /// True when the hub created the row recently and its agent has not connected yet. + func isStarting(nowMs: Int) -> Bool { + !active + && metadata?.lifecycleState == nil + && nowMs - (createdAt ?? 0) < Self.startingMemberWindowMs + } + + /// Agent foreground work (`web/src/lib/sessionInProgress.ts` `hasAgentForegroundWork`). + var hasAgentForegroundWork: Bool { + guard active else { return false } + if backgroundTaskCount > 0 { return true } + return thinking && pendingRequestsCount == 0 + } + + /// Running attached job on an unarchived session (`web/src/lib/sessionInProgress.ts`). + var hasUnarchivedRunningJob: Bool { + metadata?.lifecycleState != SessionLifecycle.archived && attachedJob?.isRunning == true + } + + /// Fresh (non-stale) running attached job on an unarchived session + /// (`web/src/lib/sessionInProgress.ts` `hasInProgressJobSession`). + func hasInProgressJob(nowMs: Int) -> Bool { + guard hasUnarchivedRunningJob, let job = attachedJob else { return false } + return nowMs - job.effectiveHeartbeatAt <= AttachedJob.staleAfterMs + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift index 5aee0fcd762..3faf943338f 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionMetadata.swift @@ -119,6 +119,9 @@ public struct SessionMetadata: Codable, Equatable, Sendable { /// clear/reopen; used to follow superseding sessions. public var supersededBySessionId: String? public var worktree: WorktreeMetadata? + /// Hub-owned: id of the session that leads this session's two-level group. + /// Absent for leaders and ungrouped sessions. + public var groupLeaderId: String? public var capabilities: SessionCapabilities? /// Loopback MCP URL when the session's CLI happy server is running. public var hapiMcpUrl: String? @@ -160,6 +163,7 @@ public struct SessionMetadata: Codable, Equatable, Sendable { lifecycleState: String? = nil, supersededBySessionId: String? = nil, worktree: WorktreeMetadata? = nil, + groupLeaderId: String? = nil, capabilities: SessionCapabilities? = nil, hapiMcpUrl: String? = nil, slashCommands: [String]? = nil, @@ -191,6 +195,7 @@ public struct SessionMetadata: Codable, Equatable, Sendable { self.lifecycleState = lifecycleState self.supersededBySessionId = supersededBySessionId self.worktree = worktree + self.groupLeaderId = groupLeaderId self.capabilities = capabilities self.hapiMcpUrl = hapiMcpUrl self.slashCommands = slashCommands diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionPatch.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionPatch.swift index 0ab3a8b0ad6..a8762cea831 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionPatch.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionPatch.swift @@ -68,6 +68,7 @@ public struct SessionPatch: Equatable, Sendable { public var collaborationMode: CodexCollaborationMode? public var copilotAgentMode: CopilotAgentMode? public var backgroundTaskCount: Int? + public var derivedToolWork: Bool? /// Bare refetch trigger for `GET /api/sessions/:id/scratchlist`; never /// applied onto the `Session` (which carries no such field). public var scratchlistUpdatedAt: Int? @@ -96,6 +97,7 @@ public struct SessionPatch: Equatable, Sendable { collaborationMode: CodexCollaborationMode? = nil, copilotAgentMode: CopilotAgentMode? = nil, backgroundTaskCount: Int? = nil, + derivedToolWork: Bool? = nil, scratchlistUpdatedAt: Int? = nil, attachedJob: VersionedValue? = nil ) { @@ -119,6 +121,7 @@ public struct SessionPatch: Equatable, Sendable { self.collaborationMode = collaborationMode self.copilotAgentMode = copilotAgentMode self.backgroundTaskCount = backgroundTaskCount + self.derivedToolWork = derivedToolWork self.scratchlistUpdatedAt = scratchlistUpdatedAt self.attachedJob = attachedJob } @@ -145,6 +148,7 @@ extension SessionPatch: Codable { case collaborationMode case copilotAgentMode case backgroundTaskCount + case derivedToolWork case scratchlistUpdatedAt case attachedJob // Web-only status-panel list; accepted so the patch is not refetched. @@ -179,6 +183,7 @@ extension SessionPatch: Codable { collaborationMode = try container.decodeIfPresent(CodexCollaborationMode.self, forKey: .collaborationMode) copilotAgentMode = try container.decodeIfPresent(CopilotAgentMode.self, forKey: .copilotAgentMode) backgroundTaskCount = try container.decodeIfPresent(Int.self, forKey: .backgroundTaskCount) + derivedToolWork = try container.decodeIfPresent(Bool.self, forKey: .derivedToolWork) scratchlistUpdatedAt = try container.decodeIfPresent(Int.self, forKey: .scratchlistUpdatedAt) attachedJob = try container.decodeIfPresent(VersionedValue.self, forKey: .attachedJob) } @@ -205,6 +210,7 @@ extension SessionPatch: Codable { try container.encodeIfPresent(collaborationMode, forKey: .collaborationMode) try container.encodeIfPresent(copilotAgentMode, forKey: .copilotAgentMode) try container.encodeIfPresent(backgroundTaskCount, forKey: .backgroundTaskCount) + try container.encodeIfPresent(derivedToolWork, forKey: .derivedToolWork) try container.encodeIfPresent(scratchlistUpdatedAt, forKey: .scratchlistUpdatedAt) try container.encodeIfPresent(attachedJob, forKey: .attachedJob) } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift index 1f42d33d23c..3c892225a93 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift @@ -56,6 +56,8 @@ public struct SessionSummaryMetadata: Codable, Equatable, Sendable { public var summary: Summary? public var flavor: String? public var worktree: WorktreeMetadata? + /// Leader of this session's group; absent for leaders and ungrouped sessions. + public var groupLeaderId: String? /// Native agent session id resolved per flavor by the hub. public var agentSessionId: String? public var lifecycleState: String? @@ -69,6 +71,7 @@ public struct SessionSummaryMetadata: Codable, Equatable, Sendable { summary: Summary? = nil, flavor: String? = nil, worktree: WorktreeMetadata? = nil, + groupLeaderId: String? = nil, agentSessionId: String? = nil, lifecycleState: String? = nil, hapiMcpUrl: String? = nil @@ -80,6 +83,7 @@ public struct SessionSummaryMetadata: Codable, Equatable, Sendable { self.summary = summary self.flavor = flavor self.worktree = worktree + self.groupLeaderId = groupLeaderId self.agentSessionId = agentSessionId self.lifecycleState = lifecycleState self.hapiMcpUrl = hapiMcpUrl @@ -120,6 +124,8 @@ public struct SessionSummary: Codable, Equatable, Sendable { public var pendingRequestKinds: [PendingRequestKind] public var pendingRequests: [PendingRequest] public var backgroundTaskCount: Int + /// Hub-derived open tool work in the transcript tail (work-scoped liveness). + public var derivedToolWork: Bool? public var futureScheduledMessageCount: Int /// Epoch ms of the soonest uninvoked scheduled message, or `nil`. public var nextScheduledAt: Int? @@ -154,6 +160,7 @@ public struct SessionSummary: Codable, Equatable, Sendable { pendingRequestKinds: [PendingRequestKind] = [], pendingRequests: [PendingRequest] = [], backgroundTaskCount: Int = 0, + derivedToolWork: Bool? = nil, futureScheduledMessageCount: Int = 0, nextScheduledAt: Int? = nil, attachedJob: AttachedJob? = nil, @@ -183,6 +190,7 @@ public struct SessionSummary: Codable, Equatable, Sendable { self.pendingRequestKinds = pendingRequestKinds self.pendingRequests = pendingRequests self.backgroundTaskCount = backgroundTaskCount + self.derivedToolWork = derivedToolWork self.futureScheduledMessageCount = futureScheduledMessageCount self.nextScheduledAt = nextScheduledAt self.attachedJob = attachedJob diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift index c56d4ec2b64..da96c34b0aa 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SummaryPatching.swift @@ -157,6 +157,7 @@ public enum SummaryPatching { summary: metadata.summary.map { SessionSummaryMetadata.Summary(text: $0.text) }, flavor: metadata.flavor, worktree: metadata.worktree, + groupLeaderId: metadata.groupLeaderId, agentSessionId: summaryAgentSessionId(metadata), lifecycleState: metadata.lifecycleState, hapiMcpUrl: metadata.hapiMcpUrl @@ -191,6 +192,7 @@ public enum SummaryPatching { pendingRequestKinds: computePendingRequestKinds(session.agentState), pendingRequests: computePendingRequests(session.agentState, fallbackSince: session.updatedAt), backgroundTaskCount: session.backgroundTaskCount ?? 0, + derivedToolWork: session.derivedToolWork == true, futureScheduledMessageCount: 0, nextScheduledAt: nil, model: session.model, @@ -237,6 +239,7 @@ public enum SummaryPatching { next.updatedAt = patch.updatedAt.map { max(current.updatedAt, $0) } ?? current.updatedAt next.lastUserMessageAt = patch.lastUserMessageAt.map { max(current.lastUserMessageAt ?? 0, $0) } ?? current.lastUserMessageAt next.backgroundTaskCount = patch.backgroundTaskCount ?? current.backgroundTaskCount + if let derivedToolWork = patch.derivedToolWork { next.derivedToolWork = derivedToolWork } if let field = patch.model { next.model = field.wireValue } if let field = patch.modelReasoningEffort { next.modelReasoningEffort = field.wireValue } if let field = patch.effort { next.effort = field.wireValue } @@ -282,6 +285,7 @@ public enum SummaryPatching { if current.machineId != next.machineId { return false } if current.summary?.text != next.summary?.text { return false } if current.flavor != next.flavor { return false } + if current.groupLeaderId != next.groupLeaderId { return false } if current.agentSessionId != next.agentSessionId { return false } if current.lifecycleState != next.lifecycleState { return false } if current.worktree?.basePath != next.worktree?.basePath { return false } @@ -313,6 +317,7 @@ public enum SummaryPatching { if current.updatedAt != next.updatedAt { return false } if current.lastUserMessageAt != next.lastUserMessageAt { return false } if current.backgroundTaskCount != next.backgroundTaskCount { return false } + if (current.derivedToolWork == true) != (next.derivedToolWork == true) { return false } if current.model != next.model { return false } if current.modelReasoningEffort != next.modelReasoningEffort { return false } if current.effort != next.effort { return false } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/UsageApi.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/UsageApi.swift index c4367de68ef..732ea5dd863 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/UsageApi.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/UsageApi.swift @@ -138,6 +138,10 @@ public struct SqliteStorageUsageResponse: Codable, Equatable, Sendable { public struct UsageQuotasResponse: Decodable, Sendable { public let machines: [Machine] + public init(machines: [Machine]) { + self.machines = machines + } + public struct Machine: Decodable, Sendable { public let machineId: String public let machineName: String @@ -145,6 +149,20 @@ public struct UsageQuotasResponse: Decodable, Sendable { public let error: String? public let accounts: [Account] + public init( + machineId: String, + machineName: String, + supported: Bool = true, + error: String? = nil, + accounts: [Account] = [] + ) { + self.machineId = machineId + self.machineName = machineName + self.supported = supported + self.error = error + self.accounts = accounts + } + public var visibleAccounts: [Account] { accounts.filter { $0.available || $0.status != "unavailable" } } @@ -159,15 +177,52 @@ public struct UsageQuotasResponse: Decodable, Sendable { public let accountLabel: String? public let note: String? public let buckets: [Bucket] + + public init( + agent: AgentFlavor, + available: Bool = true, + status: String, + planLabel: String? = nil, + creditsLabel: String? = nil, + accountLabel: String? = nil, + note: String? = nil, + buckets: [Bucket] = [] + ) { + self.agent = agent + self.available = available + self.status = status + self.planLabel = planLabel + self.creditsLabel = creditsLabel + self.accountLabel = accountLabel + self.note = note + self.buckets = buckets + } } public struct Bucket: Decodable, Sendable { public let id: String public let label: String + public let window: String? public let remainingPercent: Double public let usedPercent: Double public let resetsAt: Double? + public init( + id: String, + label: String, + window: String? = nil, + remainingPercent: Double, + usedPercent: Double, + resetsAt: Double? = nil + ) { + self.id = id + self.label = label + self.window = window + self.remainingPercent = remainingPercent + self.usedPercent = usedPercent + self.resetsAt = resetsAt + } + public var resetDate: Date? { guard let resetsAt, resetsAt != 0 else { return nil } return Date(timeIntervalSince1970: resetsAt / 1_000) diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Pairing/BindLink.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Pairing/BindLink.swift index e3e1598e0f8..1340fe7f113 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Pairing/BindLink.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Pairing/BindLink.swift @@ -74,7 +74,8 @@ public struct BindLink: Equatable, Sendable { guard let host = components.host?.lowercased(), host == Self.host else { return nil } - guard let params = formParameters(of: components), + guard let rawQuery = components.percentEncodedQuery, + let params = formParameters(from: rawQuery), let hub = params["hub"], !isBlank(hub), let code = params["code"], !isBlank(code), isHTTPURL(hub) else { @@ -83,16 +84,32 @@ public struct BindLink: Equatable, Sendable { return BindLink(hubUrl: hub, accessToken: code) } - /// `http(s):///...?hub=&token=` — the web - /// direct-access QR (`${officialWebUrl}/?hub=…&token=…`). The web host and - /// path are not pinned: self-hosted deployments serve the app anywhere. + /// `http(s):///...#hub=&token=` (or legacy + /// `?hub=&token=`, or mixed `?hub=#token=`). + /// Fragment parameters take precedence over query parameters so tokens never + /// need to travel in request URLs. The web host and path are not pinned: + /// self-hosted deployments serve the app anywhere. private static func parseWebDirectAccessURL(_ components: URLComponents) -> BindLink? { guard let host = components.host, !host.isEmpty else { return nil } - guard let params = formParameters(of: components), - let hub = params["hub"], !isBlank(hub), - let token = params["token"], !isBlank(token), + let fragmentParams: [String: String]? + if let rawFragment = components.percentEncodedFragment, !rawFragment.isEmpty { + guard let parsed = formParameters(from: rawFragment) else { return nil } + fragmentParams = parsed + } else { + fragmentParams = nil + } + let queryParams: [String: String]? + if let rawQuery = components.percentEncodedQuery, !rawQuery.isEmpty { + guard let parsed = formParameters(from: rawQuery) else { return nil } + queryParams = parsed + } else { + queryParams = nil + } + guard fragmentParams != nil || queryParams != nil, + let hub = fragmentParams?["hub"] ?? queryParams?["hub"], !isBlank(hub), + let token = fragmentParams?["token"] ?? queryParams?["token"], !isBlank(token), isHTTPURL(hub) else { return nil } @@ -101,13 +118,12 @@ public struct BindLink: Equatable, Sendable { // MARK: - Form decoding (URLSearchParams parity) - /// Decodes the raw query as `application/x-www-form-urlencoded`. - /// First occurrence wins for duplicate keys. Returns `nil` when the query - /// is absent or any component carries invalid percent escapes. - private static func formParameters(of components: URLComponents) -> [String: String]? { - guard let rawQuery = components.percentEncodedQuery else { return nil } + /// Decodes a raw `application/x-www-form-urlencoded` parameter string + /// (query or fragment). First occurrence wins for duplicate keys. Returns + /// `nil` when any component carries invalid percent escapes. + private static func formParameters(from raw: String) -> [String: String]? { var result: [String: String] = [:] - for pair in rawQuery.split(separator: "&", omittingEmptySubsequences: false) { + for pair in raw.split(separator: "&", omittingEmptySubsequences: false) { if pair.isEmpty { continue } let rawKey: Substring let rawValue: Substring diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Patch/SessionPatching.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Patch/SessionPatching.swift index 894ef945d20..14d59fc1fb7 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Patch/SessionPatching.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Patch/SessionPatching.swift @@ -63,6 +63,7 @@ public func isRenderIrrelevantSessionPatch(session: Session, patch: SessionPatch if let value = patch.collaborationMode, value != session.collaborationMode { return false } if let value = patch.copilotAgentMode, value != session.copilotAgentMode { return false } if let value = patch.backgroundTaskCount, value != session.backgroundTaskCount { return false } + if let value = patch.derivedToolWork, value != (session.derivedToolWork ?? false) { return false } // `Session` carries no scratchlistUpdatedAt, so its presence is always // "new information" in the TS reference (undefined !== number). if patch.scratchlistUpdatedAt != nil { return false } @@ -108,6 +109,7 @@ public func applySessionDetailPatch(session: Session, patch: SessionPatch) -> Se if let value = patch.collaborationMode { assign(\.collaborationMode, value as CodexCollaborationMode?) } if let value = patch.copilotAgentMode { assign(\.copilotAgentMode, value as CopilotAgentMode?) } if let value = patch.backgroundTaskCount { assign(\.backgroundTaskCount, value as Int?) } + if let value = patch.derivedToolWork { assign(\.derivedToolWork, value as Bool?) } // Version gates: dual SSE can deliver duplicates out of order. Only mark // changed when a strictly newer version lands. diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Chat/AnchoredTranscriptList.swift b/ios/Packages/HapiKit/Sources/HapiUI/Chat/AnchoredTranscriptList.swift index ced3a073e38..0bdc396aeb5 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Chat/AnchoredTranscriptList.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Chat/AnchoredTranscriptList.swift @@ -299,6 +299,30 @@ private final class TranscriptCollectionView: UICollectionView { } } +/// Finds the current first responder to tell an editing keyboard apart +/// from a read-only selection. +@MainActor +private enum KeyboardResponder { + static weak var found: UIResponder? + + static func isEditingText() -> Bool { + found = nil + UIApplication.shared.sendAction(#selector(UIResponder.hapiCaptureFirstResponder(_:)), to: nil, from: nil, for: nil) + defer { found = nil } + switch found { + case let view as UITextView: return view.isEditable + case is UIKeyInput: return true + default: return false + } + } +} + +extension UIResponder { + @objc fileprivate func hapiCaptureFirstResponder(_ sender: Any?) { + MainActor.assumeIsolated { KeyboardResponder.found = self } + } +} + /// Keep hosting roots alive across unrelated transcript updates. The small /// SwiftUI wrapper reads the latest builder and inherited environment, /// including action captures. SwiftUI can diff the resulting row instead of UIKit @@ -570,7 +594,11 @@ public final class TranscriptCollectionController + /// Optional line tap handler for inline code review commenting. + public let onSelectLine: ((DiffLineSelection) -> Void)? @State private var expanded = false @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography - public init(files: [DiffFile], compact: Bool = false, compactLineLimit: Int = 12) { + public init( + files: [DiffFile], + compact: Bool = false, + compactLineLimit: Int = 12, + commentedLineKeys: Set = [], + onSelectLine: ((DiffLineSelection) -> Void)? = nil + ) { self.files = files self.compact = compact self.compactLineLimit = compactLineLimit + self.commentedLineKeys = commentedLineKeys + self.onSelectLine = onSelectLine } - public init(file: DiffFile, compact: Bool = false, compactLineLimit: Int = 12) { - self.init(files: [file], compact: compact, compactLineLimit: compactLineLimit) + public init( + file: DiffFile, + compact: Bool = false, + compactLineLimit: Int = 12, + commentedLineKeys: Set = [], + onSelectLine: ((DiffLineSelection) -> Void)? = nil + ) { + self.init( + files: [file], + compact: compact, + compactLineLimit: compactLineLimit, + commentedLineKeys: commentedLineKeys, + onSelectLine: onSelectLine + ) } /// Parses `unifiedDiff` and renders every file it contains. - public init(unifiedDiff: String, compact: Bool = false, compactLineLimit: Int = 12) { + public init( + unifiedDiff: String, + compact: Bool = false, + compactLineLimit: Int = 12, + commentedLineKeys: Set = [], + onSelectLine: ((DiffLineSelection) -> Void)? = nil + ) { self.init( files: UnifiedDiffParser.parse(unifiedDiff), compact: compact, - compactLineLimit: compactLineLimit + compactLineLimit: compactLineLimit, + commentedLineKeys: commentedLineKeys, + onSelectLine: onSelectLine ) } + public nonisolated static func lineKindKey(_ kind: DiffLine.Kind) -> String { + switch kind { + case .addition: "addition" + case .deletion: "deletion" + case .context: "context" + case .noNewlineMarker: "marker" + } + } + + public nonisolated static func lineKey(lineNumber: Int, kind: DiffLine.Kind) -> String { + "\(lineNumber):\(lineKindKey(kind))" + } + // MARK: Rows private enum RowKind { case fileHeader(DiffFile) case hunkHeader(String) - case line(DiffLine) + case line(DiffLine, selection: DiffLineSelection?) case binaryNote } @@ -60,14 +131,41 @@ public struct DiffTextView: View { } for hunk in file.hunks { append(.hunkHeader(hunk.header)) - for line in hunk.lines { - append(.line(line)) + for (index, line) in hunk.lines.enumerated() { + let selection: DiffLineSelection? + if line.kind != .noNewlineMarker, + let number = line.newNumber ?? line.oldNumber { + let start = max(0, index - 2) + let end = min(hunk.lines.count - 1, index + 2) + let snippet = hunk.lines[start...end] + .filter { $0.kind != .noNewlineMarker } + .map { snippetPrefix($0.kind) + " " + $0.text } + .joined(separator: "\n") + selection = DiffLineSelection( + filePath: file.newPath ?? file.oldPath ?? file.displayPath, + hunkHeader: hunk.header, + line: line, + lineNumber: number, + snippet: snippet + ) + } else { + selection = nil + } + append(.line(line, selection: selection)) } } } return rows } + private func snippetPrefix(_ kind: DiffLine.Kind) -> String { + switch kind { + case .addition: "+" + case .deletion: "-" + case .context, .noNewlineMarker: " " + } + } + /// Width (in characters) of one gutter column. private var gutterDigits: Int { var maxNumber = 1 @@ -150,12 +248,29 @@ public struct DiffTextView: View { .foregroundStyle(theme.textHint) .padding(.horizontal, 12) .padding(.vertical, 6) - case .line(let line): - lineRow(line, gutterDigits: gutterDigits) + case .line(let line, let selection): + let hasComment: Bool = { + guard let selection else { return false } + return commentedLineKeys.contains( + Self.lineKey(lineNumber: selection.lineNumber, kind: line.kind) + ) + }() + if let onSelectLine, let selection { + Button { + onSelectLine(selection) + } label: { + lineRow(line, gutterDigits: gutterDigits, hasComment: hasComment) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } else { + lineRow(line, gutterDigits: gutterDigits, hasComment: hasComment) + } } } - private func lineRow(_ line: DiffLine, gutterDigits: Int) -> some View { + private func lineRow(_ line: DiffLine, gutterDigits: Int, hasComment: Bool) -> some View { let (background, foreground, prefix): (Color?, Color, String) = { switch line.kind { case .addition: @@ -175,17 +290,24 @@ public struct DiffTextView: View { + paddedNumber(line.newNumber, width: gutterDigits) + " " ) - text.foregroundColor = theme.textHint + text.foregroundColor = hasComment ? theme.link : theme.textHint text.font = typography.captionMonoFont var content = AttributedString(prefix + " " + line.text) content.foregroundColor = foreground text.append(content) - return Text(text) - .font(typography.codeFont) - .padding(.horizontal, 12) - .padding(.vertical, typography.codeLineSpacing / 2) - .background(background ?? Color.clear) + return HStack(spacing: 4) { + if hasComment { + Image(systemName: "text.bubble.fill") + .font(.caption2) + .foregroundStyle(theme.link) + } + Text(text) + .font(typography.codeFont) + } + .padding(.horizontal, 12) + .padding(.vertical, typography.codeLineSpacing / 2) + .background(hasComment ? theme.link.opacity(0.12) : (background ?? Color.clear)) } private func paddedNumber(_ number: Int?, width: Int) -> String { diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownRenderCache.swift b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownRenderCache.swift index 548225acc2b..bc499525c29 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownRenderCache.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownRenderCache.swift @@ -1,51 +1,121 @@ import Foundation +#if canImport(OSLog) +import OSLog +#endif import SwiftUI /// Per-chat bounded cache. Synchronous lookup avoids an actor-hop placeholder /// when a cell is recycled; preparation runs off the main thread. +/// +/// Streaming replies use a separate per-block slot (`prepare(settled:streaming:)`) +/// that seals closed top-level blocks once and only re-parses the active tail, +/// without polluting the shared LRU cache with intermediate streaming prefixes. public final class MarkdownRenderCache: @unchecked Sendable { + public struct StreamingEntry: Equatable, Sendable { + public let id: String + public let text: String + + public init(id: String, text: String) { + self.id = id + self.text = text + } + } + private struct Entry { let blocks: [MarkdownBlockNode] let cost: Int var accessed: Int } + + private struct StreamingSlot { + var source: String + var sealedByteOffset: Int + var sealedBlocks: [MarkdownBlockNode] + var blocks: [MarkdownBlockNode] + var hasOpenCodeFence: Bool + } + private let lock = NSLock() private var entries: [String: Entry] = [:] + private var streamingSlots: [String: StreamingSlot] = [:] private var clock = 0 private var totalCost = 0 private let maxCost: Int public init(maxCost: Int = 8 * 1024 * 1024) { self.maxCost = maxCost } + /// Count of settled entries retained in the shared LRU cache (for diagnostics / tests). + public var settledEntryCount: Int { + lock.withLock { entries.count } + } + public func cached(_ text: String) -> [MarkdownBlockNode]? { lock.withLock { - guard var entry = entries[text] else { return nil } - clock += 1 - entry.accessed = clock - entries[text] = entry - return entry.blocks + if var entry = entries[text] { + clock += 1 + entry.accessed = clock + entries[text] = entry + return entry.blocks + } + for slot in streamingSlots.values where slot.source == text { + return slot.blocks + } + return nil + } + } + + /// True when `text` is currently tracked as an active streaming slot ending + /// inside an unclosed fenced code block. + public func hasOpenCodeFence(for text: String) -> Bool { + lock.withLock { + for slot in streamingSlots.values where slot.source == text { + return slot.hasOpenCodeFence + } + return false } } public func prepare(_ sources: [String]) async { + await prepare(settled: sources, streaming: []) + } + + /// Prepares settled messages into the shared LRU cache and incrementally + /// parses active streaming messages inside dedicated per-block slots. + public func prepare(settled: [String], streaming: [StreamingEntry]) async { let task = Task.detached(priority: .userInitiated) { [self] in - for text in Set(sources) where cached(text) == nil { + #if canImport(OSLog) + let signposter = OSSignposter(subsystem: "run.hapi.companion", category: "perf") + let signpostState = signposter.beginInterval("MarkdownPrepare", id: signposter.makeSignpostID()) + defer { signposter.endInterval("MarkdownPrepare", signpostState) } + #endif + // 1. Update streaming slots incrementally (never writes into `entries`). + let activeIds = Set(streaming.map(\.id)) + for item in streaming { guard !Task.isCancelled else { return } + updateStreamingSlot(id: item.id, text: item.text) + } + + // 2. Promote any settled messages (reusing a matching streaming slot's + // already-parsed blocks when a turn just completed). + for text in Set(settled) { + guard !Task.isCancelled else { return } + let alreadyCached = lock.withLock { entries[text] != nil } + if alreadyCached { continue } guard text.utf8.count * 4 <= maxCost else { continue } - let blocks = MarkdownBlockTree.build(from: text) - lock.withLock { - guard entries[text] == nil else { return } - clock += 1 - let cost = max(1, text.utf8.count * 4) - guard cost <= maxCost else { return } - entries[text] = Entry(blocks: blocks, cost: cost, accessed: clock) - totalCost += cost - while totalCost > maxCost || entries.count > 800 { - guard let oldest = entries.min(by: { $0.value.accessed < $1.value.accessed }) else { break } - totalCost -= oldest.value.cost - entries.removeValue(forKey: oldest.key) + + let promoted: [MarkdownBlockNode]? = lock.withLock { + for slot in streamingSlots.values where slot.source == text { + return slot.blocks } + return nil } + let blocks = promoted ?? MarkdownBlockTree.build(from: text) + storeSettled(text: text, blocks: blocks) + } + + // 3. Evict streaming slots that are no longer actively streaming. + lock.withLock { + streamingSlots = streamingSlots.filter { activeIds.contains($0.key) } } } await withTaskCancellationHandler { @@ -54,6 +124,73 @@ public final class MarkdownRenderCache: @unchecked Sendable { task.cancel() } } + + private func storeSettled(text: String, blocks: [MarkdownBlockNode]) { + lock.withLock { + guard entries[text] == nil else { return } + clock += 1 + let cost = max(1, text.utf8.count * 4) + guard cost <= maxCost else { return } + entries[text] = Entry(blocks: blocks, cost: cost, accessed: clock) + totalCost += cost + while totalCost > maxCost || entries.count > 800 { + guard let oldest = entries.min(by: { $0.value.accessed < $1.value.accessed }) else { break } + totalCost -= oldest.value.cost + entries.removeValue(forKey: oldest.key) + } + } + } + + private func updateStreamingSlot(id: String, text: String) { + let existing: StreamingSlot? = lock.withLock { streamingSlots[id] } + if let existing, existing.source == text { return } + + var sealedOffset = 0 + var sealedBlocks: [MarkdownBlockNode] = [] + + if let existing, + text.hasPrefix(existing.source), + existing.sealedByteOffset > 0, + existing.sealedByteOffset <= text.utf8.count, + StreamingMarkdownSplitter.canSplitIncrementally(text) { + sealedOffset = existing.sealedByteOffset + sealedBlocks = existing.sealedBlocks + } + + let utf8 = text.utf8 + if let nextSeal = StreamingMarkdownSplitter.safeSealOffset(in: text, from: sealedOffset), + nextSeal > sealedOffset, + nextSeal <= utf8.count { + let fromIdx = utf8.index(utf8.startIndex, offsetBy: sealedOffset) + let toIdx = utf8.index(utf8.startIndex, offsetBy: nextSeal) + let newlyClosed = String(text[fromIdx.. 8 { + let overflow = streamingSlots.keys.filter { $0 != id }.prefix(streamingSlots.count - 8) + for key in overflow { + streamingSlots.removeValue(forKey: key) + } + } + } + } } private struct MarkdownRenderCacheKey: EnvironmentKey { @@ -71,29 +208,52 @@ public extension EnvironmentValues { /// miss keeps previous content until the new revision has been parsed. public struct CachedMarkdownView: View { public let markdown: String + public let isStreaming: Bool @Environment(\.hapiMarkdownCache) private var cache @State private var prepared: [MarkdownBlockNode]? - public init(markdown: String) { self.markdown = markdown } + public init(markdown: String, isStreaming: Bool = false) { + self.markdown = markdown + self.isStreaming = isStreaming + } + + private var deferTrailingCodeHighlight: Bool { + guard isStreaming else { return false } + return cache?.hasOpenCodeFence(for: markdown) + ?? StreamingMarkdownSplitter.hasUnclosedCodeFence(markdown) + } public var body: some View { Group { if let cache { - if let blocks = cache.cached(markdown) ?? prepared { MarkdownView(blocks: blocks) } - else { Text(markdown).textSelection(.enabled) } + if let blocks = cache.cached(markdown) ?? prepared { + MarkdownView(blocks: blocks, deferTrailingCodeHighlight: deferTrailingCodeHighlight) + } else { + Text(markdown).textSelection(.enabled) + } } else { - MarkdownView(markdown: markdown) + MarkdownView(markdown: markdown, deferTrailingCodeHighlight: deferTrailingCodeHighlight) } } .task(id: markdown) { guard let cache else { return } - await cache.prepare([markdown]) - guard !Task.isCancelled else { return } - if let blocks = cache.cached(markdown) { prepared = blocks } - else { + if let blocks = cache.cached(markdown) { + prepared = blocks + return + } + if isStreaming { let source = markdown let blocks = await Task.detached { MarkdownBlockTree.build(from: source) }.value if !Task.isCancelled { prepared = blocks } + } else { + await cache.prepare([markdown]) + guard !Task.isCancelled else { return } + if let blocks = cache.cached(markdown) { prepared = blocks } + else { + let source = markdown + let blocks = await Task.detached { MarkdownBlockTree.build(from: source) }.value + if !Task.isCancelled { prepared = blocks } + } } } } diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownRenderer.swift b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownRenderer.swift index a02a56ec2a0..ab65ee5c7e1 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownRenderer.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownRenderer.swift @@ -54,6 +54,53 @@ public struct MarkdownTableModel: Equatable, Sendable { self.header = header self.rows = rows } + + /// Plain tab-separated representation for pasting into spreadsheets / notes. + public func tsvText() -> String { + let allRows = [header] + rows + return allRows + .map { row in + row.map { cell in + String(cell.characters) + .replacingOccurrences(of: "\t", with: " ") + .replacingOccurrences(of: "\n", with: " ") + }.joined(separator: "\t") + } + .joined(separator: "\n") + } + + /// GFM Markdown table representation preserving column alignments. + public func markdownText() -> String { + let columnCount = max(header.count, columnAlignments.count, rows.map(\.count).max() ?? 0) + guard columnCount > 0 else { return "" } + + func escapeCell(_ cell: AttributedString) -> String { + String(cell.characters) + .replacingOccurrences(of: "|", with: "\\|") + .replacingOccurrences(of: "\n", with: "
") + } + + func formatRow(_ cells: [AttributedString]) -> String { + let padded = (0.. String in + let alignment = idx < columnAlignments.count ? columnAlignments[idx] : nil + switch alignment { + case .left: return ":---" + case .center: return ":---:" + case .right: return "---:" + case nil: return "---" + } + }.joined(separator: " | ") + " |" + + var lines = [formatRow(header), separator] + lines.append(contentsOf: rows.map(formatRow)) + return lines.joined(separator: "\n") + } } public struct MarkdownListModel: Equatable, Sendable { @@ -79,6 +126,35 @@ public struct MarkdownListModel: Equatable, Sendable { } } +/// GitHub Flavored Markdown admonition callout kinds (`> [!NOTE]`, etc.). +public enum MarkdownAdmonitionKind: String, CaseIterable, Equatable, Sendable { + case note + case tip + case important + case warning + case caution + + public var title: String { + switch self { + case .note: "Note" + case .tip: "Tip" + case .important: "Important" + case .warning: "Warning" + case .caution: "Caution" + } + } + + public var symbolName: String { + switch self { + case .note: "info.circle" + case .tip: "lightbulb" + case .important: "exclamationmark.bubble" + case .warning: "exclamationmark.triangle" + case .caution: "flame" + } + } +} + /// Renderer-ready markdown block tree. Built from source text by /// `MarkdownBlockTree.build(from:)`; pure data, so the conversion is unit /// testable without rendering any view. @@ -87,6 +163,7 @@ public indirect enum MarkdownBlockNode: Equatable, Sendable { case heading(level: Int, AttributedString) case codeBlock(language: String?, code: String) case blockquote([MarkdownBlockNode]) + case admonition(MarkdownAdmonitionKind, [MarkdownBlockNode]) case list(MarkdownListModel) case table(MarkdownTableModel) case thematicBreak @@ -168,7 +245,42 @@ struct BlockBuilder: MarkupVisitor { } mutating func visitBlockQuote(_ blockQuote: BlockQuote) -> [MarkdownBlockNode] { - [.blockquote(blockQuote.children.flatMap { visit($0) })] + var children = blockQuote.children.flatMap { visit($0) } + if let (kind, remaining) = Self.extractAdmonition(from: children) { + children = remaining + return [.admonition(kind, children)] + } + return [.blockquote(children)] + } + + private static let admonitionPrefixRegex = try! NSRegularExpression( + pattern: #"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:[ \t\n]+|$)"#, + options: [.caseInsensitive] + ) + + private static func extractAdmonition( + from children: [MarkdownBlockNode] + ) -> (MarkdownAdmonitionKind, [MarkdownBlockNode])? { + guard case .paragraph(let first) = children.first else { return nil } + let plain = String(first.characters) + let nsRange = NSRange(plain.startIndex.. [MarkdownBlockNode] { @@ -346,20 +458,28 @@ struct InlineBuilder: MarkupVisitor { if target.isEmpty { // No destination — plain text. } else if !HrefPolicy.hasScheme(target) { - // Scheme-less: only repo-relative workspace files become links; - // everything else path-like renders inert (web #1452 rule; SPA - // routes have no iOS equivalent). - if let fileLink = MarkdownTransforms.fileLinkTarget(forExplicitHref: target), - let url = fileLink.url { + // Scheme-less: session citations (`/sessions/`) and repo-relative + // workspace files become in-app links; everything else path-like + // renders inert (web #1452 rule). + if let sessionLink = MarkdownTransforms.sessionLinkTarget(forExplicitHref: target), + let url = sessionLink.url { + result.link = url + } else if let fileLink = MarkdownTransforms.fileLinkTarget(forExplicitHref: target), + let url = fileLink.url { result.link = url } } else { - switch HrefPolicy.classify(target) { - case .blocked: - break - case .allowed, .confirmFirst: - if let url = Self.makeURL(from: target) { - result.link = url + let scheme = HrefPolicy.normalizedScheme(of: target) + if scheme == SessionPathLink.urlScheme || scheme == FilePathLink.urlScheme { + // Internal link schemes are emitted by our own transforms only. + } else { + switch HrefPolicy.classify(target) { + case .blocked: + break + case .allowed, .confirmFirst: + if let url = Self.makeURL(from: target) { + result.link = url + } } } } @@ -411,15 +531,41 @@ struct InlineBuilder: MarkupVisitor { var cursor = string.startIndex for hit in MarkdownTransforms.detectAutolinkRanges(in: string) { if hit.range.lowerBound > cursor { - output += filePathLinked(String(string[cursor.. AttributedString { + let hits = MarkdownTransforms.detectSessionPathRanges(in: string) + guard !hits.isEmpty else { return filePathLinked(string) } + var output = AttributedString() + var cursor = string.startIndex + for (range, link) in hits { + if range.lowerBound > cursor { + output += filePathLinked(String(string[cursor.. 0 ? blocks[index - 1] : nil)) + ForEach(Array(segments.enumerated()), id: \.offset) { index, segment in + let isLastSegment = index == segments.count - 1 + segmentView(segment, isLastSegment: isLastSegment) + .padding(.top, index > 0 ? Self.spacing(before: segment.first ?? .thematicBreak, + after: segments[index - 1].last) : 0) + } + } + } + + @ViewBuilder + private func segmentView(_ segment: MarkdownSegment, isLastSegment: Bool) -> some View { + switch segment { + case .text(let prose): + #if canImport(UIKit) + SelectableProseView(blocks: prose) + #else + VStack(alignment: .leading, spacing: 0) { + ForEach(Array(prose.enumerated()), id: \.offset) { index, block in + MarkdownBlockView(block: block) + .padding(.top, Self.spacing(before: block, after: index > 0 ? prose[index - 1] : nil)) + } } + #endif + case .block(let block): + MarkdownBlockView( + block: block, + deferCodeHighlighting: deferTrailingCodeHighlight && isLastSegment + ) } } @@ -533,6 +710,7 @@ struct MarkdownBlockListView: View { struct MarkdownBlockView: View { let block: MarkdownBlockNode + var deferCodeHighlighting: Bool = false @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography @@ -552,18 +730,24 @@ struct MarkdownBlockView: View { .foregroundStyle(theme.textPrimary) .textSelection(.enabled) case .codeBlock(let language, let code): - CodeBlockView(language: language, code: code) + CodeBlockView(language: language, code: code, deferHighlighting: deferCodeHighlighting) case .blockquote(let children): HStack(alignment: .top, spacing: 10) { RoundedRectangle(cornerRadius: 1.5) .fill(theme.quoteBar) .frame(width: 3) MarkdownBlockListView(blocks: children) + .frame(maxWidth: .infinity, alignment: .leading) + MarkdownQuoteCopyButton(text: MarkdownPlainText.text(of: children)) + .padding(.top, -6) + .padding(.trailing, -6) } .fixedSize(horizontal: false, vertical: true) .padding(10) .background(theme.quoteBackground) .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + case .admonition(let kind, let children): + MarkdownAdmonitionView(kind: kind, children: children) case .list(let model): MarkdownListView(model: model) case .table(let model): @@ -579,6 +763,85 @@ struct MarkdownBlockView: View { } } +/// Styled GitHub Flavored Markdown admonition callout (`[!NOTE]`, `[!TIP]`, +/// `[!IMPORTANT]`, `[!WARNING]`, `[!CAUTION]`). +struct MarkdownAdmonitionView: View { + let kind: MarkdownAdmonitionKind + let children: [MarkdownBlockNode] + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography + + private var accentColor: Color { + switch kind { + case .note: theme.link + case .tip: theme.success + case .important: Color.purple + case .warning: theme.warning + case .caution: theme.danger + } + } + + var body: some View { + HStack(alignment: .top, spacing: 10) { + RoundedRectangle(cornerRadius: 1.5) + .fill(accentColor) + .frame(width: 3) + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 6) { + SwiftUI.Image(systemName: kind.symbolName) + .font(.system(size: typography.captionSize, weight: .semibold)) + .foregroundStyle(accentColor) + SwiftUI.Text(kind.title) + .font(typography.captionFont.weight(.semibold)) + .foregroundStyle(accentColor) + Spacer(minLength: 4) + MarkdownQuoteCopyButton(text: MarkdownPlainText.text(of: children)) + .padding(.vertical, -8) + .padding(.trailing, -6) + } + if !children.isEmpty { + MarkdownBlockListView(blocks: children) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + } + .fixedSize(horizontal: false, vertical: true) + .padding(10) + .background(accentColor.opacity(theme.isDark ? 0.14 : 0.08)) + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + } +} + +/// One-tap copy for a blockquote's plain text (same feedback as code blocks). +struct MarkdownQuoteCopyButton: View { + let text: String + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography + @Environment(\.hapiPasteboard) private var pasteboard + @State private var showCopied = false + + var body: some View { + Button { + let pasteboard = pasteboard + let text = text + Task { @MainActor in + pasteboard.copy(text) + showCopied = true + try? await Task.sleep(nanoseconds: 1_500_000_000) + showCopied = false + } + } label: { + SwiftUI.Image(systemName: showCopied ? "checkmark" : "doc.on.doc") + .font(typography.captionFont) + .foregroundStyle(showCopied ? theme.success : theme.textSecondary) + .frame(width: 32, height: 32) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(SwiftUI.Text(showCopied ? "Copied" : "Copy quote")) + } +} + struct MarkdownListView: View { let model: MarkdownListModel @Environment(\.hapiTheme) private var theme @@ -618,39 +881,75 @@ struct MarkdownTableView: View { let model: MarkdownTableModel @Environment(\.hapiTheme) private var theme @Environment(\.hapiTypography) private var typography + @Environment(\.hapiPasteboard) private var pasteboard + + static let minimumColumnWidth: CGFloat = 60 + static let maximumColumnWidth: CGFloat = 300 var body: some View { ScrollView(.horizontal, showsIndicators: false) { Grid(alignment: .topLeading, horizontalSpacing: 0, verticalSpacing: 0) { GridRow { ForEach(Array(model.header.enumerated()), id: \.offset) { index, cell in - SwiftUI.Text(hapiStyledText(cell, theme: theme, typography: typography)) - .fontWeight(.semibold) - .font(typography.bodyFont) - .foregroundStyle(theme.textPrimary) - .padding(.horizontal, 10) - .padding(.vertical, 6) - .gridColumnAlignment(columnAlignment(index)) + cellView(cell, column: index, header: true) .background(theme.tableHeaderBackground) } } - ForEach(Array(model.rows.enumerated()), id: \.offset) { _, row in + ForEach(Array(model.rows.enumerated()), id: \.offset) { rowIndex, row in Divider() GridRow { ForEach(Array(row.enumerated()), id: \.offset) { index, cell in - SwiftUI.Text(hapiStyledText(cell, theme: theme, typography: typography)) - .font(typography.bodyFont) - .foregroundStyle(theme.textPrimary) - .padding(.horizontal, 10) - .padding(.vertical, 6) - .gridColumnAlignment(columnAlignment(index)) + cellView(cell, column: index, header: false) + .background(rowIndex.isMultiple(of: 2) ? Color.clear : theme.quoteBackground.opacity(0.6)) } } } } + // Rows take their content height first; only then do the cells' + // `maxHeight: .infinity` frames stretch to fill them. Without this + // a large height proposal is shared out as blank space in rows. + .fixedSize(horizontal: false, vertical: true) } .background(theme.surface) .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .strokeBorder(theme.divider, lineWidth: 1) + ) + .contextMenu { + Button { + let pasteboard = pasteboard + let markdown = model.markdownText() + Task { @MainActor in pasteboard.copy(markdown) } + } label: { + Label("Copy as Markdown", systemImage: "doc.on.doc") + } + Button { + let pasteboard = pasteboard + let tsv = model.tsvText() + Task { @MainActor in pasteboard.copy(tsv) } + } label: { + Label("Copy as Plain Text", systemImage: "tablecells") + } + } + } + + private func cellView(_ cell: AttributedString, column: Int, header: Bool) -> some View { + let alignment = columnAlignment(column) + return MarkdownTableCellLayout(minWidth: Self.minimumColumnWidth, maxWidth: Self.maximumColumnWidth) { + SwiftUI.Text(hapiStyledText(cell, theme: theme, typography: typography)) + .fontWeight(header ? .semibold : nil) + .font(typography.bodyFont) + .foregroundStyle(theme.textPrimary) + .multilineTextAlignment(textAlignment(column)) + .frame(maxWidth: .infinity, alignment: Alignment(horizontal: alignment, vertical: .top)) + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + // Fill the row's height so header and stripe backgrounds stay + // even when a neighbouring cell wraps to more lines. + .frame(maxHeight: .infinity, alignment: .top) + .gridColumnAlignment(alignment) } private func columnAlignment(_ index: Int) -> HorizontalAlignment { @@ -663,6 +962,55 @@ struct MarkdownTableView: View { case .right: return .trailing } } + + private func textAlignment(_ index: Int) -> TextAlignment { + guard index < model.columnAlignments.count, let alignment = model.columnAlignments[index] else { + return .leading + } + switch alignment { + case .left: return .leading + case .center: return .center + case .right: return .trailing + } + } +} + +/// Sizes a table cell inside the horizontal scroll view: its one-line width +/// clamped to `minWidth...maxWidth` (or the column width the grid proposes), +/// with the height its text needs at exactly that width. +/// +/// `.frame(minWidth:maxWidth:)` cannot do this: under the scroll view's +/// unspecified proposal it reports the clamped width but the child's +/// unwrapped one-line height, so the grid sized rows for one line while the +/// text wrapped at `maxWidth` and spilled over the rows below. +struct MarkdownTableCellLayout: Layout { + let minWidth: CGFloat + let maxWidth: CGFloat + + private func width(_ proposal: ProposedViewSize, child: LayoutSubview) -> CGFloat { + let wanted: CGFloat + if let proposed = proposal.width, proposed.isFinite { + wanted = proposed + } else { + wanted = child.sizeThatFits(.unspecified).width + } + return min(max(wanted, minWidth), maxWidth) + } + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + guard let child = subviews.first else { return .zero } + let width = width(proposal, child: child) + let height = child.sizeThatFits(ProposedViewSize(width: width, height: nil)).height + return CGSize(width: width, height: ceil(height)) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + subviews.first?.place( + at: bounds.origin, + anchor: .topLeading, + proposal: ProposedViewSize(width: bounds.width, height: nil) + ) + } } struct MarkdownImageRow: View { diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownSelectionExtractor.swift b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownSelectionExtractor.swift new file mode 100644 index 00000000000..649ad322a44 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownSelectionExtractor.swift @@ -0,0 +1,243 @@ +import Foundation +import SwiftUI + +/// Platform-neutral metadata for a list item's visual marker and Markdown prefix, +/// attached as a custom `NSAttributedString` attribute so `ProseLayoutManager` +/// can draw markers outside the selectable text stream (no `•\t` copy pollution) +/// and `MarkdownSelectionExtractor` can reconstruct clean Markdown lists. +public struct ProseListMarkerInfo: Hashable, Sendable { + public let marker: String + public let markdownPrefix: String + public let indentLevel: Int + public let headIndent: CGFloat + /// Width of the marker column that ends at `headIndent`. + public let gutterWidth: CGFloat + /// Ordered numbers end just before the text instead of starting the gutter. + public let alignsTrailing: Bool + + public init(marker: String, markdownPrefix: String, indentLevel: Int, headIndent: CGFloat, + gutterWidth: CGFloat = 22, alignsTrailing: Bool = false) { + self.marker = marker + self.markdownPrefix = markdownPrefix + self.indentLevel = indentLevel + self.headIndent = headIndent + self.gutterWidth = gutterWidth + self.alignsTrailing = alignsTrailing + } +} + +public extension NSAttributedString.Key { + static let hapiListMarker = NSAttributedString.Key("hapi.markdown.listMarker") + static let hapiHeadingLevel = NSAttributedString.Key("hapi.markdown.headingLevel") + static let hapiInlineCode = NSAttributedString.Key("hapi.markdown.inlineCode") + static let hapiBold = NSAttributedString.Key("hapi.markdown.bold") + static let hapiItalic = NSAttributedString.Key("hapi.markdown.italic") + static let hapiStrikethrough = NSAttributedString.Key("hapi.markdown.strikethrough") +} + +/// Reconstructs clean Markdown (and clean plain text without list marker tabs) +/// from any selected range of an annotated `NSAttributedString` produced by +/// `ProseAttributedBuilder`. +public enum MarkdownSelectionExtractor { + /// Extract clean Markdown for `range` inside `attributed`. + public static func extractMarkdown(from attributed: NSAttributedString, range: NSRange) -> String { + let fullLength = attributed.length + guard fullLength > 0, range.location != NSNotFound, range.length > 0 else { return "" } + let clampedStart = min(max(0, range.location), fullLength) + let clampedEnd = min(fullLength, clampedStart + range.length) + guard clampedEnd > clampedStart else { return "" } + + let nsString = attributed.string as NSString + var outputLines: [(text: String, isListItem: Bool)] = [] + var cursor = clampedStart + + while cursor < clampedEnd { + let paragraphRange = nsString.paragraphRange(for: NSRange(location: cursor, length: 0)) + let paragraphContentEnd: Int + if paragraphRange.upperBound > paragraphRange.location, + nsString.character(at: paragraphRange.upperBound - 1) == 0x0A { + paragraphContentEnd = paragraphRange.upperBound - 1 + } else { + paragraphContentEnd = paragraphRange.upperBound + } + + let sliceStart = max(cursor, paragraphRange.location) + let sliceEnd = min(clampedEnd, paragraphContentEnd) + let startsAtParagraphStart = sliceStart == paragraphRange.location + + if sliceStart < sliceEnd { + let sliceRange = NSRange(location: sliceStart, length: sliceEnd - sliceStart) + var line = "" + var isListItem = false + + if startsAtParagraphStart { + if let level = attributed.attribute(.hapiHeadingLevel, at: sliceStart, effectiveRange: nil) as? Int, + (1...6).contains(level) { + line += String(repeating: "#", count: level) + " " + } else if let marker = attributed.attribute(.hapiListMarker, at: sliceStart, effectiveRange: nil) as? ProseListMarkerInfo { + let indentSpaces = String(repeating: " ", count: max(0, marker.indentLevel)) + line += indentSpaces + marker.markdownPrefix + isListItem = true + } + } + + line += serializeRuns(in: attributed, range: sliceRange) + outputLines.append((line, isListItem)) + } + + cursor = max(paragraphRange.upperBound, cursor + 1) + } + + var result = "" + for (idx, item) in outputLines.enumerated() { + if idx > 0 { + let prev = outputLines[idx - 1] + result += (prev.isListItem && item.isListItem) ? "\n" : "\n\n" + } + result += item.text + } + return result + } + + /// Plain text for `range`, guaranteed free of synthetic `•\t` characters + /// because list markers are drawn by `ProseLayoutManager`. + public static func extractPlainText(from attributed: NSAttributedString, range: NSRange) -> String { + let fullLength = attributed.length + guard fullLength > 0, range.location != NSNotFound, range.length > 0 else { return "" } + let clampedStart = min(max(0, range.location), fullLength) + let clampedEnd = min(fullLength, clampedStart + range.length) + guard clampedEnd > clampedStart else { return "" } + return (attributed.string as NSString).substring( + with: NSRange(location: clampedStart, length: clampedEnd - clampedStart) + ) + } + + /// Build a lightweight, platform-independent annotated `NSAttributedString` + /// from prose blocks (mirrors `ProseAttributedBuilder`'s metadata keys; used + /// directly in cross-platform unit tests). + public static func buildMetadataAttributedString(from blocks: [MarkdownBlockNode]) -> NSAttributedString { + let output = NSMutableAttributedString() + for block in blocks { + appendMetadata(block, level: 0, to: output) + } + return output + } + + private static func appendMetadata(_ block: MarkdownBlockNode, level: Int, to output: NSMutableAttributedString) { + switch block { + case .paragraph(let text): + appendParagraphMetadata(text, headingLevel: nil, listMarker: nil, to: output) + case .heading(let headingLevel, let text): + appendParagraphMetadata(text, headingLevel: headingLevel, listMarker: nil, to: output) + case .list(let model): + for (index, item) in model.items.enumerated() { + let marker = MarkdownPlainText.listMarker(model: model, item: item, index: index) + let mdPrefix = markdownListPrefix(model: model, item: item, index: index) + let markerInfo = ProseListMarkerInfo( + marker: marker, + markdownPrefix: mdPrefix, + indentLevel: level, + headIndent: CGFloat(level + 1) * 22 + ) + for (offset, child) in item.blocks.enumerated() { + if offset == 0, case .paragraph(let text) = child { + appendParagraphMetadata(text, headingLevel: nil, listMarker: markerInfo, to: output) + } else if case .list = child { + appendMetadata(child, level: level + 1, to: output) + } else if case .paragraph(let text) = child { + appendParagraphMetadata(text, headingLevel: nil, listMarker: nil, to: output) + } + } + } + default: + break + } + } + + static func markdownListPrefix(model: MarkdownListModel, item: MarkdownListModel.Item, index: Int) -> String { + if let checked = item.checkbox { + return checked ? "- [x] " : "- [ ] " + } + return model.isOrdered ? "\(model.startIndex + index). " : "- " + } + + private static func appendParagraphMetadata( + _ text: AttributedString, + headingLevel: Int?, + listMarker: ProseListMarkerInfo?, + to output: NSMutableAttributedString + ) { + if output.length > 0 { output.append(NSAttributedString(string: "\n")) } + let start = output.length + for run in text.runs { + let chunk = String(text[run.range].characters) + var attrs: [NSAttributedString.Key: Any] = [:] + let intent = run.inlinePresentationIntent ?? [] + if intent.contains(.code) { attrs[.hapiInlineCode] = true } + if intent.contains(.stronglyEmphasized) { attrs[.hapiBold] = true } + if intent.contains(.emphasized) { attrs[.hapiItalic] = true } + if intent.contains(.strikethrough) { attrs[.hapiStrikethrough] = true } + if let link = run.link { attrs[.link] = link } + output.append(NSAttributedString(string: chunk, attributes: attrs)) + } + let range = NSRange(location: start, length: output.length - start) + if range.length > 0 { + if let headingLevel { output.addAttribute(.hapiHeadingLevel, value: headingLevel, range: range) } + if let listMarker { output.addAttribute(.hapiListMarker, value: listMarker, range: range) } + } + } + + private static func serializeRuns(in attributed: NSAttributedString, range: NSRange) -> String { + var result = "" + attributed.enumerateAttributes(in: range, options: []) { attrs, runRange, _ in + let raw = (attributed.string as NSString).substring(with: runRange) + guard !raw.isEmpty else { return } + + let isCode = (attrs[.hapiInlineCode] as? Bool) == true + let isBold = (attrs[.hapiBold] as? Bool) == true + let isItalic = (attrs[.hapiItalic] as? Bool) == true + let isStrike = (attrs[.hapiStrikethrough] as? Bool) == true + let linkURL: URL? = (attrs[.link] as? URL) ?? (attrs[.link] as? String).flatMap(URL.init(string:)) + + var formatted = raw + if isCode { + formatted = wrapInlineCode(raw) + } else { + if isBold && isItalic { + formatted = "***\(formatted)***" + } else if isBold { + formatted = "**\(formatted)**" + } else if isItalic { + formatted = "*\(formatted)*" + } + if isStrike { + formatted = "~~\(formatted)~~" + } + } + + if let url = linkURL, + let scheme = url.scheme?.lowercased(), + scheme != FilePathLink.urlScheme, + scheme != SessionPathLink.urlScheme { + let target = url.absoluteString + // Avoid redundant `[https://x](https://x)` for bare autolinks. + if raw == target && !isCode && !isBold && !isItalic && !isStrike { + formatted = target + } else { + formatted = "[\(formatted)](\(target))" + } + } + result += formatted + } + return result + } + + private static func wrapInlineCode(_ code: String) -> String { + if !code.contains("`") { + return "`\(code)`" + } + let fence = "``" + let needsSpace = code.hasPrefix("`") || code.hasSuffix("`") + return needsSpace ? "\(fence) \(code) \(fence)" : "\(fence)\(code)\(fence)" + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownTransforms.swift b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownTransforms.swift index e1b0f6fb5d7..b96087fca60 100644 --- a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownTransforms.swift +++ b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/MarkdownTransforms.swift @@ -547,6 +547,80 @@ public enum MarkdownTransforms { guard shouldLinkPath(target) else { return nil } return FilePathLink(path: target, line: lineNumber(fromSuffixOf: withoutMeta)) } + + // MARK: - Session citation links (remark-session-path-links.ts + sessionReference.ts) + + private static let explicitSessionPathRegex = try! NSRegularExpression( + pattern: #"^(?:\.?/)?(?:[\w.-]+/)*sessions/([^/?#]+)/?$"# + ) + + private static let bareSessionPathRegex = try! NSRegularExpression( + pattern: #"(?:^|[\s(])((?:\.?/)?(?:[\w.-]+/)*sessions/[A-Za-z0-9_~%-]+)(?=[\s),;:!?]|$(?!\.)|(?=\.(?:[\s),;:!?]|$)))"# + ) + + /// Parse a session id from a relative `/sessions/` (or BASE_URL-prefixed) href + /// (`parseSessionPathHref`, `web/src/lib/sessionReference.ts`). + /// Rejects scheme-bearing URLs and dotted tails (e.g. `routes/sessions/chat.tsx`). + public static func sessionLinkTarget(forExplicitHref href: String) -> SessionPathLink? { + let trimmed = href.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, !HrefPolicy.hasScheme(trimmed) else { return nil } + guard let match = explicitSessionPathRegex.firstMatch(in: trimmed, range: fullRange(of: trimmed)), + let idRange = Range(match.range(at: 1), in: trimmed) + else { return nil } + guard let decoded = String(trimmed[idRange]).removingPercentEncoding, + !decoded.isEmpty, + !decoded.contains(".") + else { return nil } + return SessionPathLink(sessionId: decoded) + } + + /// Detect bare `/sessions/` citations in plain text (`remark-session-path-links.ts`). + /// Must run before `detectFilePathRanges` so session references take priority without + /// stealing dotted file paths like `web/src/routes/sessions/chat.tsx`. + public static func detectSessionPathRanges(in text: String) -> [(range: Range, link: SessionPathLink)] { + guard text.contains("sessions/") else { return [] } + var results: [(Range, SessionPathLink)] = [] + let matches = bareSessionPathRegex.matches(in: text, range: fullRange(of: text)) + for match in matches { + guard let pathRange = Range(match.range(at: 1), in: text) else { continue } + let path = String(text[pathRange]) + guard let link = sessionLinkTarget(forExplicitHref: path) else { continue } + results.append((pathRange, link)) + } + return results + } +} + +// MARK: - SessionPathLink + +/// A detected HAPI session citation (`/sessions/`), carried through +/// `AttributedString` link attributes as `hapi-session://?id=`. +public struct SessionPathLink: Equatable, Hashable, Sendable { + public var sessionId: String + + public init(sessionId: String) { + self.sessionId = sessionId + } + + public static let urlScheme = "hapi-session" + + public var url: URL? { + var components = URLComponents() + components.scheme = Self.urlScheme + components.host = "" + components.queryItems = [URLQueryItem(name: "id", value: sessionId)] + return components.url + } + + /// Parse a `hapi-session://?id=` URL back into a link. + public init?(url: URL) { + guard url.scheme?.lowercased() == Self.urlScheme else { return nil } + guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), + let id = components.queryItems?.first(where: { $0.name == "id" })?.value, + !id.isEmpty + else { return nil } + self.sessionId = id + } } // MARK: - FilePathLink diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/SelectableMarkdownText.swift b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/SelectableMarkdownText.swift new file mode 100644 index 00000000000..6ebb7b5c2c7 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/SelectableMarkdownText.swift @@ -0,0 +1,500 @@ +import SwiftUI +#if canImport(UIKit) +import UIKit +import UniformTypeIdentifiers +#endif + +// MARK: - Segmenting + +/// A rendered stretch of a block list: consecutive prose blocks (paragraphs, +/// headings, prose-only lists) are merged into one selectable text view so a +/// selection can span paragraphs; everything else keeps its own view. +enum MarkdownSegment: Equatable { + case text([MarkdownBlockNode]) + case block(MarkdownBlockNode) + + var first: MarkdownBlockNode? { + switch self { + case .text(let blocks): blocks.first + case .block(let block): block + } + } + + var last: MarkdownBlockNode? { + switch self { + case .text(let blocks): blocks.last + case .block(let block): block + } + } + + static func segments(of blocks: [MarkdownBlockNode]) -> [MarkdownSegment] { + var output: [MarkdownSegment] = [] + var run: [MarkdownBlockNode] = [] + for block in blocks { + if isProse(block) { + run.append(block) + } else { + if !run.isEmpty { output.append(.text(run)); run = [] } + output.append(.block(block)) + } + } + if !run.isEmpty { output.append(.text(run)) } + return output + } + + /// Blocks the attributed-string builder can lay out faithfully. + static func isProse(_ block: MarkdownBlockNode) -> Bool { + switch block { + case .paragraph, .heading: true + case .list(let model): model.items.allSatisfy { $0.blocks.allSatisfy(isProse) } + default: false + } + } +} + +// MARK: - Plain text + +/// Plain-text rendering of a block tree, used by copy actions. +public enum MarkdownPlainText { + public static func text(of blocks: [MarkdownBlockNode]) -> String { + blocks.map(text(of:)).filter { !$0.isEmpty }.joined(separator: "\n\n") + } + + static func text(of block: MarkdownBlockNode) -> String { + switch block { + case .paragraph(let text), .heading(_, let text): + return String(text.characters) + case .codeBlock(_, let code): + return code + case .blockquote(let children): + return text(of: children) + case .admonition(let kind, let children): + let body = text(of: children) + return body.isEmpty ? kind.title : "\(kind.title): \(body)" + case .list(let model): + return model.items.enumerated().map { index, item in + let marker = listMarker(model: model, item: item, index: index) + let body = text(of: item.blocks) + .split(separator: "\n", omittingEmptySubsequences: false) + .enumerated() + .map { $0.offset == 0 ? String($0.element) : " " + $0.element } + .joined(separator: "\n") + return "\(marker) \(body)" + }.joined(separator: "\n") + case .table(let model): + let rows = [model.header] + model.rows + return rows.map { $0.map { String($0.characters) }.joined(separator: "\t") }.joined(separator: "\n") + case .thematicBreak: + return "---" + case .image(let alt, let destination): + return alt.isEmpty ? (destination ?? "") : alt + } + } + + static func listMarker(model: MarkdownListModel, item: MarkdownListModel.Item, index: Int) -> String { + if let checked = item.checkbox { return checked ? "☑" : "☐" } + return model.isOrdered ? "\(model.startIndex + index)." : "•" + } +} + +#if canImport(UIKit) + +// MARK: - Attributed string + +/// Builds the UIKit attributed string for a prose run, mirroring the +/// SwiftUI renderer's fonts, colors and block spacing. List markers are stored +/// as `.hapiListMarker` metadata and drawn in the margin by `ProseLayoutManager` +/// instead of being injected as `"•\t"` into the text buffer. +struct ProseAttributedBuilder { + let theme: HapiTheme + let typography: HapiTypography + + private var regularWeight: UIFont.Weight { typography.boldText ? .semibold : .regular } + /// Minimum marker gutter: bullets and checkboxes sit at its leading edge. + static let listIndent: CGFloat = 22 + /// Space between a trailing-aligned number (`10.`) and its text. + static let markerGap: CGFloat = 6 + + /// The font `ProseLayoutManager` draws markers with; gutters are sized with it. + static func markerFont(_ typography: HapiTypography) -> UIFont { + .monospacedDigitSystemFont(ofSize: typography.bodySize, weight: typography.boldText ? .semibold : .regular) + } + + func build(_ blocks: [MarkdownBlockNode]) -> NSAttributedString { + let output = NSMutableAttributedString() + var previous: MarkdownBlockNode? + for block in blocks { + append(block, after: previous, level: 0, indent: 0, to: output) + previous = block + } + return output + } + + /// The gutter widens to fit the list's widest marker, so `10.` or a + /// checkbox at accessibility sizes never runs into the text the way a + /// fixed 22 pt gutter let them. + private func gutterWidth(for model: MarkdownListModel) -> CGFloat { + let attributes: [NSAttributedString.Key: Any] = [.font: Self.markerFont(typography)] + let markers = Set(model.items.enumerated().map { index, item in + MarkdownPlainText.listMarker(model: model, item: item, index: index) + }) + let widest = markers.map { ($0 as NSString).size(withAttributes: attributes).width }.max() ?? 0 + return max(Self.listIndent, ceil(widest) + Self.markerGap) + } + + private func append(_ block: MarkdownBlockNode, after previous: MarkdownBlockNode?, + level: Int, indent: CGFloat, to output: NSMutableAttributedString) { + let spacing = MarkdownBlockListView.spacing(before: block, after: previous) + switch block { + case .paragraph(let text): + appendParagraph(text, size: typography.bodySize, weight: regularWeight, + spacingBefore: spacing, indent: indent, + headingLevel: nil, listMarker: nil, to: output) + case .heading(let headingLevel, let text): + appendParagraph(text, size: typography.headingSize(headingLevel), + weight: typography.boldText ? .bold : .semibold, + spacingBefore: spacing, indent: 0, + headingLevel: headingLevel, listMarker: nil, to: output) + case .list(let model): + let gutter = gutterWidth(for: model) + let contentIndent = indent + gutter + for (index, item) in model.items.enumerated() { + let marker = MarkdownPlainText.listMarker(model: model, item: item, index: index) + let mdPrefix = MarkdownSelectionExtractor.markdownListPrefix(model: model, item: item, index: index) + let markerInfo = ProseListMarkerInfo( + marker: marker, + markdownPrefix: mdPrefix, + indentLevel: level, + headIndent: contentIndent, + gutterWidth: gutter, + alignsTrailing: model.isOrdered && item.checkbox == nil + ) + var itemPrevious: MarkdownBlockNode? + for (offset, child) in item.blocks.enumerated() { + let childSpacing: CGFloat = offset == 0 + ? (index == 0 ? spacing : 8) + : MarkdownBlockListView.spacing(before: child, after: itemPrevious) + if offset == 0, case .paragraph(let text) = child { + appendParagraph(text, size: typography.bodySize, weight: regularWeight, + spacingBefore: childSpacing, indent: contentIndent, + headingLevel: nil, listMarker: markerInfo, to: output) + } else if case .list = child { + // The nested list starts after the "\n" its first paragraph + // appends. Pointing at that separator would resolve to the + // parent paragraph and copy the child's indent onto it. + let start = output.length > 0 ? output.length + 1 : 0 + append(child, after: offset == 0 ? nil : itemPrevious, + level: level + 1, indent: contentIndent, to: output) + adjustSpacing(of: output, at: start, to: childSpacing) + } else { + appendParagraph(plainParagraph(child), size: typography.bodySize, weight: regularWeight, + spacingBefore: childSpacing, indent: contentIndent, + headingLevel: nil, listMarker: offset == 0 ? markerInfo : nil, to: output) + } + itemPrevious = child + } + } + default: + break + } + } + + private func plainParagraph(_ block: MarkdownBlockNode) -> AttributedString { + switch block { + case .paragraph(let text), .heading(_, let text): text + default: AttributedString(MarkdownPlainText.text(of: block)) + } + } + + private func adjustSpacing(of output: NSMutableAttributedString, at location: Int, to spacing: CGFloat) { + guard location < output.length, + let style = output.attribute(.paragraphStyle, at: location, effectiveRange: nil) as? NSParagraphStyle, + let copy = style.mutableCopy() as? NSMutableParagraphStyle else { return } + copy.paragraphSpacingBefore = output.length > 0 && location == 0 ? 0 : spacing + let range = (output.string as NSString).paragraphRange(for: NSRange(location: location, length: 0)) + output.addAttribute(.paragraphStyle, value: copy, range: range) + } + + private func appendParagraph(_ text: AttributedString, size: CGFloat, weight: UIFont.Weight, + spacingBefore: CGFloat, indent: CGFloat, + headingLevel: Int?, listMarker: ProseListMarkerInfo?, + to output: NSMutableAttributedString) { + let style = NSMutableParagraphStyle() + style.lineSpacing = typography.bodyLineSpacing + style.paragraphSpacingBefore = output.length == 0 ? 0 : spacingBefore + // Markers are drawn in the leading gutter by ProseLayoutManager, so both + // firstLineHeadIndent and headIndent align cleanly at `indent`. + style.firstLineHeadIndent = indent + style.headIndent = indent + + let baseFont = UIFont.systemFont(ofSize: size, weight: weight) + let primary = UIColor(theme.textPrimary) + let paragraph = NSMutableAttributedString() + for run in text.runs { + let string = String(text[run.range].characters) + var attributes: [NSAttributedString.Key: Any] = [.foregroundColor: primary] + let intent = run.inlinePresentationIntent ?? [] + if intent.contains(.code) { + attributes[.font] = UIFont.monospacedSystemFont(ofSize: typography.inlineCodeSize * size / typography.bodySize, + weight: weight) + attributes[.foregroundColor] = UIColor(theme.inlineCodeForeground) + attributes[.backgroundColor] = UIColor(theme.inlineCodeBackground) + attributes[.hapiInlineCode] = true + } else { + let isBold = intent.contains(.stronglyEmphasized) + let isItalic = intent.contains(.emphasized) + attributes[.font] = font(base: baseFont, size: size, weight: weight, + bold: isBold, italic: isItalic) + if isBold { attributes[.hapiBold] = true } + if isItalic { attributes[.hapiItalic] = true } + } + if intent.contains(.strikethrough) { + attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue + attributes[.hapiStrikethrough] = true + } + if let link = run.link { + attributes[.link] = link + } + paragraph.append(NSAttributedString(string: string, attributes: attributes)) + } + if output.length > 0 { output.append(NSAttributedString(string: "\n")) } + let start = output.length + output.append(paragraph) + let paragraphContentRange = NSRange(location: start, length: output.length - start) + let styleRange = NSRange(location: max(0, start - 1), length: output.length - max(0, start - 1)) + output.addAttribute(.paragraphStyle, value: style, range: styleRange) + if paragraphContentRange.length > 0 { + if let headingLevel { + output.addAttribute(.hapiHeadingLevel, value: headingLevel, range: paragraphContentRange) + } + if let listMarker { + output.addAttribute(.hapiListMarker, value: listMarker, range: paragraphContentRange) + } + } + } + + private func font(base: UIFont, size: CGFloat, weight: UIFont.Weight, bold: Bool, italic: Bool) -> UIFont { + var font = bold ? UIFont.systemFont(ofSize: size, weight: weight == .regular ? .bold : .heavy) : base + if italic, let descriptor = font.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits.union(.traitItalic)) { + font = UIFont(descriptor: descriptor, size: size) + } + return font + } +} + +// MARK: - Layout manager (draws list markers outside selectable text) + +private final class ProseLayoutManager: NSLayoutManager { + var markerFont: UIFont = .monospacedDigitSystemFont(ofSize: 15, weight: .regular) + var markerColor: UIColor = .secondaryLabel + + override func drawGlyphs(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) { + super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin) + guard let storage = textStorage, storage.length > 0 else { return } + + let charRange = characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil) + guard charRange.location != NSNotFound, charRange.length > 0 else { return } + let nsString = storage.string as NSString + + storage.enumerateAttribute(.hapiListMarker, in: charRange, options: []) { value, attrRange, _ in + guard let info = value as? ProseListMarkerInfo else { return } + let paragraphRange = nsString.paragraphRange(for: NSRange(location: attrRange.location, length: 0)) + // Draw once at the paragraph's opening line fragment. + guard attrRange.location == paragraphRange.location else { return } + let glyphIndex = glyphIndexForCharacter(at: paragraphRange.location) + guard glyphIndex < numberOfGlyphs else { return } + + let lineRect = lineFragmentRect(forGlyphAt: glyphIndex, effectiveRange: nil) + let glyphLoc = location(forGlyphAt: glyphIndex) + let baselineY = origin.y + lineRect.minY + glyphLoc.y + let drawY = baselineY - markerFont.ascender + + let markerAttrs: [NSAttributedString.Key: Any] = [ + .font: markerFont, + .foregroundColor: markerColor, + ] + let marker = info.marker as NSString + // Numbers end a fixed gap before the text so `9.` and `10.` share + // their dot column; bullets and checkboxes start the gutter. + let markerX = info.alignsTrailing + ? info.headIndent - ProseAttributedBuilder.markerGap - marker.size(withAttributes: markerAttrs).width + : info.headIndent - info.gutterWidth + marker.draw(at: CGPoint(x: origin.x + max(0, markerX), y: drawY), withAttributes: markerAttrs) + } + } +} + +// MARK: - Multi-format pasteboard writer + +private enum ProsePasteboardWriter { + @MainActor + static func copyRichSelection(_ attributed: NSAttributedString, range: NSRange) { + guard range.location != NSNotFound, range.length > 0, + range.location + range.length <= attributed.length else { return } + let plain = MarkdownSelectionExtractor.extractPlainText(from: attributed, range: range) + let sub = attributed.attributedSubstring(from: range) + var item: [String: Any] = [UTType.plainText.identifier: plain] + let subFull = NSRange(location: 0, length: sub.length) + if let rtf = try? sub.data(from: subFull, documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]) { + item[UTType.rtf.identifier] = rtf + } + if let html = try? sub.data(from: subFull, documentAttributes: [.documentType: NSAttributedString.DocumentType.html]) { + item[UTType.html.identifier] = html + } + UIPasteboard.general.setItems([item]) + #if !targetEnvironment(macCatalyst) + UIImpactFeedbackGenerator(style: .light).impactOccurred() + #endif + } + + @MainActor + static func copyMarkdownSelection(_ attributed: NSAttributedString, range: NSRange) { + let markdown = MarkdownSelectionExtractor.extractMarkdown(from: attributed, range: range) + guard !markdown.isEmpty else { return } + UIPasteboard.general.string = markdown + #if !targetEnvironment(macCatalyst) + UIImpactFeedbackGenerator(style: .light).impactOccurred() + #endif + } +} + +// MARK: - Text view subclass + +private final class ProseTextView: UITextView { + let proseLayoutManager: ProseLayoutManager + private let proseTextStorage: NSTextStorage + + init() { + let storage = NSTextStorage() + let layoutManager = ProseLayoutManager() + let container = NSTextContainer(size: CGSize(width: 0, height: CGFloat.greatestFiniteMagnitude)) + container.lineFragmentPadding = 0 + layoutManager.addTextContainer(container) + storage.addLayoutManager(layoutManager) + self.proseTextStorage = storage + self.proseLayoutManager = layoutManager + super.init(frame: .zero, textContainer: container) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func copy(_ sender: Any?) { + let range = selectedRange + if range.length > 0, let attributed = attributedText { + ProsePasteboardWriter.copyRichSelection(attributed, range: range) + } else { + super.copy(sender) + } + } +} + +// MARK: - View + +/// Read-only, selectable prose. Unlike `Text.textSelection`, a selection +/// here spans every paragraph of the run, survives unrelated re-renders, +/// draws list markers cleanly via `NSLayoutManager`, and offers rich Copy +/// (Plain + RTF + HTML) plus `Copy as Markdown` in the selection edit menu. +struct SelectableProseView: UIViewRepresentable { + let blocks: [MarkdownBlockNode] + @Environment(\.hapiTheme) private var theme + @Environment(\.hapiTypography) private var typography + @Environment(\.hapiOpenURL) private var hapiOpenURL + + final class Coordinator: NSObject, UITextViewDelegate { + var open: (URL) -> Void = { _ in } + var rendered: NSAttributedString? + + func textView(_ textView: UITextView, primaryActionFor textItem: UITextItem, + defaultAction: UIAction) -> UIAction? { + guard case .link(let url) = textItem.content else { return defaultAction } + let open = open + return UIAction { _ in open(url) } + } + + func textView( + _ textView: UITextView, + editMenuForTextIn range: NSRange, + suggestedActions: [UIMenuElement] + ) -> UIMenu? { + guard range.length > 0, let attributed = textView.attributedText else { + return UIMenu(children: suggestedActions) + } + let copyRich = UIAction(title: String(localized: "Copy"), image: UIImage(systemName: "doc.on.doc")) { _ in + ProsePasteboardWriter.copyRichSelection(attributed, range: range) + } + let copyMarkdown = UIAction( + title: String(localized: "Copy as Markdown"), + image: UIImage(systemName: "doc.plaintext") + ) { _ in + ProsePasteboardWriter.copyMarkdownSelection(attributed, range: range) + } + + // Replace system Copy with our multi-format Copy + Copy as Markdown, + // keeping Look Up / Translate / Share / etc. intact. + var filtered: [UIMenuElement] = [] + var inserted = false + for element in suggestedActions { + if let menu = element as? UIMenu, menu.identifier == .standardEdit { + var children = menu.children.filter { + ($0 as? UIAction)?.identifier != UIAction.Identifier("com.apple.menu.copy") + } + children.insert(contentsOf: [copyRich, copyMarkdown], at: 0) + filtered.append(menu.replacingChildren(children)) + inserted = true + } else { + filtered.append(element) + } + } + if !inserted { + filtered.insert(contentsOf: [copyRich, copyMarkdown], at: 0) + } + return UIMenu(children: filtered) + } + } + + func makeCoordinator() -> Coordinator { Coordinator() } + + func makeUIView(context: Context) -> UITextView { + let view = ProseTextView() + view.isEditable = false + view.isSelectable = true + view.isScrollEnabled = false + view.backgroundColor = .clear + view.textContainerInset = .zero + view.textContainer.lineFragmentPadding = 0 + view.dataDetectorTypes = [] + view.delegate = context.coordinator + view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + view.setContentHuggingPriority(.defaultHigh, for: .vertical) + return view + } + + func updateUIView(_ view: UITextView, context: Context) { + let open = hapiOpenURL + context.coordinator.open = { open($0) } + view.linkTextAttributes = [ + .foregroundColor: UIColor(theme.link), + .underlineStyle: NSUnderlineStyle.single.rawValue, + ] + if let proseView = view as? ProseTextView { + proseView.proseLayoutManager.markerFont = ProseAttributedBuilder.markerFont(typography) + proseView.proseLayoutManager.markerColor = UIColor(theme.textHint) + } + let text = ProseAttributedBuilder(theme: theme, typography: typography).build(blocks) + // Re-assigning identical text would drop the reader's selection. + if context.coordinator.rendered?.isEqual(to: text) != true { + context.coordinator.rendered = text + view.attributedText = text + } + } + + func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextView, context: Context) -> CGSize? { + let width = proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10_000 + let fitted = uiView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)) + return CGSize(width: width, height: ceil(fitted.height)) + } +} +#endif diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Markdown/StreamingMarkdownSplitter.swift b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/StreamingMarkdownSplitter.swift new file mode 100644 index 00000000000..6421efe897b --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Markdown/StreamingMarkdownSplitter.swift @@ -0,0 +1,196 @@ +import Foundation + +/// Pure streaming markdown utilities: +/// 1. Detects unclosed fenced code blocks so syntax highlighting can wait until +/// the fence closes (avoiding per-token highlighter churn). +/// 2. Finds safe top-level block boundaries so a growing streaming reply can +/// seal closed prefix blocks once and only re-parse the small active tail, +/// turning O(N²) streaming parses into O(tail). +public enum StreamingMarkdownSplitter { + private struct FenceState { + let character: Character + let length: Int + } + + /// True when `markdown` ends inside an unclosed `` ``` `` or `~~~` fence. + public static func hasUnclosedCodeFence(_ markdown: String) -> Bool { + var openFence: FenceState? + for rawLine in markdown.split(separator: "\n", omittingEmptySubsequences: false) { + let line = rawLine.hasSuffix("\r") ? rawLine.dropLast() : rawLine + updateFenceState(&openFence, line: line) + } + return openFence != nil + } + + /// True when `markdown` contains no document-wide constructs (reference link + /// definitions or raw HTML block openers) that can retroactively change the + /// meaning of earlier blocks. + public static func canSplitIncrementally(_ markdown: String) -> Bool { + var openFence: FenceState? + for rawLine in markdown.split(separator: "\n", omittingEmptySubsequences: false) { + let line = rawLine.hasSuffix("\r") ? rawLine.dropLast() : rawLine + let wasInFence = openFence != nil + updateFenceState(&openFence, line: line) + if wasInFence || openFence != nil { continue } + if isReferenceDefinition(line) || isHTMLBlockOpener(line) { + return false + } + } + return true + } + + /// Returns a safe UTF-8 byte offset `> startByteOffset` where closed top-level + /// blocks can be sealed and parsed independently of the active tail, or `nil` + /// if no safe boundary has been reached yet. + /// + /// Guarantees: + /// - Never splits inside a fenced code block. + /// - Never splits immediately before an indented line, list item, blockquote, + /// table line, or Setext underline (preserving loose lists and continuations). + /// - Always leaves at least the final non-blank top-level block in the tail. + /// - Bails out (`nil`) if reference link definitions or raw HTML blocks appear. + public static func safeSealOffset( + in markdown: String, + from startByteOffset: Int = 0, + minimumChunkBytes: Int = 1_024 + ) -> Int? { + let utf8 = markdown.utf8 + guard startByteOffset >= 0, startByteOffset < utf8.count else { return nil } + guard canSplitIncrementally(markdown) else { return nil } + + let startIndex = utf8.index(utf8.startIndex, offsetBy: startByteOffset) + let slice = markdown[startIndex...] + + var openFence: FenceState? + var pendingBlankEndOffset: Int? + var closedFenceBeforeBlank = false + var bestSealOffset: Int? + + var lineStart = slice.startIndex + while lineStart < slice.endIndex { + let newlineIndex = slice[lineStart...].firstIndex(of: "\n") + let lineEnd = newlineIndex ?? slice.endIndex + let nextLineStart = newlineIndex.map { slice.index(after: $0) } ?? slice.endIndex + let rawLine = slice[lineStart.. slice.startIndex { + let candidate = utf8.distance(from: utf8.startIndex, to: nextLineStart) + if candidate > startByteOffset { + pendingBlankEndOffset = candidate + } + } + } else { + if let candidate = pendingBlankEndOffset { + let chunkSize = candidate - startByteOffset + let meetsSize = chunkSize >= minimumChunkBytes || closedFenceBeforeBlank + if meetsSize && isFreshIndependentBlockStart(line) { + bestSealOffset = candidate + } + pendingBlankEndOffset = nil + closedFenceBeforeBlank = false + } + if justClosedFence { + closedFenceBeforeBlank = true + } + } + } else { + pendingBlankEndOffset = nil + closedFenceBeforeBlank = false + } + + lineStart = nextLineStart + } + + return bestSealOffset + } + + // MARK: - Line classifiers + + private static func updateFenceState(_ openFence: inout FenceState?, line: Substring) { + let (leadingSpaces, rest) = stripUpToThreeLeadingSpaces(line) + guard leadingSpaces <= 3, let first = rest.first, first == "`" || first == "~" else { return } + var runLength = 0 + for ch in rest { + if ch == first { runLength += 1 } else { break } + } + guard runLength >= 3 else { return } + let trailing = rest.dropFirst(runLength) + + if let current = openFence { + if current.character == first, runLength >= current.length, + trailing.allSatisfy({ $0 == " " || $0 == "\t" }) { + openFence = nil + } + } else { + // Backtick info strings cannot contain backticks (CommonMark §4.5). + if first == "`", trailing.contains("`") { return } + openFence = FenceState(character: first, length: runLength) + } + } + + private static func stripUpToThreeLeadingSpaces(_ line: Substring) -> (Int, Substring) { + var count = 0 + var idx = line.startIndex + while idx < line.endIndex && line[idx] == " " && count < 4 { + count += 1 + idx = line.index(after: idx) + } + return (count, line[idx...]) + } + + private static func isBlank(_ line: Substring) -> Bool { + line.allSatisfy { $0 == " " || $0 == "\t" } + } + + private static func isReferenceDefinition(_ line: Substring) -> Bool { + let (spaces, rest) = stripUpToThreeLeadingSpaces(line) + guard spaces <= 3, rest.first == "[" else { return false } + guard let close = rest.firstIndex(of: "]") else { return false } + let afterClose = rest.index(after: close) + return afterClose < rest.endIndex && rest[afterClose] == ":" + } + + private static func isHTMLBlockOpener(_ line: Substring) -> Bool { + let (spaces, rest) = stripUpToThreeLeadingSpaces(line) + guard spaces <= 3, rest.first == "<" else { return false } + guard rest.count >= 2 else { return false } + let second = rest[rest.index(after: rest.startIndex)] + return second.isASCII && (second.isLetter || second == "!" || second == "?" || second == "/") + } + + /// Conservative check: returns true only when `line` starts a fresh top-level + /// block that cannot continue a prior list, blockquote, table, or Setext heading. + private static func isFreshIndependentBlockStart(_ line: Substring) -> Bool { + guard let first = line.first else { return false } + // Indented lines might continue a loose list item. + if first == " " || first == "\t" { return false } + // Blockquotes or table rows. + if first == ">" || first == "|" { return false } + // Unordered list markers or thematic break / Setext underline (`-`, `*`, `+`, `=`). + if first == "-" || first == "*" || first == "+" || first == "=" { return false } + // Ordered list markers (`1. ` or `1) `). + if first.isASCII && first.isNumber { + var idx = line.startIndex + var digits = 0 + while idx < line.endIndex && line[idx].isASCII && line[idx].isNumber && digits < 10 { + digits += 1 + idx = line.index(after: idx) + } + if idx < line.endIndex && (line[idx] == "." || line[idx] == ")") { + let after = line.index(after: idx) + if after == line.endIndex || line[after] == " " || line[after] == "\t" { + return false + } + } + } + return true + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Media/ZoomableImageView.swift b/ios/Packages/HapiKit/Sources/HapiUI/Media/ZoomableImageView.swift new file mode 100644 index 00000000000..2f47f53b24a --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Media/ZoomableImageView.swift @@ -0,0 +1,138 @@ +#if canImport(UIKit) +import SwiftUI +import UIKit + +/// Full-screen image viewer with pinch-to-zoom, double-tap zoom and pan. +/// A single tap no longer dismisses (it would fight the zoom gestures); +/// the close button does. +public struct HapiImageViewer: View { + public let image: UIImage? + public let title: String + @Environment(\.dismiss) private var dismiss + + public init(image: UIImage?, title: String) { + self.image = image + self.title = title + } + + public var body: some View { + ZStack(alignment: .topTrailing) { + Color.black.ignoresSafeArea() + if let image { + ZoomableImageView(image: image) + .ignoresSafeArea() + .accessibilityLabel(Text(verbatim: title)) + } else { + Text(verbatim: title) + .foregroundStyle(.white) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + Button { dismiss() } label: { + Image(systemName: "xmark.circle.fill") + .font(.title2) + .foregroundStyle(.white.opacity(0.8)) + .padding(16) + } + .accessibilityLabel(Text("Close")) + } + } +} + +/// `UIScrollView`-backed zoom: native pinch/pan physics and bounce, +/// which SwiftUI magnify gestures do not give for free. +public struct ZoomableImageView: UIViewRepresentable { + public let image: UIImage + public var maximumZoomScale: CGFloat = 6 + + public init(image: UIImage, maximumZoomScale: CGFloat = 6) { + self.image = image + self.maximumZoomScale = maximumZoomScale + } + + public func makeUIView(context: Context) -> ZoomingScrollView { + let view = ZoomingScrollView() + view.maximumZoomScale = maximumZoomScale + view.setImage(image) + return view + } + + public func updateUIView(_ view: ZoomingScrollView, context: Context) { + view.maximumZoomScale = maximumZoomScale + if view.image !== image { view.setImage(image) } + } +} + +public final class ZoomingScrollView: UIScrollView, UIScrollViewDelegate { + private let imageView = UIImageView() + private var laidOutSize: CGSize = .zero + var image: UIImage? { imageView.image } + + override init(frame: CGRect) { + super.init(frame: frame) + delegate = self + backgroundColor = .clear + showsVerticalScrollIndicator = false + showsHorizontalScrollIndicator = false + contentInsetAdjustmentBehavior = .never + decelerationRate = .fast + minimumZoomScale = 1 + imageView.contentMode = .scaleAspectFit + imageView.isUserInteractionEnabled = true + addSubview(imageView) + let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:))) + doubleTap.numberOfTapsRequired = 2 + addGestureRecognizer(doubleTap) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + func setImage(_ image: UIImage) { + imageView.image = image + laidOutSize = .zero + setNeedsLayout() + } + + public override func layoutSubviews() { + super.layoutSubviews() + guard bounds.size != laidOutSize, bounds.width > 0, bounds.height > 0 else { + centerImage() + return + } + laidOutSize = bounds.size + zoomScale = 1 + imageView.frame = CGRect(origin: .zero, size: fittedSize()) + contentSize = imageView.frame.size + centerImage() + } + + /// Aspect-fit size of the image at zoom scale 1. + private func fittedSize() -> CGSize { + guard let image = imageView.image, image.size.width > 0, image.size.height > 0 else { return bounds.size } + let scale = min(bounds.width / image.size.width, bounds.height / image.size.height) + return CGSize(width: image.size.width * scale, height: image.size.height * scale) + } + + private func centerImage() { + let horizontal = max(0, (bounds.width - contentSize.width) / 2) + let vertical = max(0, (bounds.height - contentSize.height) / 2) + contentInset = UIEdgeInsets(top: vertical, left: horizontal, bottom: vertical, right: horizontal) + } + + @objc private func handleDoubleTap(_ recognizer: UITapGestureRecognizer) { + if zoomScale > minimumZoomScale + 0.01 { + setZoomScale(minimumZoomScale, animated: true) + return + } + let target = min(maximumZoomScale, 2.5) + let point = recognizer.location(in: imageView) + let size = CGSize(width: bounds.width / target, height: bounds.height / target) + zoom(to: CGRect(x: point.x - size.width / 2, y: point.y - size.height / 2, + width: size.width, height: size.height), animated: true) + } + + public func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView } + + public func scrollViewDidZoom(_ scrollView: UIScrollView) { centerImage() } +} +#endif diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Terminal/CoreTextTerminalView.swift b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/CoreTextTerminalView.swift new file mode 100644 index 00000000000..d06323919d4 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/CoreTextTerminalView.swift @@ -0,0 +1,997 @@ +#if canImport(UIKit) +import CoreGraphics +import CoreText +import SwiftUI +import UIKit + +/// Native 60/120fps CoreText terminal view (`UIView` + `UIKeyInput` + `UIEditMenuInteraction`). +/// +/// Renders directly from `TerminalEmulator` using whole-pixel monospaced `CTFont` +/// grid geometry, per-row `CTLine` shaping with `kCTWritingDirectionOverride` +/// (prevents Bidi column corruption), contiguous background run coalescing, +/// vector `CGPath` box-drawing/block glyphs, dirty-row invalidation, smooth +/// scrollback panning, long-press text selection, hardware keyboard support, +/// and lazy VoiceOver row accessibility elements. +public final class CoreTextTerminalCanvasView: UIView, UIKeyInput, @MainActor UIEditMenuInteractionDelegate { + private static let ltrBidiOverride: [NSNumber] = [ + NSNumber(value: NSWritingDirection.leftToRight.rawValue | NSWritingDirectionFormatType.override.rawValue) + ] + // MARK: - State & Callbacks + + public var emulator: TerminalEmulator { + didSet { + scrollOffsetFromBottom = 0 + selection = nil + invalidateAccessibility() + setNeedsDisplay() + } + } + + public var palette: TerminalPalette = .forTheme(.dark) { + didSet { + guard palette != oldValue else { return } + emulator.palette = palette + backgroundColor = UIColor(cgColor: palette.background.cgColor) + setNeedsDisplay() + } + } + + public var fontSize: CGFloat = 13 { + didSet { + let clamped = max(9, min(24, fontSize)) + if clamped != fontSize { + fontSize = clamped + return + } + guard fontSize != oldValue else { return } + rebuildFontMetrics() + reportGridSizeIfNeeded() + setNeedsDisplay() + } + } + + /// Number of lines scrolled UP into scrollback (`0` = pinned to live bottom). + public private(set) var scrollOffsetFromBottom: Int = 0 { + didSet { + if scrollOffsetFromBottom != oldValue { + onScrollOffsetChange?(scrollOffsetFromBottom) + invalidateAccessibility() + setNeedsDisplay() + } + } + } + + public var onInput: ((String) -> Void)? + public var onPaste: ((String) -> Void)? + public var onGridSizeChange: ((Int, Int) -> Void)? + public var onScrollOffsetChange: ((Int) -> Void)? + public var onSendExcerpt: ((String) -> Void)? + public var onFontSizeChange: ((CGFloat) -> Void)? + public var onFocusChange: ((Bool) -> Void)? + + // MARK: - Internals + + private static let horizontalInset: CGFloat = 6 + private static let verticalInset: CGFloat = 4 + + private var metrics: TerminalGridMetrics + private var regularFont: CTFont + private var boldFont: CTFont + private var italicFont: CTFont + private var boldItalicFont: CTFont + + private var lastReportedGrid: (cols: Int, rows: Int) = (0, 0) + private var lastRenderedGeneration: UInt64 = 0 + + private var selection: TerminalSelection? { + didSet { + if selection != oldValue { setNeedsDisplay() } + } + } + + private var panAccumulatedY: CGFloat = 0 + private var pinchBaseFontSize: CGFloat = 13 + private var editMenuInteraction: UIEditMenuInteraction? + private var cachedAccessibilityElements: [Any]? + + private var cursorBlinkOn: Bool = true + private var cursorBlinkTask: Task? + + // MARK: - Init + + public init(emulator: TerminalEmulator, palette: TerminalPalette = .forTheme(.dark), fontSize: CGFloat = 13) { + self.emulator = emulator + self.palette = palette + self.fontSize = max(9, min(24, fontSize)) + let initialScale: CGFloat = 2.0 + self.metrics = TerminalGridMetrics(fontSize: self.fontSize, scale: initialScale) + self.regularFont = TerminalGridMetrics.makeFont(size: self.fontSize, bold: false, italic: false) + self.boldFont = TerminalGridMetrics.makeFont(size: self.fontSize, bold: true, italic: false) + self.italicFont = TerminalGridMetrics.makeFont(size: self.fontSize, bold: false, italic: true) + self.boldItalicFont = TerminalGridMetrics.makeFont(size: self.fontSize, bold: true, italic: true) + super.init(frame: .zero) + + isOpaque = true + contentMode = .redraw + backgroundColor = UIColor(cgColor: palette.background.cgColor) + isMultipleTouchEnabled = true + + let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) + addGestureRecognizer(tap) + + let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) + pan.maximumNumberOfTouches = 1 + addGestureRecognizer(pan) + + let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:))) + longPress.minimumPressDuration = 0.32 + addGestureRecognizer(longPress) + + let pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:))) + addGestureRecognizer(pinch) + + let editMenu = UIEditMenuInteraction(delegate: self) + addInteraction(editMenu) + self.editMenuInteraction = editMenu + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + public override func didMoveToWindow() { + super.didMoveToWindow() + if window != nil { + rebuildFontMetrics() + reportGridSizeIfNeeded() + updateCursorBlinkTimer() + } else { + cursorBlinkTask?.cancel() + cursorBlinkTask = nil + } + } + + public override func layoutSubviews() { + super.layoutSubviews() + reportGridSizeIfNeeded() + } + + // MARK: - Public Updates + + /// Refreshes only the dirty rows from `emulator` (or full view on scroll/alt-screen change). + public func syncWithEmulator() { + let maxOffset = emulator.availableScrollbackCount + if scrollOffsetFromBottom > maxOffset { + scrollOffsetFromBottom = maxOffset + } + guard emulator.generation != lastRenderedGeneration else { return } + lastRenderedGeneration = emulator.generation + invalidateAccessibility() + + let (full, rows) = emulator.consumeDirty() + if full || scrollOffsetFromBottom > 0 || rows.isEmpty { + setNeedsDisplay() + return + } + // Expand dirty rect by 1 row above/below so ascender/descender ink bleed stays crisp. + var minRow = Int.max + var maxRow = Int.min + for r in rows { + if r < minRow { minRow = r } + if r > maxRow { maxRow = r } + } + let clampedMin = max(0, minRow - 1) + let clampedMax = min(emulator.rows - 1, maxRow + 1) + let dirtyY = Self.verticalInset + CGFloat(clampedMin) * metrics.cellHeight + let dirtyH = CGFloat(clampedMax - clampedMin + 1) * metrics.cellHeight + setNeedsDisplay(CGRect(x: 0, y: max(0, dirtyY), width: bounds.width, height: dirtyH)) + } + + public func jumpToBottom() { + scrollOffsetFromBottom = 0 + } + + public func clearSelection() { + selection = nil + editMenuInteraction?.dismissMenu() + } + + // MARK: - Font & Grid Sizing + + private func rebuildFontMetrics() { + let scale = window?.screen.scale ?? traitCollection.displayScale + metrics = TerminalGridMetrics(fontSize: fontSize, scale: max(1, scale)) + regularFont = TerminalGridMetrics.makeFont(size: fontSize, bold: false, italic: false) + boldFont = TerminalGridMetrics.makeFont(size: fontSize, bold: true, italic: false) + italicFont = TerminalGridMetrics.makeFont(size: fontSize, bold: false, italic: true) + boldItalicFont = TerminalGridMetrics.makeFont(size: fontSize, bold: true, italic: true) + } + + private func reportGridSizeIfNeeded() { + guard bounds.width > 40, bounds.height > 40 else { return } + let (cols, rows) = metrics.gridSize( + for: bounds.size, + horizontalInset: Self.horizontalInset, + verticalInset: Self.verticalInset + ) + guard cols != lastReportedGrid.cols || rows != lastReportedGrid.rows else { return } + lastReportedGrid = (cols, rows) + onGridSizeChange?(cols, rows) + } + + // MARK: - CoreText Rendering + + public override func draw(_ rect: CGRect) { + guard let ctx = UIGraphicsGetCurrentContext() else { return } + + ctx.setFillColor(palette.background.cgColor) + ctx.fill(rect) + + let rowHeight = metrics.cellHeight + let colWidth = metrics.cellWidth + let originX = Self.horizontalInset + let originY = Self.verticalInset + let visibleRows = emulator.rows + let sbCount = emulator.availableScrollbackCount + let topAbsoluteLine = max(0, sbCount - scrollOffsetFromBottom) + + let firstRow = max(0, Int(floor((rect.minY - originY) / rowHeight)) - 1) + let lastRow = min(visibleRows - 1, Int(ceil((rect.maxY - originY) / rowHeight))) + guard firstRow <= lastRow else { return } + + let focused = isFirstResponder + let showCursor = scrollOffsetFromBottom == 0 && emulator.cursorVisible && (!focused || cursorBlinkOn) + + for viewRow in firstRow...lastRow { + let absLine = topAbsoluteLine + viewRow + guard let row = emulator.row(atAbsoluteLine: absLine) else { continue } + let rowY = originY + CGFloat(viewRow) * rowHeight + drawRow( + row, + viewRow: viewRow, + absLine: absLine, + originX: originX, + rowY: rowY, + colWidth: colWidth, + rowHeight: rowHeight, + showCursor: showCursor && viewRow == emulator.cursorRow, + focused: focused, + in: ctx + ) + } + } + + private func drawRow( + _ row: TerminalRow, + viewRow: Int, + absLine: Int, + originX: CGFloat, + rowY: CGFloat, + colWidth: CGFloat, + rowHeight: CGFloat, + showCursor: Bool, + focused: Bool, + in ctx: CGContext + ) { + let cells = row.cells + let colCount = cells.count + let defaultBgRGB = palette.background + let cursorCol = showCursor ? emulator.cursorCol : -1 + + // Pass 1: Coalesced contiguous non-default background runs. + var runStart = -1 + var runColor: TerminalRGB? + for c in 0...colCount { + let cellBg: TerminalRGB? + if c < colCount { + let cell = cells[c] + let inverted = cell.style.contains(.inverse) + let bg = inverted ? palette.resolve(cell.fg) : palette.resolve(cell.bg) + cellBg = (bg != defaultBgRGB) ? bg : nil + } else { + cellBg = nil + } + if cellBg != runColor { + if let color = runColor, runStart >= 0 { + ctx.setFillColor(color.cgColor) + ctx.fill(CGRect( + x: originX + CGFloat(runStart) * colWidth, + y: rowY, + width: CGFloat(c - runStart) * colWidth, + height: rowHeight + )) + } + runColor = cellBg + runStart = cellBg != nil ? c : -1 + } + } + + // Pass 2: Selection highlight. + if let sel = selection { + var selStart = -1 + for c in 0...colCount { + let inside = c < colCount && sel.contains(line: absLine, col: c) + if inside && selStart < 0 { + selStart = c + } else if !inside && selStart >= 0 { + ctx.setFillColor(palette.selection.cgColor.copy(alpha: palette.selectionAlpha) ?? palette.selection.cgColor) + ctx.fill(CGRect( + x: originX + CGFloat(selStart) * colWidth, + y: rowY, + width: CGFloat(c - selStart) * colWidth, + height: rowHeight + )) + selStart = -1 + } + } + } + + // Pass 3: Cursor backdrop (block / underline / bar). + if showCursor && cursorCol >= 0 && cursorCol < colCount { + let cursorWidth = CGFloat(max(1, Int(cells[cursorCol].width))) * colWidth + let cursorRect = CGRect( + x: originX + CGFloat(cursorCol) * colWidth, + y: rowY, + width: cursorWidth, + height: rowHeight + ) + ctx.saveGState() + if focused { + ctx.setFillColor(palette.cursor.cgColor) + switch emulator.cursorStyle { + case .block: + ctx.fill(cursorRect) + case .underline: + let h = max(2, metrics.underlineThickness * 1.6) + ctx.fill(CGRect(x: cursorRect.minX, y: cursorRect.maxY - h, width: cursorRect.width, height: h)) + case .bar: + let w = max(2, metrics.underlineThickness * 1.5) + ctx.fill(CGRect(x: cursorRect.minX, y: cursorRect.minY, width: w, height: cursorRect.height)) + } + } else { + // Hollow outline when unfocused (clear visual cue that keyboard is dismissed). + ctx.setStrokeColor(palette.cursor.cgColor) + ctx.setLineWidth(max(1, metrics.underlineThickness)) + ctx.stroke(cursorRect.insetBy(dx: 0.5, dy: 0.5)) + } + ctx.restoreGState() + } + + // Pass 4: Vector box-drawing/blocks + per-run CoreText glyphs with Bidi override. + var c = 0 + while c < colCount { + let cell = cells[c] + if cell.width == 0 || cell.grapheme.isEmpty || cell.style.contains(.hidden) { + c += 1 + continue + } + + let isBlockCursorHere = showCursor && focused && emulator.cursorStyle == .block && c == cursorCol + let fgRGB = resolvedForeground(for: cell, blockCursor: isBlockCursorHere) + let fgColor = fgRGB.cgColor + + // Crisp vector CGPath for Box Drawing & Block Elements. + if cell.width == 1 && TerminalVectorGlyphs.canDraw(cell.grapheme) { + let cellRect = CGRect( + x: originX + CGFloat(c) * colWidth, + y: rowY, + width: colWidth, + height: rowHeight + ) + TerminalVectorGlyphs.draw( + cell.grapheme, + in: cellRect, + color: fgColor, + scale: metrics.scale, + context: ctx + ) + drawDecorations(for: cell.style, x: cellRect.minX, width: colWidth, rowY: rowY, color: fgColor, in: ctx) + c += 1 + continue + } + + // Wide glyph (CJK / Emoji) or multi-scalar grapheme: draw in its exact column slot. + if cell.width == 2 || cell.grapheme.unicodeScalars.count > 1 || !isFastASCII(cell.grapheme) { + let spanCols = max(1, Int(cell.width)) + let x = originX + CGFloat(c) * colWidth + let slotWidth = CGFloat(spanCols) * colWidth + drawSingleGlyph( + cell.grapheme, + atX: x, + rowY: rowY, + slotWidth: slotWidth, + rowHeight: rowHeight, + font: fontForStyle(cell.style), + color: fgColor, + in: ctx + ) + drawDecorations(for: cell.style, x: x, width: slotWidth, rowY: rowY, color: fgColor, in: ctx) + c += spanCols + continue + } + + // Fast coalesced ASCII run with identical (fg, style, non-cursor) attributes. + let runStartCol = c + var text = "" + text.reserveCapacity(16) + while c < colCount { + let next = cells[c] + if next.width != 1 || next.style.contains(.hidden) { break } + let nextCursorBlock = showCursor && focused && emulator.cursorStyle == .block && c == cursorCol + if nextCursorBlock != isBlockCursorHere { break } + if next.grapheme.isEmpty { + // Break on spaces if underline/strikethrough differs, else bridge short gaps cleanly. + if next.style != cell.style || resolvedForeground(for: next, blockCursor: nextCursorBlock) != fgRGB { + break + } + text.append(" ") + c += 1 + continue + } + if !isFastASCII(next.grapheme) || TerminalVectorGlyphs.canDraw(next.grapheme) { break } + if next.style != cell.style || resolvedForeground(for: next, blockCursor: nextCursorBlock) != fgRGB { + break + } + text.append(next.grapheme) + c += 1 + } + + let runX = originX + CGFloat(runStartCol) * colWidth + let runWidth = CGFloat(c - runStartCol) * colWidth + drawASCIIRun( + text, + atX: runX, + rowY: rowY, + colWidth: colWidth, + font: fontForStyle(cell.style), + color: fgColor, + in: ctx + ) + drawDecorations(for: cell.style, x: runX, width: runWidth, rowY: rowY, color: fgColor, in: ctx) + } + } + + private func resolvedForeground(for cell: TerminalCell, blockCursor: Bool) -> TerminalRGB { + if blockCursor { return palette.cursorText } + let inverted = cell.style.contains(.inverse) + let color = inverted ? cell.bg : cell.fg + let dim = cell.style.contains(.dim) && !inverted + return palette.resolve(color, dim: dim) + } + + private func fontForStyle(_ style: TerminalCellStyle) -> CTFont { + let bold = style.contains(.bold) + let italic = style.contains(.italic) + switch (bold, italic) { + case (false, false): return regularFont + case (true, false): return boldFont + case (false, true): return italicFont + case (true, true): return boldItalicFont + } + } + + private func isFastASCII(_ grapheme: String) -> Bool { + guard grapheme.utf8.count == 1, let byte = grapheme.utf8.first else { return false } + return byte >= 0x20 && byte <= 0x7E + } + + private func drawASCIIRun( + _ text: String, + atX x: CGFloat, + rowY: CGFloat, + colWidth: CGFloat, + font: CTFont, + color: CGColor, + in ctx: CGContext + ) { + // Explicit LTR Bidi override prevents mixed RTL/LTR strings from reordering columns. + let attrs: [CFString: Any] = [ + kCTFontAttributeName: font, + kCTForegroundColorAttributeName: color, + kCTWritingDirectionAttributeName: Self.ltrBidiOverride, + ] + guard let attrStr = CFAttributedStringCreate(kCFAllocatorDefault, text as CFString, attrs as CFDictionary) else { + return + } + let line = CTLineCreateWithAttributedString(attrStr) + + ctx.saveGState() + // CoreText draws in flipped (bottom-up) text space relative to UIKit's top-down coordinates. + ctx.textMatrix = CGAffineTransform(scaleX: 1.0, y: -1.0) + ctx.textPosition = CGPoint(x: x, y: rowY + metrics.baselineOffset) + CTLineDraw(line, ctx) + ctx.restoreGState() + } + + private func drawSingleGlyph( + _ text: String, + atX x: CGFloat, + rowY: CGFloat, + slotWidth: CGFloat, + rowHeight: CGFloat, + font: CTFont, + color: CGColor, + in ctx: CGContext + ) { + let attrs: [CFString: Any] = [ + kCTFontAttributeName: font, + kCTForegroundColorAttributeName: color, + kCTWritingDirectionAttributeName: Self.ltrBidiOverride, + ] + guard let attrStr = CFAttributedStringCreate(kCFAllocatorDefault, text as CFString, attrs as CFDictionary) else { + return + } + let line = CTLineCreateWithAttributedString(attrStr) + + ctx.saveGState() + // Clip horizontally to the cell slot (+1pt overhang tolerance) so wide fallback + // glyphs never bleed across neighboring columns. + ctx.clip(to: CGRect(x: x - 0.5, y: rowY - 2, width: slotWidth + 1.0, height: rowHeight + 4)) + ctx.textMatrix = CGAffineTransform(scaleX: 1.0, y: -1.0) + ctx.textPosition = CGPoint(x: x, y: rowY + metrics.baselineOffset) + CTLineDraw(line, ctx) + ctx.restoreGState() + } + + private func drawDecorations( + for style: TerminalCellStyle, + x: CGFloat, + width: CGFloat, + rowY: CGFloat, + color: CGColor, + in ctx: CGContext + ) { + if style.contains(.underline) { + ctx.setFillColor(color) + ctx.fill(CGRect( + x: x, + y: rowY + metrics.baselineOffset + metrics.underlineOffset, + width: width, + height: metrics.underlineThickness + )) + } + if style.contains(.strikethrough) { + ctx.setFillColor(color) + ctx.fill(CGRect( + x: x, + y: rowY + metrics.cellHeight * 0.5, + width: width, + height: metrics.underlineThickness + )) + } + } + + // MARK: - Gestures (Focus, Scrollback Pan, Long-Press Selection, Pinch Zoom) + + private func gridPosition(for point: CGPoint) -> TerminalGridPosition { + let col = max(0, min(emulator.cols - 1, Int(floor((point.x - Self.horizontalInset) / max(1, metrics.cellWidth))))) + let viewRow = max(0, min(emulator.rows - 1, Int(floor((point.y - Self.verticalInset) / max(1, metrics.cellHeight))))) + let sbCount = emulator.availableScrollbackCount + let absLine = max(0, min(emulator.totalLineCount - 1, sbCount - scrollOffsetFromBottom + viewRow)) + return TerminalGridPosition(line: absLine, col: col) + } + + @objc private func handleTap(_ gesture: UITapGestureRecognizer) { + if selection != nil { + clearSelection() + return + } + _ = becomeFirstResponder() + } + + @objc private func handlePan(_ gesture: UIPanGestureRecognizer) { + let translation = gesture.translation(in: self) + switch gesture.state { + case .began: + panAccumulatedY = 0 + case .changed: + let deltaY = translation.y - panAccumulatedY + let rowStep = max(1, metrics.cellHeight) + let rowsDelta = Int(deltaY / rowStep) + if rowsDelta != 0 { + panAccumulatedY += CGFloat(rowsDelta) * rowStep + let maxScroll = emulator.availableScrollbackCount + if maxScroll > 0 { + // Dragging finger DOWN scrolls back into older history (increases offset from bottom). + scrollOffsetFromBottom = max(0, min(maxScroll, scrollOffsetFromBottom + rowsDelta)) + } else if emulator.isUsingAlternateScreen { + // In alt-screen (less / vim / Bubbletea / tmux), vertical drag emits Up/Down arrows. + let key = rowsDelta > 0 + ? (emulator.applicationCursorKeys ? "\u{1b}OA" : "\u{1b}[A") + : (emulator.applicationCursorKeys ? "\u{1b}OB" : "\u{1b}[B") + let steps = min(abs(rowsDelta), 5) + onInput?(String(repeating: key, count: steps)) + } + } + default: + panAccumulatedY = 0 + } + } + + @objc private func handleLongPress(_ gesture: UILongPressGestureRecognizer) { + let pt = gesture.location(in: self) + let pos = gridPosition(for: pt) + switch gesture.state { + case .began: + editMenuInteraction?.dismissMenu() + let wordSelection = wordSelectionAround(pos) ?? TerminalSelection(anchor: pos, focus: pos) + selection = wordSelection + #if !targetEnvironment(macCatalyst) + UIImpactFeedbackGenerator(style: .light).impactOccurred() + #endif + case .changed: + if var current = selection { + current.focus = pos + selection = current + } + case .ended: + guard let sel = selection, !emulator.extractText(for: sel).isEmpty else { + selection = nil + return + } + let config = UIEditMenuConfiguration(identifier: nil, sourcePoint: pt) + editMenuInteraction?.presentEditMenu(with: config) + case .cancelled, .failed: + selection = nil + default: + break + } + } + + @objc private func handlePinch(_ gesture: UIPinchGestureRecognizer) { + switch gesture.state { + case .began: + pinchBaseFontSize = fontSize + case .changed: + let next = (pinchBaseFontSize * gesture.scale).rounded() + let clamped = max(10, min(22, next)) + if clamped != fontSize { + fontSize = clamped + onFontSizeChange?(clamped) + } + default: + break + } + } + + private func wordSelectionAround(_ pos: TerminalGridPosition) -> TerminalSelection? { + guard let row = emulator.row(atAbsoluteLine: pos.line) else { return nil } + guard pos.col < row.cells.count else { return nil } + func isWordChar(_ cell: TerminalCell) -> Bool { + if cell.width == 0 { return true } + guard !cell.grapheme.isEmpty else { return false } + return cell.grapheme != " " && cell.grapheme != "\t" + } + guard isWordChar(row.cells[pos.col]) else { return nil } + var left = pos.col + while left > 0 && isWordChar(row.cells[left - 1]) { left -= 1 } + var right = pos.col + while right + 1 < row.cells.count && isWordChar(row.cells[right + 1]) { right += 1 } + return TerminalSelection( + anchor: TerminalGridPosition(line: pos.line, col: left), + focus: TerminalGridPosition(line: pos.line, col: right) + ) + } + + // MARK: - Edit Menu (Copy & Send to Chat) + + public func editMenuInteraction( + _ interaction: UIEditMenuInteraction, + menuFor configuration: UIEditMenuConfiguration, + suggestedActions: [UIMenuElement] + ) -> UIMenu? { + guard let sel = selection else { return nil } + let selectedText = emulator.extractText(for: sel) + guard !selectedText.isEmpty else { return nil } + + var actions: [UIMenuElement] = [ + UIAction(title: String(localized: "Copy"), image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in + UIPasteboard.general.string = selectedText + self?.clearSelection() + } + ] + if let onSendExcerpt { + actions.append( + UIAction(title: String(localized: "Send to Chat"), image: UIImage(systemName: "text.bubble")) { [weak self] _ in + onSendExcerpt(selectedText) + self?.clearSelection() + } + ) + } + return UIMenu(children: actions) + } + + public func editMenuInteraction( + _ interaction: UIEditMenuInteraction, + willDismissMenuFor configuration: UIEditMenuConfiguration, + animator: any UIEditMenuInteractionAnimating + ) { + // Keep selection briefly only if user is still dragging; otherwise clear cleanly. + } + + // MARK: - First Responder & Cursor Blink + + public override var canBecomeFirstResponder: Bool { true } + + @discardableResult + public override func becomeFirstResponder() -> Bool { + let ok = super.becomeFirstResponder() + if ok { + cursorBlinkOn = true + updateCursorBlinkTimer() + onFocusChange?(true) + setNeedsDisplay() + } + return ok + } + + @discardableResult + public override func resignFirstResponder() -> Bool { + let ok = super.resignFirstResponder() + if ok { + cursorBlinkTask?.cancel() + cursorBlinkTask = nil + onFocusChange?(false) + setNeedsDisplay() + } + return ok + } + + private func updateCursorBlinkTimer() { + cursorBlinkTask?.cancel() + cursorBlinkTask = nil + guard isFirstResponder, window != nil else { return } + cursorBlinkTask = Task { @MainActor [weak self] in + while !Task.isCancelled { + try? await Task.sleep(for: .milliseconds(600)) + guard !Task.isCancelled, let self else { return } + guard self.isFirstResponder, self.scrollOffsetFromBottom == 0, self.emulator.cursorVisible else { + continue + } + self.cursorBlinkOn.toggle() + let y = Self.verticalInset + CGFloat(self.emulator.cursorRow) * self.metrics.cellHeight + self.setNeedsDisplay(CGRect(x: 0, y: y, width: self.bounds.width, height: self.metrics.cellHeight)) + } + } + } + + // MARK: - UIKeyInput & UITextInputTraits + + public var hasText: Bool { true } + + public var autocorrectionType: UITextAutocorrectionType { + get { .no } + set {} + } + + public var autocapitalizationType: UITextAutocapitalizationType { + get { .none } + set {} + } + + public var spellCheckingType: UITextSpellCheckingType { + get { .no } + set {} + } + + public var smartQuotesType: UITextSmartQuotesType { + get { .no } + set {} + } + + public var smartDashesType: UITextSmartDashesType { + get { .no } + set {} + } + + public var smartInsertDeleteType: UITextSmartInsertDeleteType { + get { .no } + set {} + } + + public func insertText(_ text: String) { + if scrollOffsetFromBottom > 0 { jumpToBottom() } + clearSelection() + let normalized = text.replacingOccurrences(of: "\n", with: "\r") + onInput?(normalized) + } + + public func deleteBackward() { + if scrollOffsetFromBottom > 0 { jumpToBottom() } + clearSelection() + onInput?("\u{7f}") + } + + // MARK: - Physical Keyboard (iPad / Mac Catalyst) + + public override func pressesBegan(_ presses: Set, with event: UIPressesEvent?) { + var handled = false + for press in presses { + guard let key = press.key else { continue } + if handleHardwareKey(key) { + handled = true + } + } + if !handled { + super.pressesBegan(presses, with: event) + } + } + + private func handleHardwareKey(_ key: UIKey) -> Bool { + let mods = key.modifierFlags + + // Command shortcuts (⌘C copy, ⌘V paste, ⌘K clear, ⌘+/- font zoom). + if mods.contains(.command) { + switch key.charactersIgnoringModifiers.lowercased() { + case "c": + if let sel = selection { + let text = emulator.extractText(for: sel) + if !text.isEmpty { + UIPasteboard.general.string = text + clearSelection() + return true + } + } + return false + case "v": + if let text = UIPasteboard.general.string, !text.isEmpty { + if scrollOffsetFromBottom > 0 { jumpToBottom() } + onPaste?(text) + return true + } + return false + case "k": + onInput?("\u{0c}") // Ctrl+L + return true + case "=", "+": + let next = min(22, fontSize + 1) + if next != fontSize { fontSize = next; onFontSizeChange?(next) } + return true + case "-": + let next = max(10, fontSize - 1) + if next != fontSize { fontSize = next; onFontSizeChange?(next) } + return true + case "0": + if fontSize != 13 { fontSize = 13; onFontSizeChange?(13) } + return true + default: + return false + } + } + + let appCursor = emulator.applicationCursorKeys + var sequence: String? + switch key.keyCode { + case .keyboardEscape: + sequence = "\u{1b}" + case .keyboardTab: + sequence = mods.contains(.shift) ? "\u{1b}[Z" : "\t" + case .keyboardReturnOrEnter, .keypadEnter: + sequence = "\r" + case .keyboardDeleteOrBackspace: + sequence = "\u{7f}" + case .keyboardDeleteForward: + sequence = "\u{1b}[3~" + case .keyboardUpArrow: + sequence = appCursor ? "\u{1b}OA" : "\u{1b}[A" + case .keyboardDownArrow: + sequence = appCursor ? "\u{1b}OB" : "\u{1b}[B" + case .keyboardRightArrow: + sequence = appCursor ? "\u{1b}OC" : "\u{1b}[C" + case .keyboardLeftArrow: + sequence = appCursor ? "\u{1b}OD" : "\u{1b}[D" + case .keyboardHome: + sequence = appCursor ? "\u{1b}OH" : "\u{1b}[H" + case .keyboardEnd: + sequence = appCursor ? "\u{1b}OF" : "\u{1b}[F" + case .keyboardPageUp: + sequence = "\u{1b}[5~" + case .keyboardPageDown: + sequence = "\u{1b}[6~" + default: + break + } + + if var seq = sequence { + if mods.contains(.alternate) { seq = "\u{1b}\(seq)" } + if scrollOffsetFromBottom > 0 { jumpToBottom() } + clearSelection() + onInput?(seq) + return true + } + + // Control + character (Ctrl+C, Ctrl+D, Ctrl+A..Z, Ctrl+[, etc.) + if mods.contains(.control) { + let base = key.charactersIgnoringModifiers + if base.unicodeScalars.count == 1, let scalar = base.unicodeScalars.first { + let v = scalar.value + var ctrl: UInt8? + if v == 0x20 || v == 0x40 { ctrl = 0x00 } + else if v >= 0x61 && v <= 0x7A { ctrl = UInt8(v - 0x60) } + else if v >= 0x41 && v <= 0x5F { ctrl = UInt8(v - 0x40) } + else if v == 0x3F { ctrl = 0x7F } + if let byte = ctrl { + var out = String(UnicodeScalar(byte)) + if mods.contains(.alternate) { out = "\u{1b}\(out)" } + if scrollOffsetFromBottom > 0 { jumpToBottom() } + clearSelection() + onInput?(out) + return true + } + } + } + + // Option / Alt + character -> ESC prefix + if mods.contains(.alternate) && !mods.contains(.control) { + let base = key.charactersIgnoringModifiers + if !base.isEmpty { + if scrollOffsetFromBottom > 0 { jumpToBottom() } + clearSelection() + onInput?("\u{1b}\(base)") + return true + } + } + + return false + } + + // MARK: - VoiceOver Accessibility (Row-level Elements) + + private func invalidateAccessibility() { + cachedAccessibilityElements = nil + } + + public override var isAccessibilityElement: Bool { + get { false } + set {} + } + + private func resolvedAccessibilityElements() -> [UIAccessibilityElement] { + if let cached = cachedAccessibilityElements as? [UIAccessibilityElement] { + return cached + } + let sbCount = emulator.availableScrollbackCount + let topLine = max(0, sbCount - scrollOffsetFromBottom) + var elements: [UIAccessibilityElement] = [] + for r in 0.. Int { + resolvedAccessibilityElements().count + } + + public override func accessibilityElement(at index: Int) -> Any? { + let elements = resolvedAccessibilityElements() + guard index >= 0 && index < elements.count else { return nil } + return elements[index] + } + + public override func index(ofAccessibilityElement element: Any) -> Int { + guard let target = element as? UIAccessibilityElement else { return NSNotFound } + return resolvedAccessibilityElements().firstIndex { $0 === target } ?? NSNotFound + } +} +#endif diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalBuffer.swift b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalBuffer.swift new file mode 100644 index 00000000000..3f66c2e6e8c --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalBuffer.swift @@ -0,0 +1,383 @@ +import CoreGraphics +import Foundation + +// MARK: - Colors & Palette + +public struct TerminalRGB: Equatable, Hashable, Sendable { + public var r: UInt8 + public var g: UInt8 + public var b: UInt8 + + public init(_ r: UInt8, _ g: UInt8, _ b: UInt8) { + self.r = r + self.g = g + self.b = b + } + + public init(hex: UInt32) { + self.r = UInt8((hex >> 16) & 0xFF) + self.g = UInt8((hex >> 8) & 0xFF) + self.b = UInt8(hex & 0xFF) + } + + public var cgColor: CGColor { + CGColor( + srgbRed: CGFloat(r) / 255.0, + green: CGFloat(g) / 255.0, + blue: CGFloat(b) / 255.0, + alpha: 1.0 + ) + } + + /// Formats RGB for xterm OSC 10/11 replies (`rgb:rrrr/gggg/bbbb`). + public var oscRGBString: String { + let rr = String(format: "%02x%02x", r, r) + let gg = String(format: "%02x%02x", g, g) + let bb = String(format: "%02x%02x", b, b) + return "rgb:\(rr)/\(gg)/\(bb)" + } +} + +public enum TerminalColor: Equatable, Hashable, Sendable { + case defaultForeground + case defaultBackground + case ansi(UInt8) + case rgb(UInt8, UInt8, UInt8) +} + +/// Complete terminal color palette aligned with `HapiTheme.Variant`. +public struct TerminalPalette: Equatable, Sendable { + public var background: TerminalRGB + public var foreground: TerminalRGB + public var cursor: TerminalRGB + public var cursorText: TerminalRGB + public var selection: TerminalRGB + public var selectionAlpha: CGFloat + /// The 16 ANSI colors (`0...7` standard, `8...15` bright). + public var ansi16: [TerminalRGB] + + public init( + background: TerminalRGB, + foreground: TerminalRGB, + cursor: TerminalRGB, + cursorText: TerminalRGB, + selection: TerminalRGB, + selectionAlpha: CGFloat, + ansi16: [TerminalRGB] + ) { + self.background = background + self.foreground = foreground + self.cursor = cursor + self.cursorText = cursorText + self.selection = selection + self.selectionAlpha = selectionAlpha + self.ansi16 = ansi16 + } + + public static func forTheme(_ variant: HapiTheme.Variant) -> TerminalPalette { + switch variant { + case .light: + return TerminalPalette( + background: TerminalRGB(hex: 0xFFFFFF), + foreground: TerminalRGB(hex: 0x1C1D22), + cursor: TerminalRGB(hex: 0x2563EB), + cursorText: TerminalRGB(hex: 0xFFFFFF), + selection: TerminalRGB(hex: 0x3B82F6), + selectionAlpha: 0.24, + ansi16: [ + TerminalRGB(hex: 0x1C1D22), // 0 black + TerminalRGB(hex: 0xC92A2A), // 1 red + TerminalRGB(hex: 0x15803D), // 2 green + TerminalRGB(hex: 0xB45309), // 3 yellow + TerminalRGB(hex: 0x1D4ED8), // 4 blue + TerminalRGB(hex: 0x7E22CE), // 5 magenta + TerminalRGB(hex: 0x0E7490), // 6 cyan + TerminalRGB(hex: 0x6B7280), // 7 white + TerminalRGB(hex: 0x52555E), // 8 bright black + TerminalRGB(hex: 0xDC2626), // 9 bright red + TerminalRGB(hex: 0x16A34A), // 10 bright green + TerminalRGB(hex: 0xD97706), // 11 bright yellow + TerminalRGB(hex: 0x2563EB), // 12 bright blue + TerminalRGB(hex: 0x9333EA), // 13 bright magenta + TerminalRGB(hex: 0x0891B2), // 14 bright cyan + TerminalRGB(hex: 0x111827), // 15 bright white + ] + ) + case .dark: + return TerminalPalette( + background: TerminalRGB(hex: 0x0F1115), + foreground: TerminalRGB(hex: 0xE8EAED), + cursor: TerminalRGB(hex: 0x6C9EFF), + cursorText: TerminalRGB(hex: 0x0F1115), + selection: TerminalRGB(hex: 0x6C9EFF), + selectionAlpha: 0.30, + ansi16: [ + TerminalRGB(hex: 0x282C34), // 0 black + TerminalRGB(hex: 0xF85149), // 1 red + TerminalRGB(hex: 0x3FB950), // 2 green + TerminalRGB(hex: 0xD29922), // 3 yellow + TerminalRGB(hex: 0x58A6FF), // 4 blue + TerminalRGB(hex: 0xBC8CFF), // 5 magenta + TerminalRGB(hex: 0x39C5CF), // 6 cyan + TerminalRGB(hex: 0xB1BAC4), // 7 white + TerminalRGB(hex: 0x6E7681), // 8 bright black + TerminalRGB(hex: 0xFF7B72), // 9 bright red + TerminalRGB(hex: 0x56D364), // 10 bright green + TerminalRGB(hex: 0xE3B341), // 11 bright yellow + TerminalRGB(hex: 0x79C0FF), // 12 bright blue + TerminalRGB(hex: 0xD2A8FF), // 13 bright magenta + TerminalRGB(hex: 0x56D4DD), // 14 bright cyan + TerminalRGB(hex: 0xF0F6FC), // 15 bright white + ] + ) + case .oled: + var dark = TerminalPalette.forTheme(.dark) + dark.background = TerminalRGB(hex: 0x000000) + dark.cursorText = TerminalRGB(hex: 0x000000) + return dark + } + } + + public func resolve(_ color: TerminalColor, dim: Bool = false) -> TerminalRGB { + let base: TerminalRGB + switch color { + case .defaultForeground: + base = foreground + case .defaultBackground: + base = background + case .rgb(let r, let g, let b): + base = TerminalRGB(r, g, b) + case .ansi(let index): + if index < 16 { + base = ansi16[Int(index)] + } else if index < 232 { + // 6x6x6 xterm color cube. + let offset = Int(index) - 16 + let rIdx = offset / 36 + let gIdx = (offset % 36) / 6 + let bIdx = offset % 6 + let levels: [UInt8] = [0, 95, 135, 175, 215, 255] + base = TerminalRGB(levels[rIdx], levels[gIdx], levels[bIdx]) + } else { + // 24-step grayscale ramp (8 .. 238). + let level = UInt8(8 + (Int(index) - 232) * 10) + base = TerminalRGB(level, level, level) + } + } + guard dim else { return base } + // Blend 35% toward background for legible dim text on both light & dark themes. + func blend(_ a: UInt8, _ b: UInt8) -> UInt8 { + UInt8((Int(a) * 65 + Int(b) * 35) / 100) + } + return TerminalRGB( + blend(base.r, background.r), + blend(base.g, background.g), + blend(base.b, background.b) + ) + } +} + +// MARK: - Cell, Row, Cursor, Selection + +public struct TerminalCellStyle: OptionSet, Equatable, Hashable, Sendable { + public let rawValue: UInt8 + public init(rawValue: UInt8) { self.rawValue = rawValue } + + public static let bold = TerminalCellStyle(rawValue: 1 << 0) + public static let dim = TerminalCellStyle(rawValue: 1 << 1) + public static let italic = TerminalCellStyle(rawValue: 1 << 2) + public static let underline = TerminalCellStyle(rawValue: 1 << 3) + public static let inverse = TerminalCellStyle(rawValue: 1 << 4) + public static let hidden = TerminalCellStyle(rawValue: 1 << 5) + public static let strikethrough = TerminalCellStyle(rawValue: 1 << 6) +} + +public struct TerminalCell: Equatable, Sendable { + /// Empty string represents a blank space cell. + public var grapheme: String + /// Display column width: `1` normal, `2` wide lead cell, `0` trailing spacer of a wide glyph. + public var width: UInt8 + public var fg: TerminalColor + public var bg: TerminalColor + public var style: TerminalCellStyle + + public static let blank = TerminalCell( + grapheme: "", + width: 1, + fg: .defaultForeground, + bg: .defaultBackground, + style: [] + ) + + public init( + grapheme: String = "", + width: UInt8 = 1, + fg: TerminalColor = .defaultForeground, + bg: TerminalColor = .defaultBackground, + style: TerminalCellStyle = [] + ) { + self.grapheme = grapheme + self.width = width + self.fg = fg + self.bg = bg + self.style = style + } + + public static func blank(bg: TerminalColor) -> TerminalCell { + TerminalCell(grapheme: "", width: 1, fg: .defaultForeground, bg: bg, style: []) + } + + public static func wideSpacer(fg: TerminalColor, bg: TerminalColor, style: TerminalCellStyle) -> TerminalCell { + TerminalCell(grapheme: "", width: 0, fg: fg, bg: bg, style: style) + } +} + +public struct TerminalRow: Equatable, Sendable { + public var cells: [TerminalCell] + /// True when the line soft-wrapped onto the following row (no explicit newline). + public var wrapped: Bool + + public init(cols: Int, fill: TerminalCell = .blank, wrapped: Bool = false) { + self.cells = Array(repeating: fill, count: max(1, cols)) + self.wrapped = wrapped + } + + /// Plain text of the row with trailing blank spaces trimmed. + public func plainText(trimTrailingSpaces: Bool = true) -> String { + var out = "" + out.reserveCapacity(cells.count) + for cell in cells { + if cell.width == 0 { continue } + out.append(cell.grapheme.isEmpty ? " " : cell.grapheme) + } + if trimTrailingSpaces { + while out.last == " " { + out.removeLast() + } + } + return out + } +} + +public enum TerminalCursorStyle: Equatable, Sendable { + case block + case underline + case bar +} + +public struct TerminalGridPosition: Equatable, Comparable, Sendable { + /// Absolute line index in `0 ..< totalLineCount`. + public var line: Int + public var col: Int + + public init(line: Int, col: Int) { + self.line = line + self.col = col + } + + public static func < (lhs: TerminalGridPosition, rhs: TerminalGridPosition) -> Bool { + lhs.line != rhs.line ? lhs.line < rhs.line : lhs.col < rhs.col + } +} + +public struct TerminalSelection: Equatable, Sendable { + public var anchor: TerminalGridPosition + public var focus: TerminalGridPosition + + public init(anchor: TerminalGridPosition, focus: TerminalGridPosition) { + self.anchor = anchor + self.focus = focus + } + + public var normalized: (start: TerminalGridPosition, end: TerminalGridPosition) { + anchor <= focus ? (anchor, focus) : (focus, anchor) + } + + public func contains(line: Int, col: Int) -> Bool { + let (start, end) = normalized + if line < start.line || line > end.line { return false } + if start.line == end.line { + return col >= start.col && col <= end.col + } + if line == start.line { return col >= start.col } + if line == end.line { return col <= end.col } + return true + } +} + +// MARK: - Display Width (wcwidth / East Asian Wide + Emoji + Combining) + +public enum TerminalCharWidth { + /// Returns terminal column width: `0` (combining/zero-width), `1` (narrow), or `2` (wide/emoji). + public static func width(of scalar: UnicodeScalar) -> Int { + let v = scalar.value + if v == 0 || v < 0x20 || (v >= 0x7F && v < 0xA0) { return 0 } + if v < 0x7F { return 1 } + + // Combining marks, variation selectors, ZWJ, format controls. + if v == 0x200D || v == 0x200B || v == 0x200C || v == 0xFEFF { return 0 } + if (0x0300...0x036F).contains(v) + || (0x1AB0...0x1AFF).contains(v) + || (0x1DC0...0x1DFF).contains(v) + || (0x20D0...0x20FF).contains(v) + || (0xFE00...0xFE0F).contains(v) + || (0xFE20...0xFE2F).contains(v) + || (0xE0100...0xE01EF).contains(v) + { + return 0 + } + let cat = scalar.properties.generalCategory + if cat == .nonspacingMark || cat == .enclosingMark { return 0 } + + // Emoji modifiers (skin tones) attach to preceding emoji. + if (0x1F3FB...0x1F3FF).contains(v) { return 0 } + + // East Asian Wide / Fullwidth & common Emoji presentation ranges. + if (0x1100...0x115F).contains(v) + || v == 0x2329 || v == 0x232A + || (0x231A...0x231B).contains(v) + || (0x23E9...0x23EC).contains(v) + || v == 0x23F0 || v == 0x23F3 + || (0x25FD...0x25FE).contains(v) + || (0x2614...0x2615).contains(v) + || (0x2648...0x2653).contains(v) + || v == 0x267F || v == 0x2693 || v == 0x26A1 + || (0x26AA...0x26AB).contains(v) + || (0x26BD...0x26BE).contains(v) + || (0x26C4...0x26C5).contains(v) + || v == 0x26CE || v == 0x26D4 || v == 0x26EA + || (0x26F2...0x26F3).contains(v) + || v == 0x26F5 || v == 0x26FA || v == 0x26FD + || v == 0x2705 || (0x270A...0x270B).contains(v) + || v == 0x2728 || v == 0x274C || v == 0x274E + || (0x2753...0x2755).contains(v) + || v == 0x2757 || (0x2795...0x2797).contains(v) + || v == 0x27B0 || v == 0x27BF + || (0x2B1B...0x2B1C).contains(v) + || v == 0x2B50 || v == 0x2B55 + || (0x2E80...0x303E).contains(v) + || (0x3041...0x33FF).contains(v) + || (0x3400...0x4DBF).contains(v) + || (0x4E00...0x9FFF).contains(v) + || (0xA000...0xA4CF).contains(v) + || (0xA960...0xA97F).contains(v) + || (0xAC00...0xD7A3).contains(v) + || (0xF900...0xFAFF).contains(v) + || (0xFE10...0xFE19).contains(v) + || (0xFE30...0xFE6F).contains(v) + || (0xFF01...0xFF60).contains(v) + || (0xFFE0...0xFFE6).contains(v) + || (0x1F004...0x1F0CF).contains(v) + || (0x1F18E...0x1F1FF).contains(v) + || (0x1F200...0x1F2FF).contains(v) + || (0x1F300...0x1F64F).contains(v) + || (0x1F680...0x1F6FF).contains(v) + || (0x1F900...0x1FAFF).contains(v) + || (0x20000...0x3FFFD).contains(v) + { + return 2 + } + + return 1 + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalEmulator.swift b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalEmulator.swift new file mode 100644 index 00000000000..b2371dbbd45 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalEmulator.swift @@ -0,0 +1,1319 @@ +import Foundation + +/// Pure-Swift VT100 / xterm-256color / 24-bit Truecolor terminal emulator. +/// +/// Designed for interactive shells (bash/zsh/fish/vim/tmux) and modern coding +/// agent TUIs (Claude Code Ink, Codex TUI, Bubbletea/AGY): supports alternate +/// screen buffers, DECSTBM scroll regions, synchronized output (`DECSET 2026`), +/// bracketed paste (`DECSET 2004`), application cursor keys (`DECCKM`), cursor +/// position & OSC 10/11 color queries, DEC Special Graphics, CJK/Emoji display +/// width, and bounded primary scrollback with dirty-row tracking. +public final class TerminalEmulator { + // MARK: - Dimensions & Buffers + + public private(set) var cols: Int + public private(set) var rows: Int + public let maxScrollback: Int + + /// Active visible viewport rows (`count == rows`). + public private(set) var grid: [TerminalRow] + /// Primary scrollback lines (oldest at index 0; empty while in alt-screen view). + public private(set) var scrollback: [TerminalRow] = [] + + public private(set) var cursorRow: Int = 0 + public private(set) var cursorCol: Int = 0 + public private(set) var cursorVisible: Bool = true + public private(set) var cursorStyle: TerminalCursorStyle = .block + + public private(set) var title: String = "" + public private(set) var isUsingAlternateScreen: Bool = false + public private(set) var applicationCursorKeys: Bool = false + public private(set) var bracketedPasteMode: Bool = false + public private(set) var synchronizedOutputActive: Bool = false + public private(set) var mouseReportingEnabled: Bool = false + public private(set) var sgrMouseMode: Bool = false + + /// Monotonic revision bumped whenever visible content/cursor changes (deferred during `?2026`). + public private(set) var generation: UInt64 = 0 + /// Palette used to answer `OSC 10/11` color queries. + public var palette: TerminalPalette = .forTheme(.dark) + + /// Invoked synchronously when the emulator answers a terminal query (`CSI 6n`, `DA`, `OSC 10/11`). + public var onReply: ((String) -> Void)? + /// Invoked when `OSC 0` / `OSC 2` changes the terminal title. + public var onTitleChange: ((String) -> Void)? + + // MARK: - Internal State + + private var pendingWrap: Bool = false + private var autowrap: Bool = true + private var originMode: Bool = false + private var insertMode: Bool = false + private var newlineMode: Bool = false + private var scrollTop: Int = 0 + private var scrollBottom: Int + + private var currentFg: TerminalColor = .defaultForeground + private var currentBg: TerminalColor = .defaultBackground + private var currentStyle: TerminalCellStyle = [] + + // DEC Special Graphics G0/G1 charset switching + private var g0LineDrawing: Bool = false + private var g1LineDrawing: Bool = false + private var activeCharsetG1: Bool = false + + private var tabStops: Set = [] + private var lastPrintedScalar: UnicodeScalar? + private var lastPrintedPos: (row: Int, col: Int)? + + private struct SavedCursor { + var row: Int + var col: Int + var fg: TerminalColor + var bg: TerminalColor + var style: TerminalCellStyle + var originMode: Bool + var autowrap: Bool + var g0LineDrawing: Bool + var g1LineDrawing: Bool + var activeCharsetG1: Bool + } + + private var savedPrimaryCursor: SavedCursor? + private var savedAltCursor: SavedCursor? + private var stashedPrimaryGrid: [TerminalRow]? + + // Dirty tracking for incremental CoreText invalidation + private var dirtyRows: IndexSet = IndexSet() + private var needsFullRedraw: Bool = true + private var pendingSyncDirty: Bool = false + + // Incremental UTF-8 decoder buffer + private var utf8Buffer: [UInt8] = [] + private var utf8ExpectedLength: Int = 0 + + // VT parser state + private enum ParseState { + case ground + case escape + case escapeIntermediate(UInt8) + case csiEntry + case csiParam + case oscString + case oscEsc + case dcsString + case dcsEsc + } + + private var parseState: ParseState = .ground + private var csiPrefix: UInt8 = 0 + private var csiIntermediate: UInt8 = 0 + private var csiRawParams: [UInt8] = [] + private var oscBytes: [UInt8] = [] + + private static let maxOSCBytes = 8192 + + // MARK: - Init + + public init(cols: Int = 80, rows: Int = 24, maxScrollback: Int = 5_000) { + let clampedCols = max(2, cols) + let clampedRows = max(2, rows) + self.cols = clampedCols + self.rows = clampedRows + self.maxScrollback = max(0, maxScrollback) + self.scrollBottom = clampedRows - 1 + self.grid = (0.. TerminalRow? { + let sbCount = availableScrollbackCount + if line < 0 || line >= sbCount + rows { return nil } + if line < sbCount { + return scrollback[line] + } + return grid[line - sbCount] + } + + /// Extracts selected text across scrollback + active viewport, joining soft-wrapped lines. + public func extractText(for selection: TerminalSelection) -> String { + let (start, end) = selection.normalized + let total = totalLineCount + guard total > 0 else { return "" } + let startLine = max(0, min(start.line, total - 1)) + let endLine = max(startLine, min(end.line, total - 1)) + + var output = "" + for lineIdx in startLine...endLine { + guard let row = row(atAbsoluteLine: lineIdx) else { continue } + let colStart = (lineIdx == startLine) ? max(0, min(start.col, row.cells.count - 1)) : 0 + let colEnd = (lineIdx == endLine) ? max(colStart, min(end.col, row.cells.count - 1)) : (row.cells.count - 1) + + var lineText = "" + // If selection starts on the trailing half of a wide char, include its lead char. + var c = colStart + if c > 0 && row.cells[c].width == 0 && row.cells[c - 1].width == 2 { + c -= 1 + } + while c <= colEnd && c < row.cells.count { + let cell = row.cells[c] + if cell.width == 0 { + c += 1 + continue + } + lineText.append(cell.grapheme.isEmpty ? " " : cell.grapheme) + c += 1 + } + + // Trim trailing spaces unless this line soft-wraps directly into the next selected line. + if lineIdx == endLine || !row.wrapped { + while lineText.last == " " { + lineText.removeLast() + } + } + output.append(lineText) + if lineIdx < endLine && !row.wrapped { + output.append("\n") + } + } + return output + } + + /// Returns all visible viewport lines joined by newlines (useful for copy-screen & tests). + public var visiblePlainText: String { + grid.map { $0.plainText() }.joined(separator: "\n") + } + + /// Consumes accumulated dirty viewport row indices since the previous draw. + public func consumeDirty() -> (full: Bool, rows: IndexSet) { + let result = (needsFullRedraw, dirtyRows) + needsFullRedraw = false + dirtyRows.removeAll() + return result + } + + // MARK: - Feed Input + + public func feed(_ text: String) { + feed(Array(text.utf8)) + } + + public func feed(_ bytes: [UInt8]) { + guard !bytes.isEmpty else { return } + let prevRow = cursorRow + for byte in bytes { + processByte(byte) + } + if cursorRow != prevRow { + markDirty(prevRow) + markDirty(cursorRow) + } + if synchronizedOutputActive { + pendingSyncDirty = true + } else { + generation &+= 1 + } + } + + /// Forces any held synchronized-output frame to become visible (safety valve if a TUI disconnects mid-frame). + public func flushSynchronizedOutput() { + guard synchronizedOutputActive else { return } + synchronizedOutputActive = false + if pendingSyncDirty { + pendingSyncDirty = false + needsFullRedraw = true + generation &+= 1 + } + } + + public func reset() { + isUsingAlternateScreen = false + stashedPrimaryGrid = nil + savedPrimaryCursor = nil + savedAltCursor = nil + scrollback.removeAll(keepingCapacity: false) + grid = (0.. [TerminalRow] { + var adjusted = source.map { row -> TerminalRow in + var next = TerminalRow(cols: targetCols, wrapped: row.wrapped) + let copyCount = min(row.cells.count, targetCols) + for i in 0.. 0 && next.cells[targetCols - 1].width == 2 { + next.cells[targetCols - 1] = .blank + } + return next + } + + if adjusted.count > targetRows { + let overflow = adjusted.count - targetRows + if preserveIntoScrollback && maxScrollback > 0 { + // Push lines above the cursor into scrollback so the active prompt stays visible. + let maxPush = min(overflow, max(0, cursorRow - (targetRows - 1))) + if maxPush > 0 { + for i in 0.. targetRows { + adjusted.removeLast(adjusted.count - targetRows) + } + } else if adjusted.count < targetRows { + let deficit = targetRows - adjusted.count + if preserveIntoScrollback && !scrollback.isEmpty { + let pull = min(deficit, scrollback.count) + let restored = Array(scrollback.suffix(pull)) + scrollback.removeLast(pull) + var resizedRestored = restored.map { row -> TerminalRow in + var next = TerminalRow(cols: targetCols, wrapped: row.wrapped) + let copyCount = min(row.cells.count, targetCols) + for i in 0.. 0 { + if (byte & 0xC0) == 0x80 { + utf8Buffer.append(byte) + if utf8Buffer.count == utf8ExpectedLength { + let bytes = utf8Buffer + utf8Buffer.removeAll(keepingCapacity: true) + utf8ExpectedLength = 0 + if let decoded = String(bytes: bytes, encoding: .utf8), let scalar = decoded.unicodeScalars.first { + printScalar(scalar) + } + } + return + } else { + // Interrupted UTF-8 sequence — drop incomplete bytes and handle this byte fresh. + utf8Buffer.removeAll(keepingCapacity: true) + utf8ExpectedLength = 0 + } + } + + if byte >= 0x80 { + if (byte & 0xE0) == 0xC0 { + utf8Buffer = [byte]; utf8ExpectedLength = 2 + } else if (byte & 0xF0) == 0xE0 { + utf8Buffer = [byte]; utf8ExpectedLength = 3 + } else if (byte & 0xF8) == 0xF0 { + utf8Buffer = [byte]; utf8ExpectedLength = 4 + } + return + } + + if byte < 0x20 || byte == 0x7F { + handleC0(byte) + } else { + let scalar = UnicodeScalar(byte) + printScalar(mapCharset(scalar)) + } + + case .escape: + handleEscape(byte) + + case .escapeIntermediate(let inter): + handleEscapeIntermediate(inter, final: byte) + + case .csiEntry: + if byte == 0x3F || byte == 0x3E || byte == 0x3C || byte == 0x3D { // ? > < = + csiPrefix = byte + parseState = .csiParam + } else { + parseState = .csiParam + handleCSIParam(byte) + } + + case .csiParam: + handleCSIParam(byte) + + case .oscString: + if byte == 0x07 { // BEL terminates OSC + finishOSC() + parseState = .ground + } else if byte == 0x1B { + parseState = .oscEsc + } else if oscBytes.count < Self.maxOSCBytes { + oscBytes.append(byte) + } + + case .oscEsc: + if byte == 0x5C { // ST (ESC \) + finishOSC() + parseState = .ground + } else { + finishOSC() + parseState = .escape + handleEscape(byte) + } + + case .dcsString: + if byte == 0x1B { + parseState = .dcsEsc + } + + case .dcsEsc: + if byte == 0x5C { // ST + parseState = .ground + } else if byte != 0x1B { + parseState = .dcsString + } + } + } + + private func handleC0(_ byte: UInt8) { + switch byte { + case 0x07: // BEL + break + case 0x08: // BS + pendingWrap = false + if cursorCol > 0 { cursorCol -= 1 } + markDirty(cursorRow) + case 0x09: // HT (Tab) + pendingWrap = false + var nextCol = cursorCol + 1 + while nextCol < cols - 1 && !tabStops.contains(nextCol) { + nextCol += 1 + } + cursorCol = min(cols - 1, nextCol) + markDirty(cursorRow) + case 0x0A, 0x0B, 0x0C: // LF, VT, FF + pendingWrap = false + if newlineMode { cursorCol = 0 } + lineFeed() + case 0x0D: // CR + pendingWrap = false + cursorCol = 0 + markDirty(cursorRow) + case 0x0E: // SO (G1) + activeCharsetG1 = true + case 0x0F: // SI (G0) + activeCharsetG1 = false + case 0x1B: // ESC + parseState = .escape + default: + break + } + } + + private func handleEscape(_ byte: UInt8) { + switch byte { + case 0x5B: // '[' -> CSI + csiPrefix = 0 + csiIntermediate = 0 + csiRawParams.removeAll(keepingCapacity: true) + parseState = .csiEntry + case 0x5D: // ']' -> OSC + oscBytes.removeAll(keepingCapacity: true) + parseState = .oscString + case 0x50, 0x58, 0x5E, 0x5F: // DCS (P), SOS (X), PM (^), APC (_) + parseState = .dcsString + case 0x20...0x2F: // Intermediate bytes (e.g. '(', ')', '#') + parseState = .escapeIntermediate(byte) + case 0x37: // '7' DECSC + saveCursor() + parseState = .ground + case 0x38: // '8' DECRC + restoreCursor() + parseState = .ground + case 0x44: // 'D' IND + pendingWrap = false + lineFeed() + parseState = .ground + case 0x45: // 'E' NEL + pendingWrap = false + cursorCol = 0 + lineFeed() + parseState = .ground + case 0x48: // 'H' HTS + tabStops.insert(cursorCol) + parseState = .ground + case 0x4D: // 'M' RI (Reverse Index) + pendingWrap = false + reverseIndex() + parseState = .ground + case 0x63: // 'c' RIS (Full Reset) + reset() + default: + parseState = .ground + } + } + + private func handleEscapeIntermediate(_ inter: UInt8, final byte: UInt8) { + if byte >= 0x20 && byte <= 0x2F { + // Multiple intermediates — keep consuming until final byte. + return + } + switch inter { + case 0x28: // '(' G0 charset + g0LineDrawing = (byte == 0x30) // '0' = DEC Special Graphics + case 0x29: // ')' G1 charset + g1LineDrawing = (byte == 0x30) + default: + break + } + parseState = .ground + } + + private func handleCSIParam(_ byte: UInt8) { + // C0 controls can be interleaved inside CSI sequences (VT100 spec). + if byte < 0x20 { + if byte == 0x18 || byte == 0x1A { // CAN / SUB cancels CSI + parseState = .ground + return + } + if byte == 0x1B { + parseState = .escape + return + } + handleC0(byte) + return + } + if (byte >= 0x30 && byte <= 0x3B) { // 0-9, :, ; + if csiRawParams.count < 256 { + csiRawParams.append(byte) + } + return + } + if byte >= 0x20 && byte <= 0x2F { // intermediate (e.g. SP for DECSCUSR) + csiIntermediate = byte + return + } + if byte >= 0x40 && byte <= 0x7E { // final byte + dispatchCSI(final: byte) + parseState = .ground + return + } + parseState = .ground + } + + // MARK: - Character Printing & Wrapping + + private func mapCharset(_ scalar: UnicodeScalar) -> UnicodeScalar { + let useLineDrawing = activeCharsetG1 ? g1LineDrawing : g0LineDrawing + guard useLineDrawing else { return scalar } + switch scalar.value { + case 0x60: return UnicodeScalar(0x25C6)! // ◆ + case 0x61: return UnicodeScalar(0x2592)! // ▒ + case 0x6A: return UnicodeScalar(0x2518)! // ┘ + case 0x6B: return UnicodeScalar(0x2510)! // ┐ + case 0x6C: return UnicodeScalar(0x250C)! // ┌ + case 0x6D: return UnicodeScalar(0x2514)! // └ + case 0x6E: return UnicodeScalar(0x253C)! // ┼ + case 0x71: return UnicodeScalar(0x2500)! // ─ + case 0x74: return UnicodeScalar(0x251C)! // ├ + case 0x75: return UnicodeScalar(0x2524)! // ┤ + case 0x76: return UnicodeScalar(0x2534)! // ┴ + case 0x77: return UnicodeScalar(0x252C)! // ┬ + case 0x78: return UnicodeScalar(0x2502)! // │ + default: return scalar + } + } + + private func printScalar(_ scalar: UnicodeScalar) { + let w = TerminalCharWidth.width(of: scalar) + + // Combining mark / variation selector / ZWJ attaches to the last printed cell. + if w == 0 { + if let pos = lastPrintedPos, pos.row < rows, pos.col < cols { + if !grid[pos.row].cells[pos.col].grapheme.isEmpty { + grid[pos.row].cells[pos.col].grapheme.unicodeScalars.append(scalar) + markDirty(pos.row) + } + } + return + } + + if pendingWrap { + pendingWrap = false + if autowrap { + grid[cursorRow].wrapped = true + cursorCol = 0 + lineFeed() + } + } + + // Wide char at the very last column wraps onto the next row first. + if w == 2 && cursorCol == cols - 1 { + if autowrap { + grid[cursorRow].cells[cursorCol] = .blank(bg: currentBg) + grid[cursorRow].wrapped = true + markDirty(cursorRow) + cursorCol = 0 + lineFeed() + } else { + return + } + } + + if insertMode { + shiftRowRight(row: cursorRow, from: cursorCol, count: w) + } + + clearOverwrittenWideCell(row: cursorRow, col: cursorCol) + if w == 2 && cursorCol + 1 < cols { + clearOverwrittenWideCell(row: cursorRow, col: cursorCol + 1) + } + + let ch = String(scalar) + grid[cursorRow].cells[cursorCol] = TerminalCell( + grapheme: ch == " " ? "" : ch, + width: UInt8(w), + fg: currentFg, + bg: currentBg, + style: currentStyle + ) + if w == 2 && cursorCol + 1 < cols { + grid[cursorRow].cells[cursorCol + 1] = .wideSpacer(fg: currentFg, bg: currentBg, style: currentStyle) + } + lastPrintedScalar = scalar + lastPrintedPos = (cursorRow, cursorCol) + markDirty(cursorRow) + + if cursorCol + w >= cols { + if autowrap { + pendingWrap = true + cursorCol = cols - 1 + } else { + cursorCol = cols - 1 + } + } else { + cursorCol += w + } + } + + private func clearOverwrittenWideCell(row: Int, col: Int) { + guard row >= 0 && row < rows && col >= 0 && col < cols else { return } + let existing = grid[row].cells[col] + if existing.width == 0 && col > 0 && grid[row].cells[col - 1].width == 2 { + grid[row].cells[col - 1] = .blank(bg: existing.bg) + } else if existing.width == 2 && col + 1 < cols && grid[row].cells[col + 1].width == 0 { + grid[row].cells[col + 1] = .blank(bg: existing.bg) + } + } + + // MARK: - Scrolling & Line Ops + + private func lineFeed() { + if cursorRow == scrollBottom { + scrollUp(count: 1) + } else if cursorRow < rows - 1 { + cursorRow += 1 + } + markDirty(cursorRow) + } + + private func reverseIndex() { + if cursorRow == scrollTop { + scrollDown(count: 1) + } else if cursorRow > 0 { + cursorRow -= 1 + } + markDirty(cursorRow) + } + + private func scrollUp(count: Int) { + let n = min(max(1, count), scrollBottom - scrollTop + 1) + let fullScreenRegion = (scrollTop == 0 && scrollBottom == rows - 1) + if fullScreenRegion && !isUsingAlternateScreen && maxScrollback > 0 { + for i in 0.. 0 else { return } + scrollback.append(row) + if scrollback.count > maxScrollback { + let excess = scrollback.count - maxScrollback + scrollback.removeFirst(excess) + } + } + + private func shiftRowRight(row: Int, from col: Int, count: Int) { + guard count > 0, col < cols else { return } + let n = min(count, cols - col) + clearOverwrittenWideCell(row: row, col: col) + for c in stride(from: cols - 1, through: col + n, by: -1) { + grid[row].cells[c] = grid[row].cells[c - n] + } + let blank = TerminalCell.blank(bg: currentBg) + for c in col..<(col + n) { + grid[row].cells[c] = blank + } + if grid[row].cells[cols - 1].width == 2 { + grid[row].cells[cols - 1] = blank + } + markDirty(row) + } + + private func shiftRowLeft(row: Int, from col: Int, count: Int) { + guard count > 0, col < cols else { return } + let n = min(count, cols - col) + clearOverwrittenWideCell(row: row, col: col) + if col + n < cols { + clearOverwrittenWideCell(row: row, col: col + n) + } + for c in col..<(cols - n) { + grid[row].cells[c] = grid[row].cells[c + n] + } + let blank = TerminalCell.blank(bg: currentBg) + for c in (cols - n).. [Int] { + guard !csiRawParams.isEmpty else { return [] } + let str = String(decoding: csiRawParams, as: UTF8.self) + return str.split(separator: ";", omittingEmptySubsequences: false).map { part in + // Take leading parameter before any ':' sub-param. + let head = part.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false).first ?? "" + // Digit runs too long for Int also count as the maximum, not 0 + // (which would mean "default"). + guard !head.isEmpty else { return 0 } + guard let value = Int(head) else { + return head.allSatisfy(\.isNumber) ? Self.maxCSIParam : 0 + } + return min(max(value, 0), Self.maxCSIParam) + } + } + + private func param(_ params: [Int], _ index: Int, default def: Int) -> Int { + guard index < params.count else { return def } + let val = params[index] + return val == 0 ? def : val + } + + private func dispatchCSI(final byte: UInt8) { + if csiPrefix == 0x3F { // '?' DEC Private Mode + handleDECPrivateCSI(final: byte) + return + } + if csiPrefix == 0x3E { // '>' Secondary DA + if byte == 0x63 { // 'c' + onReply?("\u{1b}[>0;10;1c") + } + return + } + if csiIntermediate == 0x20 && byte == 0x71 { // SP q -> DECSCUSR + let p = parseCSIParams().first ?? 0 + switch p { + case 0, 1, 2: cursorStyle = .block + case 3, 4: cursorStyle = .underline + case 5, 6: cursorStyle = .bar + default: break + } + markDirty(cursorRow) + return + } + + let params = parseCSIParams() + + switch byte { + case 0x41: // 'A' CUU + pendingWrap = false + let n = param(params, 0, default: 1) + let minRow = (cursorRow >= scrollTop) ? scrollTop : 0 + cursorRow = max(minRow, cursorRow - n) + case 0x42: // 'B' CUD + pendingWrap = false + let n = param(params, 0, default: 1) + let maxRow = (cursorRow <= scrollBottom) ? scrollBottom : rows - 1 + cursorRow = min(maxRow, cursorRow + n) + case 0x43: // 'C' CUF + pendingWrap = false + cursorCol = min(cols - 1, cursorCol + param(params, 0, default: 1)) + case 0x44: // 'D' CUB + pendingWrap = false + cursorCol = max(0, cursorCol - param(params, 0, default: 1)) + case 0x45: // 'E' CNL + pendingWrap = false + cursorCol = 0 + cursorRow = min(scrollBottom, cursorRow + param(params, 0, default: 1)) + case 0x46: // 'F' CPL + pendingWrap = false + cursorCol = 0 + cursorRow = max(scrollTop, cursorRow - param(params, 0, default: 1)) + case 0x47, 0x60: // 'G' CHA / '`' HPA + pendingWrap = false + cursorCol = max(0, min(cols - 1, param(params, 0, default: 1) - 1)) + case 0x48, 0x66: // 'H' CUP / 'f' HVP + pendingWrap = false + let r = param(params, 0, default: 1) - 1 + let c = param(params, 1, default: 1) - 1 + let baseRow = originMode ? scrollTop : 0 + let maxRow = originMode ? scrollBottom : rows - 1 + cursorRow = max(baseRow, min(maxRow, baseRow + r)) + cursorCol = max(0, min(cols - 1, c)) + case 0x64: // 'd' VPA + pendingWrap = false + let r = param(params, 0, default: 1) - 1 + cursorRow = max(0, min(rows - 1, r)) + case 0x49: // 'I' CHT + pendingWrap = false + // More tab stops than columns cannot move the cursor any further. + for _ in 0.. 0 && !tabStops.contains(prevCol) { prevCol -= 1 } + cursorCol = max(0, prevCol) + } + case 0x4A: // 'J' ED (Erase in Display) + pendingWrap = false + let mode = params.first ?? 0 + let blank = TerminalCell.blank(bg: currentBg) + switch mode { + case 0: // cursor to end + eraseRow(cursorRow, from: cursorCol, to: cols, fill: blank) + if cursorRow + 1 < rows { + for r in (cursorRow + 1).. 0 { + for r in 0..= scrollTop && cursorRow <= scrollBottom else { break } + let n = min(param(params, 0, default: 1), scrollBottom - cursorRow + 1) + let oldTop = scrollTop + scrollTop = cursorRow + scrollDown(count: n) + scrollTop = oldTop + case 0x4D: // 'M' DL (Delete Lines) + pendingWrap = false + guard cursorRow >= scrollTop && cursorRow <= scrollBottom else { break } + let n = min(param(params, 0, default: 1), scrollBottom - cursorRow + 1) + let oldTop = scrollTop + scrollTop = cursorRow + scrollUp(count: n) + scrollTop = oldTop + case 0x40: // '@' ICH (Insert Chars) + pendingWrap = false + shiftRowRight(row: cursorRow, from: cursorCol, count: param(params, 0, default: 1)) + case 0x50: // 'P' DCH (Delete Chars) + pendingWrap = false + shiftRowLeft(row: cursorRow, from: cursorCol, count: param(params, 0, default: 1)) + case 0x53: // 'S' SU (Scroll Up) + scrollUp(count: param(params, 0, default: 1)) + case 0x54: // 'T' SD (Scroll Down) + scrollDown(count: param(params, 0, default: 1)) + case 0x62: // 'b' REP (Repeat Preceding Graphic Char) + if let scalar = lastPrintedScalar { + let count = min(param(params, 0, default: 1), cols * rows) + for _ in 0..= 0 && bottom < rows && top < bottom { + scrollTop = top + scrollBottom = bottom + } else { + scrollTop = 0 + scrollBottom = rows - 1 + } + pendingWrap = false + cursorRow = originMode ? scrollTop : 0 + cursorCol = 0 + case 0x6D: // 'm' SGR + handleSGR() + case 0x68: // 'h' SM + for p in params { + if p == 4 { insertMode = true } + else if p == 20 { newlineMode = true } + } + case 0x6C: // 'l' RM + for p in params { + if p == 4 { insertMode = false } + else if p == 20 { newlineMode = false } + } + case 0x6E: // 'n' DSR (Device Status Report) + let p = params.first ?? 0 + if p == 6 { + let reportedRow = originMode ? (cursorRow - scrollTop + 1) : (cursorRow + 1) + onReply?("\u{1b}[\(reportedRow);\(cursorCol + 1)R") + } else if p == 5 { + onReply?("\u{1b}[0n") + } + case 0x63: // 'c' Primary DA + if (params.first ?? 0) == 0 { + onReply?("\u{1b}[?62;22c") + } + case 0x67: // 'g' TBC (Tab Clear) + let mode = params.first ?? 0 + if mode == 0 { tabStops.remove(cursorCol) } + else if mode == 3 { tabStops.removeAll() } + case 0x73: // 's' SCOSC + saveCursor() + case 0x75: // 'u' SCORC + restoreCursor() + default: + break + } + } + + private func handleDECPrivateCSI(final byte: UInt8) { + guard byte == 0x68 || byte == 0x6C else { return } // 'h' (DECSET) or 'l' (DECRST) + let enable = (byte == 0x68) + for mode in parseCSIParams() { + switch mode { + case 1: + applicationCursorKeys = enable + case 6: + originMode = enable + pendingWrap = false + cursorRow = enable ? scrollTop : 0 + cursorCol = 0 + case 7: + autowrap = enable + case 25: + cursorVisible = enable + markDirty(cursorRow) + case 47, 1047: + if enable { + enterAlternateScreen(saveCursorFirst: false, clearAlt: true) + } else { + leaveAlternateScreen(restoreCursorAfter: false) + } + case 1048: + if enable { saveCursor() } else { restoreCursor() } + case 1049: + if enable { + enterAlternateScreen(saveCursorFirst: true, clearAlt: true) + } else { + leaveAlternateScreen(restoreCursorAfter: true) + } + case 1000, 1002, 1003: + mouseReportingEnabled = enable + case 1006: + sgrMouseMode = enable + case 2004: + bracketedPasteMode = enable + case 2026: + if enable { + synchronizedOutputActive = true + } else { + synchronizedOutputActive = false + if pendingSyncDirty { + pendingSyncDirty = false + generation &+= 1 + } + } + default: + break + } + } + } + + // MARK: - SGR (Colors + Attributes, Semicolon & Colon Syntax) + + private func handleSGR() { + if csiRawParams.isEmpty { + resetSGR() + return + } + let raw = String(decoding: csiRawParams, as: UTF8.self) + let tokens = raw.split(separator: ";", omittingEmptySubsequences: false) + var i = 0 + while i < tokens.count { + let token = tokens[i] + if token.contains(":") { + applyColonSGR(token) + i += 1 + continue + } + let code = Int(token) ?? 0 + switch code { + case 0: resetSGR() + case 1: currentStyle.insert(.bold) + case 2: currentStyle.insert(.dim) + case 3: currentStyle.insert(.italic) + case 4: currentStyle.insert(.underline) + case 7: currentStyle.insert(.inverse) + case 8: currentStyle.insert(.hidden) + case 9: currentStyle.insert(.strikethrough) + case 21, 22: currentStyle.remove([.bold, .dim]) + case 23: currentStyle.remove(.italic) + case 24: currentStyle.remove(.underline) + case 27: currentStyle.remove(.inverse) + case 28: currentStyle.remove(.hidden) + case 29: currentStyle.remove(.strikethrough) + case 30...37: currentFg = .ansi(UInt8(code - 30)) + case 39: currentFg = .defaultForeground + case 40...47: currentBg = .ansi(UInt8(code - 40)) + case 49: currentBg = .defaultBackground + case 90...97: currentFg = .ansi(UInt8(code - 90 + 8)) + case 100...107: currentBg = .ansi(UInt8(code - 100 + 8)) + case 38, 48: + let isFg = (code == 38) + if i + 1 < tokens.count { + let kind = Int(tokens[i + 1]) ?? -1 + if kind == 5, i + 2 < tokens.count { + let idx = UInt8(clamping: Int(tokens[i + 2]) ?? 0) + if isFg { currentFg = .ansi(idx) } else { currentBg = .ansi(idx) } + i += 3 + continue + } else if kind == 2, i + 4 < tokens.count { + let r = UInt8(clamping: Int(tokens[i + 2]) ?? 0) + let g = UInt8(clamping: Int(tokens[i + 3]) ?? 0) + let b = UInt8(clamping: Int(tokens[i + 4]) ?? 0) + if isFg { currentFg = .rgb(r, g, b) } else { currentBg = .rgb(r, g, b) } + i += 5 + continue + } + } + default: + break + } + i += 1 + } + } + + /// Handles ISO-8613-3 colon-separated SGR params (`38:5:n`, `38:2::r:g:b`, `38:2:r:g:b`, `4:3`). + private func applyColonSGR(_ token: Substring) { + let parts = token.split(separator: ":", omittingEmptySubsequences: false).map { Int($0) } + guard let head = parts.first.flatMap({ $0 }) else { return } + switch head { + case 4: + let style = parts.count > 1 ? (parts[1] ?? 1) : 1 + if style == 0 { currentStyle.remove(.underline) } + else { currentStyle.insert(.underline) } + case 38, 48: + let isFg = (head == 38) + guard parts.count >= 3, let kind = parts[1] else { return } + if kind == 5, let idx = parts[2] { + let c: TerminalColor = .ansi(UInt8(clamping: idx)) + if isFg { currentFg = c } else { currentBg = c } + } else if kind == 2 { + // `38:2:colorspace:r:g:b` (6 parts) or `38:2:r:g:b` (5 parts) + if parts.count >= 6, let r = parts[3], let g = parts[4], let b = parts[5] { + let c: TerminalColor = .rgb(UInt8(clamping: r), UInt8(clamping: g), UInt8(clamping: b)) + if isFg { currentFg = c } else { currentBg = c } + } else if parts.count >= 5, let r = parts[2], let g = parts[3], let b = parts[4] { + let c: TerminalColor = .rgb(UInt8(clamping: r), UInt8(clamping: g), UInt8(clamping: b)) + if isFg { currentFg = c } else { currentBg = c } + } + } + default: + break + } + } + + private func resetSGR() { + currentFg = .defaultForeground + currentBg = .defaultBackground + currentStyle = [] + } + + // MARK: - OSC + + private func finishOSC() { + guard !oscBytes.isEmpty else { return } + let raw = String(decoding: oscBytes, as: UTF8.self) + oscBytes.removeAll(keepingCapacity: true) + guard let sep = raw.firstIndex(of: ";") else { return } + let code = raw[..= 0 && row < rows else { return } + let start = max(0, min(startCol, cols)) + let end = max(start, min(endCol, cols)) + guard start < end else { return } + clearOverwrittenWideCell(row: row, col: start) + if end < cols { + clearOverwrittenWideCell(row: row, col: end - 1) + } + for c in start..= 0 && row < rows else { return } + dirtyRows.insert(row) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalSurfaceView.swift b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalSurfaceView.swift new file mode 100644 index 00000000000..0fb206851bd --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalSurfaceView.swift @@ -0,0 +1,106 @@ +#if canImport(UIKit) +import SwiftUI +import UIKit + +/// SwiftUI wrapper around `CoreTextTerminalCanvasView`. +public struct TerminalSurfaceView: UIViewRepresentable { + public let emulator: TerminalEmulator + public let generation: UInt64 + public let fontSize: CGFloat + public let focusToken: Int + public let dismissKeyboardToken: Int + public let jumpToBottomToken: Int + public let onInput: (String) -> Void + public let onPaste: (String) -> Void + public let onGridSizeChange: (Int, Int) -> Void + public let onScrollOffsetChange: (Int) -> Void + public let onSendExcerpt: ((String) -> Void)? + public let onFontSizeChange: ((CGFloat) -> Void)? + public let onFocusChange: ((Bool) -> Void)? + + @Environment(\.hapiTheme) private var theme + + public init( + emulator: TerminalEmulator, + generation: UInt64, + fontSize: CGFloat, + focusToken: Int = 0, + dismissKeyboardToken: Int = 0, + jumpToBottomToken: Int = 0, + onInput: @escaping (String) -> Void, + onPaste: @escaping (String) -> Void, + onGridSizeChange: @escaping (Int, Int) -> Void, + onScrollOffsetChange: @escaping (Int) -> Void, + onSendExcerpt: ((String) -> Void)? = nil, + onFontSizeChange: ((CGFloat) -> Void)? = nil, + onFocusChange: ((Bool) -> Void)? = nil + ) { + self.emulator = emulator + self.generation = generation + self.fontSize = fontSize + self.focusToken = focusToken + self.dismissKeyboardToken = dismissKeyboardToken + self.jumpToBottomToken = jumpToBottomToken + self.onInput = onInput + self.onPaste = onPaste + self.onGridSizeChange = onGridSizeChange + self.onScrollOffsetChange = onScrollOffsetChange + self.onSendExcerpt = onSendExcerpt + self.onFontSizeChange = onFontSizeChange + self.onFocusChange = onFocusChange + } + + public final class Coordinator { + var lastFocusToken = 0 + var lastDismissToken = 0 + var lastJumpToken = 0 + } + + public func makeCoordinator() -> Coordinator { Coordinator() } + + public func makeUIView(context: Context) -> CoreTextTerminalCanvasView { + let view = CoreTextTerminalCanvasView( + emulator: emulator, + palette: TerminalPalette.forTheme(theme.variant), + fontSize: fontSize + ) + wireCallbacks(view) + return view + } + + public func updateUIView(_ view: CoreTextTerminalCanvasView, context: Context) { + if view.emulator !== emulator { + view.emulator = emulator + } + view.palette = TerminalPalette.forTheme(theme.variant) + if view.fontSize != fontSize { + view.fontSize = fontSize + } + wireCallbacks(view) + view.syncWithEmulator() + + if focusToken != context.coordinator.lastFocusToken { + context.coordinator.lastFocusToken = focusToken + _ = view.becomeFirstResponder() + } + if dismissKeyboardToken != context.coordinator.lastDismissToken { + context.coordinator.lastDismissToken = dismissKeyboardToken + _ = view.resignFirstResponder() + } + if jumpToBottomToken != context.coordinator.lastJumpToken { + context.coordinator.lastJumpToken = jumpToBottomToken + view.jumpToBottom() + } + } + + private func wireCallbacks(_ view: CoreTextTerminalCanvasView) { + view.onInput = onInput + view.onPaste = onPaste + view.onGridSizeChange = onGridSizeChange + view.onScrollOffsetChange = onScrollOffsetChange + view.onSendExcerpt = onSendExcerpt + view.onFontSizeChange = onFontSizeChange + view.onFocusChange = onFocusChange + } +} +#endif diff --git a/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalVectorGlyphs.swift b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalVectorGlyphs.swift new file mode 100644 index 00000000000..6d7b624e5f8 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiUI/Terminal/TerminalVectorGlyphs.swift @@ -0,0 +1,400 @@ +import CoreGraphics +import CoreText +import Foundation + +// MARK: - Whole-pixel CoreText Grid Metrics + +/// Whole-pixel monospaced cell geometry measured from `CTFont` at the display scale. +public struct TerminalGridMetrics: Equatable, Sendable { + public let fontSize: CGFloat + public let scale: CGFloat + public let cellWidth: CGFloat + public let cellHeight: CGFloat + public let baselineOffset: CGFloat + public let underlineOffset: CGFloat + public let underlineThickness: CGFloat + + public init(fontSize: CGFloat, scale: CGFloat = 2.0) { + let clampedSize = max(9, min(28, fontSize)) + let safeScale = max(1, scale) + self.fontSize = clampedSize + self.scale = safeScale + + let font = Self.makeFont(size: clampedSize, bold: false, italic: false) + let ascent = CTFontGetAscent(font) + let descent = CTFontGetDescent(font) + let leading = CTFontGetLeading(font) + + var glyph: CGGlyph = 0 + var char: UniChar = 0x004D // 'M' + CTFontGetGlyphsForCharacters(font, &char, &glyph, 1) + var advance = CGSize.zero + CTFontGetAdvancesForGlyphs(font, .horizontal, &glyph, &advance, 1) + let rawWidth = advance.width > 0 ? advance.width : clampedSize * 0.6 + + // Snap cell dimensions to whole device pixels so adjacent rows/columns never + // show subpixel seams on box-drawing lines or colored backgrounds. + let lineHeightRaw = ascent + descent + max(leading, clampedSize * 0.14) + self.cellWidth = ceil(rawWidth * safeScale) / safeScale + self.cellHeight = ceil(lineHeightRaw * safeScale) / safeScale + self.baselineOffset = ceil((ascent + (self.cellHeight - (ascent + descent)) * 0.45) * safeScale) / safeScale + self.underlineOffset = max(1, ceil(descent * 0.45 * safeScale) / safeScale) + self.underlineThickness = max(1 / safeScale, ceil(max(1.0, clampedSize / 14.0) * safeScale) / safeScale) + } + + public func gridSize(for bounds: CGSize, horizontalInset: CGFloat = 6, verticalInset: CGFloat = 4) -> (cols: Int, rows: Int) { + let usableW = max(0, bounds.width - horizontalInset * 2) + let usableH = max(0, bounds.height - verticalInset * 2) + let cols = max(20, Int(floor(usableW / max(1, cellWidth)))) + let rows = max(6, Int(floor(usableH / max(1, cellHeight)))) + return (cols, rows) + } + + public static func makeFont(size: CGFloat, bold: Bool, italic: Bool) -> CTFont { + let base = CTFontCreateUIFontForLanguage(.userFixedPitch, size, nil) + ?? CTFontCreateWithName("Menlo" as CFString, size, nil) + var traits: CTFontSymbolicTraits = [] + if bold { traits.insert(.traitBold) } + if italic { traits.insert(.traitItalic) } + guard !traits.isEmpty else { return base } + return CTFontCreateCopyWithSymbolicTraits(base, size, nil, traits, traits) ?? base + } +} + +// MARK: - Crisp CGPath Vector Box Drawing & Block Elements + +/// Renders Box Drawing (`U+2500...U+257F`) and Block Elements (`U+2580...U+259F`) +/// directly as pixel-snapped vector geometry, eliminating hairline seams in TUIs +/// (Claude Code Ink, Codex, Bubbletea, tmux, lazygit). +public enum TerminalVectorGlyphs { + public static func canDraw(_ grapheme: String) -> Bool { + guard grapheme.unicodeScalars.count == 1, let scalar = grapheme.unicodeScalars.first else { + return false + } + let v = scalar.value + return (0x2500...0x259F).contains(v) + } + + /// Draws the vector glyph into `rect` (UIKit top-down coordinates). Returns `true` if drawn. + @discardableResult + public static func draw( + _ grapheme: String, + in rect: CGRect, + color: CGColor, + scale: CGFloat, + context ctx: CGContext + ) -> Bool { + guard grapheme.unicodeScalars.count == 1, let scalar = grapheme.unicodeScalars.first else { + return false + } + let v = scalar.value + if (0x2580...0x259F).contains(v) { + return drawBlockElement(v, in: rect, color: color, context: ctx) + } + if (0x2500...0x257F).contains(v) { + return drawBoxDrawing(v, in: rect, color: color, scale: scale, context: ctx) + } + return false + } + + // MARK: Block Elements (U+2580..U+259F) + + private static func drawBlockElement(_ v: UInt32, in rect: CGRect, color: CGColor, context ctx: CGContext) -> Bool { + ctx.saveGState() + defer { ctx.restoreGState() } + ctx.setFillColor(color) + + let x = rect.minX, y = rect.minY, w = rect.width, h = rect.height + + switch v { + case 0x2580: // ▀ Upper half + ctx.fill(CGRect(x: x, y: y, width: w, height: h * 0.5)) + case 0x2581...0x2588: // ▁..█ Lower 1/8..8/8 + let frac = CGFloat(v - 0x2580) / 8.0 + let bh = h * frac + ctx.fill(CGRect(x: x, y: y + h - bh, width: w, height: bh)) + case 0x2589...0x258F: // ▉..▏ Left 7/8..1/8 + let frac = CGFloat(0x2590 - v) / 8.0 + ctx.fill(CGRect(x: x, y: y, width: w * frac, height: h)) + case 0x2590: // ▐ Right half + ctx.fill(CGRect(x: x + w * 0.5, y: y, width: w * 0.5, height: h)) + case 0x2591: // ░ Light shade + ctx.setAlpha(0.25); ctx.fill(rect) + case 0x2592: // ▒ Medium shade + ctx.setAlpha(0.50); ctx.fill(rect) + case 0x2593: // ▓ Dark shade + ctx.setAlpha(0.75); ctx.fill(rect) + case 0x2594: // ▔ Upper 1/8 + ctx.fill(CGRect(x: x, y: y, width: w, height: h / 8.0)) + case 0x2595: // ▕ Right 1/8 + ctx.fill(CGRect(x: x + w * 7.0 / 8.0, y: y, width: w / 8.0, height: h)) + case 0x2596...0x259F: // Quadrant blocks + let hw = w * 0.5, hh = h * 0.5 + let ul = CGRect(x: x, y: y, width: hw, height: hh) + let ur = CGRect(x: x + hw, y: y, width: hw, height: hh) + let ll = CGRect(x: x, y: y + hh, width: hw, height: hh) + let lr = CGRect(x: x + hw, y: y + hh, width: hw, height: hh) + switch v { + case 0x2596: ctx.fill(ll) + case 0x2597: ctx.fill(lr) + case 0x2598: ctx.fill(ul) + case 0x2599: ctx.fill([ul, ll, lr]) + case 0x259A: ctx.fill([ul, lr]) + case 0x259B: ctx.fill([ul, ur, ll]) + case 0x259C: ctx.fill([ul, ur, lr]) + case 0x259D: ctx.fill(ur) + case 0x259E: ctx.fill([ur, ll]) + case 0x259F: ctx.fill([ur, ll, lr]) + default: return false + } + default: + return false + } + return true + } + + // MARK: Box Drawing (U+2500..U+257F) + + private enum Arm: UInt8 { + case none = 0 + case light = 1 + case heavy = 2 + case double = 3 + } + + private static func drawBoxDrawing( + _ v: UInt32, + in rect: CGRect, + color: CGColor, + scale: CGFloat, + context ctx: CGContext + ) -> Bool { + let s = max(1, scale) + func snap(_ val: CGFloat) -> CGFloat { round(val * s) / s } + + let light = max(1 / s, snap(max(1.0, rect.width * 0.12))) + let heavy = max(light * 2, snap(max(2.0, rect.width * 0.24))) + let midX = snap(rect.midX) + let midY = snap(rect.midY) + + ctx.saveGState() + defer { ctx.restoreGState() } + ctx.setStrokeColor(color) + ctx.setFillColor(color) + ctx.setLineCap(.butt) + ctx.setLineJoin(.miter) + + // Rounded corners used heavily by Claude Code / Ink / Bubbletea (`╭ ╮ ╯ ╰`). + if (0x256D...0x2570).contains(v) { + let r = min(rect.width, rect.height) * 0.45 + let path = CGMutablePath() + switch v { + case 0x256D: // ╭ down + right + path.move(to: CGPoint(x: rect.maxX, y: midY)) + path.addArc(tangent1End: CGPoint(x: midX, y: midY), tangent2End: CGPoint(x: midX, y: rect.maxY), radius: r) + path.addLine(to: CGPoint(x: midX, y: rect.maxY)) + case 0x256E: // ╮ down + left + path.move(to: CGPoint(x: rect.minX, y: midY)) + path.addArc(tangent1End: CGPoint(x: midX, y: midY), tangent2End: CGPoint(x: midX, y: rect.maxY), radius: r) + path.addLine(to: CGPoint(x: midX, y: rect.maxY)) + case 0x256F: // ╯ up + left + path.move(to: CGPoint(x: rect.minX, y: midY)) + path.addArc(tangent1End: CGPoint(x: midX, y: midY), tangent2End: CGPoint(x: midX, y: rect.minY), radius: r) + path.addLine(to: CGPoint(x: midX, y: rect.minY)) + case 0x2570: // ╰ up + right + path.move(to: CGPoint(x: rect.maxX, y: midY)) + path.addArc(tangent1End: CGPoint(x: midX, y: midY), tangent2End: CGPoint(x: midX, y: rect.minY), radius: r) + path.addLine(to: CGPoint(x: midX, y: rect.minY)) + default: + break + } + ctx.setLineWidth(light) + ctx.addPath(path) + ctx.strokePath() + return true + } + + // Diagonals `╱ ╲ ╳` + if (0x2571...0x2573).contains(v) { + ctx.setLineWidth(light) + if v == 0x2571 || v == 0x2573 { + ctx.move(to: CGPoint(x: rect.minX, y: rect.maxY)) + ctx.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) + } + if v == 0x2572 || v == 0x2573 { + ctx.move(to: CGPoint(x: rect.minX, y: rect.minY)) + ctx.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) + } + ctx.strokePath() + return true + } + + // Dashed horizontal / vertical lines (`┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ ╌ ╍ ╎ ╏`) + if (0x2504...0x250B).contains(v) || (0x254C...0x254F).contains(v) { + let isHeavy = (v == 0x2505 || v == 0x2507 || v == 0x2509 || v == 0x250B || v == 0x254D || v == 0x254F) + let isVertical = (v == 0x2506 || v == 0x2507 || v == 0x250A || v == 0x250B || v == 0x254E || v == 0x254F) + let dashes = (v >= 0x254C) ? 2 : ((v >= 0x2508) ? 4 : 3) + let thick = isHeavy ? heavy : light + let total = isVertical ? rect.height : rect.width + let step = total / CGFloat(dashes) + let seg = max(1 / s, step * 0.6) + for i in 0.. (Arm, Arm, Arm, Arm)? { + // (left, right, up, down) + switch v { + case 0x2500: return (.light, .light, .none, .none) // ─ + case 0x2501: return (.heavy, .heavy, .none, .none) // ━ + case 0x2502: return (.none, .none, .light, .light) // │ + case 0x2503: return (.none, .none, .heavy, .heavy) // ┃ + case 0x250C: return (.none, .light, .none, .light) // ┌ + case 0x250D: return (.none, .heavy, .none, .light) // ┍ + case 0x250E: return (.none, .light, .none, .heavy) // ┎ + case 0x250F: return (.none, .heavy, .none, .heavy) // ┏ + case 0x2510: return (.light, .none, .none, .light) // ┐ + case 0x2511: return (.heavy, .none, .none, .light) // ┑ + case 0x2512: return (.light, .none, .none, .heavy) // ┒ + case 0x2513: return (.heavy, .none, .none, .heavy) // ┓ + case 0x2514: return (.none, .light, .light, .none) // └ + case 0x2515: return (.none, .heavy, .light, .none) // ┕ + case 0x2516: return (.none, .light, .heavy, .none) // ┖ + case 0x2517: return (.none, .heavy, .heavy, .none) // ┗ + case 0x2518: return (.light, .none, .light, .none) // ┘ + case 0x2519: return (.heavy, .none, .light, .none) // ┙ + case 0x251A: return (.light, .none, .heavy, .none) // ┚ + case 0x251B: return (.heavy, .none, .heavy, .none) // ┛ + case 0x251C: return (.none, .light, .light, .light) // ├ + case 0x251D: return (.none, .heavy, .light, .light) // ┝ + case 0x251E: return (.none, .light, .heavy, .light) // ┞ + case 0x251F: return (.none, .light, .light, .heavy) // ┟ + case 0x2520: return (.none, .light, .heavy, .heavy) // ┠ + case 0x2521: return (.none, .heavy, .heavy, .light) // ┡ + case 0x2522: return (.none, .heavy, .light, .heavy) // ┢ + case 0x2523: return (.none, .heavy, .heavy, .heavy) // ┣ + case 0x2524: return (.light, .none, .light, .light) // ┤ + case 0x2525: return (.heavy, .none, .light, .light) // ┥ + case 0x2526: return (.light, .none, .heavy, .light) // ┦ + case 0x2527: return (.light, .none, .light, .heavy) // ┧ + case 0x2528: return (.light, .none, .heavy, .heavy) // ┨ + case 0x2529: return (.heavy, .none, .heavy, .light) // ┩ + case 0x252A: return (.heavy, .none, .light, .heavy) // ┪ + case 0x252B: return (.heavy, .none, .heavy, .heavy) // ┫ + case 0x252C: return (.light, .light, .none, .light) // ┬ + case 0x252D: return (.heavy, .light, .none, .light) // ┭ + case 0x252E: return (.light, .heavy, .none, .light) // ┮ + case 0x252F: return (.heavy, .heavy, .none, .light) // ┯ + case 0x2530: return (.light, .light, .none, .heavy) // ┰ + case 0x2531: return (.heavy, .light, .none, .heavy) // ┱ + case 0x2532: return (.light, .heavy, .none, .heavy) // ┲ + case 0x2533: return (.heavy, .heavy, .none, .heavy) // ┳ + case 0x2534: return (.light, .light, .light, .none) // ┴ + case 0x2535: return (.heavy, .light, .light, .none) // ┵ + case 0x2536: return (.light, .heavy, .light, .none) // ┶ + case 0x2537: return (.heavy, .heavy, .light, .none) // ┷ + case 0x2538: return (.light, .light, .heavy, .none) // ┸ + case 0x2539: return (.heavy, .light, .heavy, .none) // ┹ + case 0x253A: return (.light, .heavy, .heavy, .none) // ┺ + case 0x253B: return (.heavy, .heavy, .heavy, .none) // ┻ + case 0x253C: return (.light, .light, .light, .light) // ┼ + case 0x254B: return (.heavy, .heavy, .heavy, .heavy) // ╋ + case 0x2550: return (.double, .double, .none, .none) // ═ + case 0x2551: return (.none, .none, .double, .double) // ║ + case 0x2552: return (.none, .double, .none, .light) // ╒ + case 0x2553: return (.none, .light, .none, .double) // ╓ + case 0x2554: return (.none, .double, .none, .double) // ╔ + case 0x2555: return (.double, .none, .none, .light) // ╕ + case 0x2556: return (.light, .none, .none, .double) // ╖ + case 0x2557: return (.double, .none, .none, .double) // ╗ + case 0x2558: return (.none, .double, .light, .none) // ╘ + case 0x2559: return (.none, .light, .double, .none) // ╙ + case 0x255A: return (.none, .double, .double, .none) // ╚ + case 0x255B: return (.double, .none, .light, .none) // ╛ + case 0x255C: return (.light, .none, .double, .none) // ╜ + case 0x255D: return (.double, .none, .double, .none) // ╝ + case 0x255E: return (.none, .double, .light, .light) // ╞ + case 0x255F: return (.none, .light, .double, .double)// ╟ + case 0x2560: return (.none, .double, .double, .double)// ╠ + case 0x2561: return (.double, .none, .light, .light) // ╡ + case 0x2562: return (.light, .none, .double, .double)// ╢ + case 0x2563: return (.double, .none, .double, .double)// ╣ + case 0x2564: return (.double, .double, .none, .light)// ╤ + case 0x2565: return (.light, .light, .none, .double) // ╥ + case 0x2566: return (.double, .double, .none, .double)// ╦ + case 0x2567: return (.double, .double, .light, .none)// ╧ + case 0x2568: return (.light, .light, .double, .none) // ╨ + case 0x2569: return (.double, .double, .double, .none)// ╩ + case 0x256A: return (.double, .double, .light, .light)// ╪ + case 0x256B: return (.light, .light, .double, .double)// ╫ + case 0x256C: return (.double, .double, .double, .double)// ╬ + case 0x2574: return (.light, .none, .none, .none) // ╴ + case 0x2575: return (.none, .none, .light, .none) // ╵ + case 0x2576: return (.none, .light, .none, .none) // ╶ + case 0x2577: return (.none, .none, .none, .light) // ╷ + case 0x2578: return (.heavy, .none, .none, .none) // ╸ + case 0x2579: return (.none, .none, .heavy, .none) // ╹ + case 0x257A: return (.none, .heavy, .none, .none) // ╺ + case 0x257B: return (.none, .none, .none, .heavy) // ╻ + case 0x257C: return (.light, .heavy, .none, .none) // ╼ + case 0x257D: return (.none, .none, .light, .heavy) // ╽ + case 0x257E: return (.heavy, .light, .none, .none) // ╾ + case 0x257F: return (.none, .none, .heavy, .light) // ╿ + default: + return nil + } + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift index 7ffce29107b..5cf5712cf53 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ChatInteractorTests.swift @@ -1653,4 +1653,27 @@ struct ChatInteractorTests { harness.events.contains(.notice("Session metadata is incomplete (missing: path, machineId)")) }) } + + @Test func failedSendDoesNotClobberMessageAlreadyConsumedBySSE() async throws { + let harness = try await ChatInteractionHarness(detail: chatDetail(thinking: true)) + await harness.performer.script("POST", "/api/sessions/sess-1/messages", status: 504, json: #"{"error":"Gateway timeout"}"#) + await harness.performer.gate("POST", pathSuffix: "/api/sessions/sess-1/messages") + + harness.interactor.setComposerText("hello") + harness.interactor.sendMessage() + #expect(await eventually { await harness.row(localId: "local-1")?.status == .sending }) + + // SSE echoes and consumes the message before the HTTP request times out with 504. + await harness.window().ingestSSEMessages([ + WindowMessage(wire: queuedServerRow(id: "srv-1", localId: "local-1", text: "hello")) + ]) + await harness.window().markConsumed(localIds: ["local-1"], invokedAt: 999) + await harness.performer.openGates() + + #expect(await eventually { !harness.interactor.composer.isSending }) + let row = try #require(await harness.row(localId: "local-1")) + #expect(row.id == "srv-1") + #expect(row.status == .sent) + #expect(row.invokedAt == .number(999)) + } } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ComposerPromptRecallTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ComposerPromptRecallTests.swift new file mode 100644 index 00000000000..ddcbe6eed0e --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ComposerPromptRecallTests.swift @@ -0,0 +1,40 @@ +import HapiClient +import Testing + +@Suite("ComposerPromptRecall") +struct ComposerPromptRecallTests { + @Test func entersRecallOnlyWhenEmptyAndStepsThroughHistory() { + var recall = ComposerPromptRecall() + let history = ["latest prompt", "latest prompt", "earlier prompt", "oldest prompt"] + + // Non-empty live draft does not hijack up-arrow caret navigation. + #expect(recall.stepUp(currentText: "in progress", history: history) == nil) + #expect(!recall.isActive) + + // Empty draft steps newest → oldest, collapsing consecutive duplicates. + #expect(recall.stepUp(currentText: "", history: history) == "latest prompt") + #expect(recall.index == 0) + #expect(recall.stepUp(currentText: "latest prompt", history: history) == "earlier prompt") + #expect(recall.index == 1) + #expect(recall.stepUp(currentText: "earlier prompt", history: history) == "oldest prompt") + #expect(recall.index == 2) + // Clamps at oldest. + #expect(recall.stepUp(currentText: "oldest prompt", history: history) == "oldest prompt") + #expect(recall.index == 2) + + // Stepping back down returns through newer prompts and finally clears recall. + #expect(recall.stepDown(history: history) == "earlier prompt") + #expect(recall.stepDown(history: history) == "latest prompt") + #expect(recall.stepDown(history: history) == "") + #expect(!recall.isActive) + #expect(recall.stepDown(history: history) == nil) + } + + @Test func resetExitsRecallImmediately() { + var recall = ComposerPromptRecall() + #expect(recall.stepUp(currentText: "", history: ["one", "two"]) == "one") + recall.reset() + #expect(!recall.isActive) + #expect(recall.stepDown(history: ["one", "two"]) == nil) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ContextWindowMetricsTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ContextWindowMetricsTests.swift new file mode 100644 index 00000000000..90acbdf93ea --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Chat/ContextWindowMetricsTests.swift @@ -0,0 +1,80 @@ +import HapiClient +import HapiProtocol +import Testing + +@Suite("ContextWindowMetrics") +struct ContextWindowMetricsTests { + @Test func resolvesExplicitWindowAndSeverityThresholds() throws { + let normalUsage = LatestUsage( + inputTokens: 1_000, + outputTokens: 500, + cacheCreation: 2_000, + cacheRead: 50_000, + contextSize: 60_000, + contextWindow: 200_000, + model: "claude-sonnet-4", + timestamp: 1_000 + ) + let normal = try #require(ContextWindowMetrics.resolve(usage: normalUsage, sessionModel: nil, flavor: "claude")) + #expect(normal.usedPercent == 30) + #expect(normal.remainingPercent == 70) + #expect(normal.severity == .normal) + + var warnUsage = normalUsage + warnUsage.contextSize = 150_000 // 75% + let warn = try #require(ContextWindowMetrics.resolve(usage: warnUsage, sessionModel: nil, flavor: "claude")) + #expect(warn.severity == .warning) + + var dangerUsage = normalUsage + dangerUsage.contextSize = 185_000 // 92.5% + let danger = try #require(ContextWindowMetrics.resolve(usage: dangerUsage, sessionModel: nil, flavor: "claude")) + #expect(danger.severity == .danger) + } + + @Test func fallsBackToModelAndFlavorBudgetsWhenExplicitWindowAbsent() throws { + let usage = LatestUsage( + inputTokens: 1_000, + outputTokens: 200, + cacheCreation: 0, + cacheRead: 0, + contextSize: 95_000, + contextWindow: nil, + model: nil, + timestamp: 1_000 + ) + // Claude opus preset uses 1M - 10k = 990k budget. + let claude = try #require(ContextWindowMetrics.resolve(usage: usage, sessionModel: "opus", flavor: "claude")) + #expect(claude.maxContextSize == 990_000) + + // Codex uses 258,400 - 10,000 = 248,400 budget. + let codex = try #require(ContextWindowMetrics.resolve(usage: usage, sessionModel: "gpt-5", flavor: "codex")) + #expect(codex.maxContextSize == 248_400) + + // Cursor parses bracketed [context=128k]. + let cursor = try #require(ContextWindowMetrics.resolve( + usage: usage, + sessionModel: "claude-4[context=128k]", + flavor: "cursor" + )) + #expect(cursor.maxContextSize == 118_000) + } + + @Test func formatsTokensAndElapsedDurations() { + #expect(ContextWindowMetrics.formatTokens(850) == "850") + #expect(ContextWindowMetrics.formatTokens(45_400) == "45k") + #expect(ContextWindowMetrics.formatTokens(1_250_000) == "1.2M") + #expect(ContextWindowMetrics.formatElapsed(sinceMs: 10_000, nowMs: 15_000) == "0:05") + #expect(ContextWindowMetrics.formatElapsed(sinceMs: 0, nowMs: 75_000) == "1:15") + #expect(ContextWindowMetrics.formatElapsed(sinceMs: 0, nowMs: 3_665_000) == "1:01:05") + } + + @Test func combinesStagedAndUnstagedDiffStats() { + let unstaged = NumstatParser.parse("10\t2\tsrc/a.swift\n4\t1\tsrc/b.swift\n") + let staged = NumstatParser.parse("5\t0\tsrc/a.swift\n3\t3\tsrc/c.swift\n") + let combined = SessionGitDiffStats.combine(unstaged: unstaged, staged: staged) + #expect(combined.insertions == 22) + #expect(combined.deletions == 6) + #expect(combined.changedFiles == 3) + #expect(combined.hasChanges) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/DiagnosticsTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/DiagnosticsTests.swift new file mode 100644 index 00000000000..ef2f0bd1426 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/DiagnosticsTests.swift @@ -0,0 +1,84 @@ +import Foundation +import HapiClient +import Testing + +@Suite("Diagnostics") +struct DiagnosticsTests { + @Test func redactorScrubsTokensJWTsLinksAndHubOrigins() { + let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJucyI6ImRlZmF1bHQifQ.signature_token_12345" + let raw = """ + Failed hapicompanion://bind?hub=https://my.secret.dev&code=supersecret + Authorization: Bearer tok_abcdef123456 + jwt=\(jwt) + https://app.hapi.run/?hub=https://my.secret.dev&token=secret99&pushKey=abc123 + """ + let scrubbed = DiagnosticRedactor.redact(raw) + #expect(!scrubbed.contains("supersecret")) + #expect(!scrubbed.contains("tok_abcdef123456")) + #expect(!scrubbed.contains(jwt)) + #expect(!scrubbed.contains("secret99")) + #expect(!scrubbed.contains("abc123")) + #expect(scrubbed.contains("hapicompanion://[REDACTED]")) + #expect(scrubbed.contains("Bearer [REDACTED]")) + #expect(scrubbed.contains("[REDACTED_JWT]")) + #expect(scrubbed.contains("token=[REDACTED]")) + #expect(scrubbed.contains("pushKey=[REDACTED]")) + + let originA = DiagnosticRedactor.redactHubOrigin("https://private.internal.example:3006") + let originB = DiagnosticRedactor.redactHubOrigin("https://other.internal.example") + #expect(!originA.contains("private.internal.example")) + #expect(originA.hasPrefix("https://hub-")) + #expect(originA.hasSuffix(":3006")) + #expect(originA != originB) + } + + @Test func ringBufferEnforcesCapacityAndScrubsEntries() { + let log = DiagnosticEventLog(capacity: 3) + for index in 0..<5 { + log.record(category: "sse", "event-\(index) token=secret\(index)") + } + let entries = log.snapshot() + #expect(entries.count == 3) + #expect(entries.map(\.message) == [ + "event-2 token=[REDACTED]", + "event-3 token=[REDACTED]", + "event-4 token=[REDACTED]", + ]) + } + + @Test func formattedReportIncludesKeySectionsWithoutLeakingSecrets() { + let snapshot = DiagnosticSnapshot( + generatedAt: Date(timeIntervalSince1970: 1_700_000_000), + appVersion: "1.2.3 (45)", + osVersion: "iOS 18.5", + platform: "iOS", + protocolVersion: 1, + pairedHubCount: 2, + activeHubRedacted: DiagnosticRedactor.redactHubOrigin("https://secret.home.arpa"), + hubHealthStatus: "ok (protocol v1)", + globalSSEState: "connected", + lastResumeVerdict: "ok", + sessionCount: 12, + onlineMachineCount: 2, + activeChatOpen: true, + activeChatReconnecting: false, + pushAuthorization: "authorized", + pushRegisteredHubCount: 2, + pushLastProblem: "Failed with token=leakme", + hangCount: 1, + crashCount: 0, + scrollHitchRatio: "1.25 ms/s", + recentEvents: [ + .init(timestamp: Date(timeIntervalSince1970: 1_700_000_000), category: "sse", message: "Connected scope=global resume=ok") + ] + ) + let report = snapshot.formattedReport() + #expect(report.contains("HAPI Diagnostics (Redacted)")) + #expect(report.contains("App: 1.2.3 (45) · iOS iOS 18.5 · protocol v1")) + #expect(report.contains("Hangs recorded: 1 · Crashes recorded: 0")) + #expect(report.contains("Scroll hitch ratio: 1.25 ms/s")) + #expect(!report.contains("secret.home.arpa")) + #expect(!report.contains("leakme")) + #expect(report.contains("token=[REDACTED]")) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Files/DiffReviewStoreTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Files/DiffReviewStoreTests.swift new file mode 100644 index 00000000000..32da922bee7 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Files/DiffReviewStoreTests.swift @@ -0,0 +1,98 @@ +import Foundation +import HapiClient +import Testing + +@Suite("DiffReviewStore") +@MainActor +struct DiffReviewStoreTests { + private func makeIsolatedDefaults() -> (UserDefaults, String) { + let suiteName = "hapi.diffReview.tests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + return (defaults, suiteName) + } + + @Test func upsertsReplacesPersistsAndClearsComments() { + let (defaults, suiteName) = makeIsolatedDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + + let store = DiffReviewStore(scope: "hub-a", defaults: defaults) + let first = DiffReviewComment( + path: "src/app.swift", + staged: false, + lineNumber: 12, + lineKind: .addition, + snippet: "+ let x = 1", + comment: " Rename x to count " + ) + store.upsert(first, sessionId: "s1") + + #expect(store.comments(forSession: "s1").count == 1) + #expect(store.comments(forSession: "s1").first?.comment == "Rename x to count") + #expect(store.commentedLineKeys(forSession: "s1", path: "src/app.swift", staged: false) == ["12:addition"]) + + // Same line replaces rather than duplicating. + let updated = DiffReviewComment( + path: "src/app.swift", + staged: false, + lineNumber: 12, + lineKind: .addition, + snippet: "+ let x = 1", + comment: "Use itemCount" + ) + store.upsert(updated, sessionId: "s1") + #expect(store.comments(forSession: "s1").count == 1) + #expect(store.comments(forSession: "s1").first?.comment == "Use itemCount") + + // Survives reload from UserDefaults. + let reloaded = DiffReviewStore(scope: "hub-a", defaults: defaults) + #expect(reloaded.comments(forSession: "s1").count == 1) + #expect(reloaded.comments(forSession: "s1").first?.comment == "Use itemCount") + + // Blank comment removes the line entry. + var cleared = updated + cleared.comment = " \n " + reloaded.upsert(cleared, sessionId: "s1") + #expect(reloaded.comments(forSession: "s1").isEmpty) + } + + @Test func formatsGroupedReviewPromptWithDiffSnippets() { + let comments = [ + DiffReviewComment( + path: "Sources/A.swift", + staged: false, + lineNumber: 40, + lineKind: .addition, + snippet: " func f() {\n+ fatalError()\n }", + comment: "Throw an error instead of crashing." + ), + DiffReviewComment( + path: "Sources/B.swift", + staged: true, + lineNumber: 8, + lineKind: .deletion, + snippet: "- guard ok else { return }", + comment: "Keep this guard." + ), + DiffReviewComment( + path: "Sources/A.swift", + staged: false, + lineNumber: 10, + lineKind: .context, + snippet: " let timeout = 5", + comment: "Make timeout configurable." + ), + ] + + let prompt = DiffReviewStore.formatReviewPrompt(comments) + #expect(prompt.contains("### `Sources/A.swift`")) + #expect(prompt.contains("### `Sources/B.swift`")) + #expect(prompt.contains("**Line 10** (context):")) + #expect(prompt.contains("**Line 40** (added):")) + #expect(prompt.contains("**Line 8** (staged, removed):")) + #expect(prompt.contains("```diff\n func f() {\n+ fatalError()\n }\n```")) + // Line 10 should sort before line 40 within Sources/A.swift. + let r10 = prompt.range(of: "**Line 10**")!.lowerBound + let r40 = prompt.range(of: "**Line 40**")!.lowerBound + #expect(r10 < r40) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/HubRegistryTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/HubRegistryTests.swift index c7b851300b1..a0592ecdec5 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/HubRegistryTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/HubRegistryTests.swift @@ -87,4 +87,36 @@ struct HubRegistryTests { #expect(registry.hubs.isEmpty) #expect(registry.activeHub == nil) } + + @Test func tracksHubIdsPerPairedHubAndCleansUpOnRemoval() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + let registry = HubRegistry(defaults: defaults) + registry.register("https://one.test") + registry.register("https://two.test") + registry.register("https://two-lan.test") + + // Unregistered hubs and blank ids are ignored. + registry.setHubId("hub-unregistered", for: "https://unknown.test") + registry.setHubId(" ", for: "https://one.test") + #expect(registry.hubId(for: "https://unknown.test") == nil) + #expect(registry.hubId(for: "https://one.test") == nil) + + registry.setHubId("hub-1", for: "https://ONE.test/") + registry.setHubId("hub-2", for: "https://two.test") + registry.setHubId("hub-2", for: "https://two-lan.test") + + #expect(registry.hubId(for: "https://one.test") == "hub-1") + #expect(registry.hubUrl(forHubId: "hub-1") == "https://one.test") + #expect(registry.hubUrls(forHubId: "hub-2") == ["https://two.test", "https://two-lan.test"]) + + // When multiple paired URLs share a hubId, the active hub comes first. + registry.setActiveHub("https://two-lan.test") + #expect(registry.hubUrls(forHubId: "hub-2") == ["https://two-lan.test", "https://two.test"]) + #expect(registry.hubUrl(forHubId: "hub-2") == "https://two-lan.test") + + registry.remove("https://two-lan.test") + #expect(registry.hubId(for: "https://two-lan.test") == nil) + #expect(registry.hubUrls(forHubId: "hub-2") == ["https://two.test"]) + } } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift index 56295fcd9b2..50aa8888bcb 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/MessageWindowControllerTests.swift @@ -801,6 +801,64 @@ struct MessageWindowControllerTests { #expect(files.count == 10) } + @Test func snapshotsRespectTotalByteBudgetAndRejectOversizedSingleSnapshot() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("hapi-window-budget-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: directory) } + // Budget fits roughly 2 small snapshots (~250 bytes each) but rejects a 2 KiB single payload. + let snapshots = WindowSnapshotStore(directory: directory, maxSessions: 10, maxTotalBytes: 900) + + let largePayload = String(repeating: "x", count: 1500) + snapshots.save( + sessionId: "too-big", + snapshot: PersistedMessageWindow( + messages: [buildOptimisticMessage(localId: "big-1", text: largePayload, createdAt: 1000, status: .sent)] + ) + ) + #expect(snapshots.load(sessionId: "too-big") == nil) + + for index in 0..<5 { + snapshots.save( + sessionId: "small-\(index)", + snapshot: PersistedMessageWindow( + messages: [WindowMessage(wire: agentRow(id: "s-\(index)", seq: 1, at: 1000 + index))] + ) + ) + } + let files = try FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: [.fileSizeKey] + ).filter { $0.lastPathComponent.hasSuffix(".window.json") } + let totalBytes = files.reduce(0) { sum, url in + sum + ((try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) + } + #expect(totalBytes <= 900) + #expect(files.count >= 1 && files.count < 5) + } + + @Test func debouncedPersistenceCoalescesBurstsAndFlushesOnDemand() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("hapi-window-debounce-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: directory) } + let snapshots = WindowSnapshotStore(directory: directory) + let provider = GatedMessagesProvider() + let controller = MessageWindowController( + sessionId: "debounced", + provider: provider, + snapshots: snapshots, + persistDebounce: .seconds(30) + ) + + await controller.ingestSSEMessages([WindowMessage(wire: agentRow(id: "m-1", seq: 1, at: 1000))]) + await controller.ingestSSEMessages([WindowMessage(wire: agentRow(id: "m-2", seq: 2, at: 2000))]) + // Not written synchronously before the debounce window fires. + #expect(snapshots.load(sessionId: "debounced") == nil) + + await controller.flushPersistence() + let persisted = try #require(snapshots.load(sessionId: "debounced")) + #expect(persisted.messages.map(\.id) == ["m-1", "m-2"]) + } + // MARK: - Seed @Test func seedFromCarriesRowsAndOlderCursorButForcesALatestReset() async { diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/PairingLogicTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/PairingLogicTests.swift index b4eccbbfaa4..f8a4daf4371 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/PairingLogicTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/PairingLogicTests.swift @@ -45,8 +45,9 @@ struct PairingLogicTests { ) } - private func healthJSON(protocolVersion: Int = 1, status: String = "ok") -> String { - "{\"status\":\"\(status)\",\"protocolVersion\":\(protocolVersion),\"capabilities\":{\"workGraph\":true}}" + private func healthJSON(protocolVersion: Int = 1, status: String = "ok", hubId: String? = nil) -> String { + let hubIdField = hubId.map { ",\"hubId\":\"\($0)\"" } ?? "" + return "{\"status\":\"\(status)\",\"protocolVersion\":\(protocolVersion)\(hubIdField),\"capabilities\":{\"workGraph\":true}}" } // MARK: - Success @@ -55,7 +56,7 @@ struct PairingLogicTests { let world = try makeWorld() defer { world.tearDown() } let jwt = freshJWT() - await world.performer.enqueue(status: 200, json: healthJSON()) + await world.performer.enqueue(status: 200, json: healthJSON(hubId: "hub-uuid-1")) await world.performer.enqueue(status: 200, json: authResponseJSON(token: jwt)) let paired = try await world.service.pair( @@ -70,6 +71,7 @@ struct PairingLogicTests { #expect(stored.jwt == jwt) #expect(world.registry.hubs == ["https://hub.example.com"]) #expect(world.registry.activeHub == "https://hub.example.com") + #expect(world.registry.hubId(for: "https://hub.example.com") == "hub-uuid-1") // Wire order: unauthenticated GET /health, then POST /api/auth with // the token passed through verbatim (opaque, incl. the namespace). diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Push/DeviceEndpointTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Push/DeviceEndpointTests.swift index 529cf245527..e31d100c692 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Push/DeviceEndpointTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Push/DeviceEndpointTests.swift @@ -3,6 +3,7 @@ import Foundation import FoundationNetworking // URLSession types live here on Linux #endif import HapiClient +import HapiProtocol import Testing @Suite("Device registration endpoints") @@ -60,4 +61,29 @@ struct DeviceEndpointTests { #expect(apiError.status == 400) #expect(apiError.code == "Invalid body") } + + @Test func registerSendsPreferencesAndDecodesHubId() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: #"{"ok":true,"hubId":"hub-uuid-42"}"#) + + let response = try await harness.client.registerDevice( + token: "a1b2c3", + deviceId: "device-uuid-1", + pushKey: "KZFhIWo=", + preferences: PushNotificationPreferences( + ready: false, + permissionRequest: true, + inputRequest: false, + modelError: true + ) + ) + + #expect(response == DeviceRegisterResponse(ok: true, hubId: "hub-uuid-42")) + let request = await harness.performer.requests.first + let body = try #require(bodyString(request)) + #expect( + body + == #"{"deviceId":"device-uuid-1","platform":"ios","preferences":{"inputRequest":false,"modelError":true,"permissionRequest":true,"ready":false},"pushKey":"KZFhIWo=","token":"a1b2c3"}"# + ) + } } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Push/PushPayloadTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Push/PushPayloadTests.swift index 15690153bf7..bacf092e0d5 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Push/PushPayloadTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Push/PushPayloadTests.swift @@ -14,6 +14,7 @@ struct PushPayloadTests { "requestId": "req-9", "severity": "warning", "contractVersion": "1", + "hubId": "hub-uuid-7", ] @Test func parsesEveryContractField() throws { @@ -28,10 +29,18 @@ struct PushPayloadTests { #expect(payload.requestId == "req-9") #expect(payload.severity == .warning) #expect(payload.contractVersion == "1") + #expect(payload.hubId == "hub-uuid-7") #expect(payload.supportsActions) #expect(payload.categoryIdentifier == "permission-request") } + @Test func blankHubIdDecodesAsNil() throws { + var fields = fullFields + fields["hubId"] = " " + let payload = try #require(PushPayload.parse(dictionary: fields)) + #expect(payload.hubId == nil) + } + @Test func missingSessionIdDropsTheMessage() { var fields = fullFields fields["sessionId"] = nil diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/SSE/SSEClientTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/SSE/SSEClientTests.swift index 25e1619ae91..6a6b463a62d 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/SSE/SSEClientTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/SSE/SSEClientTests.swift @@ -23,7 +23,8 @@ struct SSEClientTests { tokens: [String?] = ["tok-1"], pathObserver: FakePathObserver? = nil, transport: FakeTransport = FakeTransport(), - clock: ManualClock = ManualClock() + clock: ManualClock = ManualClock(), + foregroundLivenessProbe: (@Sendable (_ subscriptionId: String?) async -> Bool)? = nil ) async -> Harness { let tokenSource = TokenSource(tokens) let configuration = SSEClientConfiguration( @@ -31,7 +32,8 @@ struct SSEClientTests { tokenProvider: { tokenSource.next() }, scope: scope, visibility: visibility, - jitterMs: { 0 } + jitterMs: { 0 }, + foregroundLivenessProbe: foregroundLivenessProbe ) let client = SSEClient( configuration: configuration, @@ -259,6 +261,63 @@ struct SSEClientTests { await h.client.stop() } + @Test func resumeAfterBriefSilenceRunsProbeAndReconnectsOnFailure() async throws { + actor ProbeCapture { + var lastSubscriptionId: String? + func record(_ id: String?) { lastSubscriptionId = id } + } + let capture = ProbeCapture() + let h = await makeHarness(foregroundLivenessProbe: { subId in + await capture.record(subId) + return false + }) + let first = try #require(await h.transport.nextConnection()) + first.open() + first.sendHandshake(resume: "ok", subscriptionId: "sub-dead") + #expect(await waitUntil { !h.box.handshakes.isEmpty }) + + await h.client.suspend() + h.clock.advance(byMs: 15_000) // in the 5..45 s active probe window + await h.client.resume() + + _ = try #require(await h.transport.nextConnection()) + #expect(await capture.lastSubscriptionId == "sub-dead") + #expect(first.isTerminated) + await h.client.stop() + } + + @Test func resumeAfterBriefSilenceTightensDeadlineWhenNoBytesArrive() async throws { + let h = await makeHarness(foregroundLivenessProbe: { _ in true }) + let first = try #require(await h.transport.nextConnection()) + first.open() + first.sendHandshake(resume: "ok", subscriptionId: "sub-half-open") + #expect(await waitUntil { !h.box.handshakes.isEmpty }) + + await h.client.suspend() + h.clock.advance(byMs: 15_000) + await h.client.resume() + #expect(await h.transport.expectNoConnection()) + + // Advance past the 35 s post-resume heartbeat grace (still far below the 90 s staleness timeout). + await advanceOnceSleeperParked(h.clock, byMs: 25_000) + _ = try #require(await h.transport.nextConnection()) + #expect(first.isTerminated) + await h.client.stop() + } + + @Test func resumeWithHungConnectAttemptAbandonsAfterThreeSeconds() async throws { + let h = await makeHarness() + let first = try #require(await h.transport.nextConnection()) + // Connection never opened before backgrounding. + await h.client.suspend() + h.clock.advance(byMs: 4_000) + await h.client.resume() + + _ = try #require(await h.transport.nextConnection()) + #expect(first.isTerminated) + await h.client.stop() + } + // MARK: - Event delivery @Test func eventsAreYieldedInArrivalOrder() async throws { diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/AgentProfileStoreTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/AgentProfileStoreTests.swift new file mode 100644 index 00000000000..1bec196b034 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/AgentProfileStoreTests.swift @@ -0,0 +1,49 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +@Suite("AgentProfileStore") +@MainActor +struct AgentProfileStoreTests { + private func makeIsolatedDefaults() -> (UserDefaults, String) { + let suiteName = "hapi.profiles.tests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + return (defaults, suiteName) + } + + @Test func savesFiltersReloadsAndDeletesProfiles() { + let (defaults, suiteName) = makeIsolatedDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + + let store = AgentProfileStore(defaults: defaults) + let fast = AgentProfile( + name: "Fast Claude", + flavor: "claude", + model: "sonnet", + effort: "low", + permissionMode: .default + ) + let deep = AgentProfile( + name: "Deep Codex", + flavor: "codex", + model: "o3", + effort: "high", + permissionMode: .yolo + ) + store.save(deep) + store.save(fast) + + #expect(store.profiles.count == 2) + #expect(store.profiles(forFlavor: "claude") == [fast]) + #expect(store.profiles(forFlavor: "codex") == [deep]) + #expect(fast.summaryText == "sonnet · low · default") + + let reloaded = AgentProfileStore(defaults: defaults) + #expect(reloaded.profiles == store.profiles) + + reloaded.delete(id: fast.id) + #expect(reloaded.profiles(forFlavor: "claude").isEmpty) + #expect(reloaded.profiles(forFlavor: "codex") == [deep]) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/PushNotificationPrefsTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/PushNotificationPrefsTests.swift new file mode 100644 index 00000000000..92d49ea11ee --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/PushNotificationPrefsTests.swift @@ -0,0 +1,47 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +@MainActor +@Suite("PushNotificationPrefs") +struct PushNotificationPrefsTests { + @Test func defaultsToAllEnabledAndPersistsChanges() throws { + let suiteName = "PushNotificationPrefsTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let first = PushNotificationPrefs(defaults: defaults) + #expect(first.preferences == .allEnabled) + + let updated = PushNotificationPreferences( + ready: false, + permissionRequest: true, + inputRequest: false, + modelError: true + ) + first.setPreferences(updated) + + let reloaded = PushNotificationPrefs(defaults: defaults) + #expect(reloaded.preferences == updated) + } + + @Test func fallsBackToAllEnabledOnCorruptDataAndDefaultsMissingKeys() throws { + let suiteName = "PushNotificationPrefsTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + defaults.set(Data("not-json".utf8), forKey: PushNotificationPrefs.preferencesKey) + #expect(PushNotificationPrefs(defaults: defaults).preferences == .allEnabled) + + defaults.set(Data(#"{"ready":false}"#.utf8), forKey: PushNotificationPrefs.preferencesKey) + #expect( + PushNotificationPrefs(defaults: defaults).preferences == PushNotificationPreferences( + ready: false, + permissionRequest: true, + inputRequest: true, + modelError: true + ) + ) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/QuotaPaceTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/QuotaPaceTests.swift new file mode 100644 index 00000000000..6c2bf211428 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/QuotaPaceTests.swift @@ -0,0 +1,47 @@ +import Foundation +import HapiClient +import Testing + +@Suite("QuotaPace") +struct QuotaPaceTests { + @Test func infersCommonWindowDurations() { + #expect(QuotaPace.inferWindowSeconds(window: "5h") == 18_000) + #expect(QuotaPace.inferWindowSeconds(window: "weekly") == 604_800) + #expect(QuotaPace.inferWindowSeconds(window: "24h") == 86_400) + #expect(QuotaPace.inferWindowSeconds(window: "30m") == 1_800) + #expect(QuotaPace.inferWindowSeconds(window: nil, id: "claude-five_hour", label: "Current session") == 18_000) + #expect(QuotaPace.inferWindowSeconds(window: nil, id: "claude-seven_day", label: "Weekly") == 604_800) + #expect(QuotaPace.inferWindowSeconds(window: nil, id: "x", label: "3d window") == 259_200) + #expect(QuotaPace.inferWindowSeconds(window: nil, id: "unknown", label: "Rate limit") == nil) + } + + @Test func evaluatesOnTrackTightRunsOutAndReached() { + let now = Date(timeIntervalSince1970: 1_700_000_000) + let fiveHours: TimeInterval = 5 * 3_600 + + // Halfway through 5h window (2.5h elapsed, 2.5h left) + let reset = now.addingTimeInterval(2.5 * 3_600) + + #expect(QuotaPace.evaluate(usedPercent: 30, resetDate: reset, windowSeconds: fiveHours, now: now) == .onTrack) + #expect(QuotaPace.evaluate(usedPercent: 46, resetDate: reset, windowSeconds: fiveHours, now: now) == .tight) + #expect(QuotaPace.evaluate(usedPercent: 100, resetDate: reset, windowSeconds: fiveHours, now: now) == .reached) + + // 75% used in 2.5h -> remaining 25% lasts 2.5h / 3 = 50 minutes + let fastPace = QuotaPace.evaluate(usedPercent: 75, resetDate: reset, windowSeconds: fiveHours, now: now) + if case .runsOut(let projected) = fastPace { + #expect(abs(projected.timeIntervalSince(now) - 3_000) < 1) + } else { + Issue.record("Expected .runsOut, got \(fastPace)") + } + } + + @Test func suppressesNoisyEarlyWindowEstimates() { + let now = Date(timeIntervalSince1970: 1_700_000_000) + let fiveHours: TimeInterval = 5 * 3_600 + // Only 30 seconds into a 5h window (minimumElapsed is 180s) + let reset = now.addingTimeInterval(fiveHours - 30) + #expect(QuotaPace.evaluate(usedPercent: 10, resetDate: reset, windowSeconds: fiveHours, now: now) == .unknown) + // Reset already passed + #expect(QuotaPace.evaluate(usedPercent: 50, resetDate: now.addingTimeInterval(-10), windowSeconds: fiveHours, now: now) == .unknown) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/QuotaPresentationTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/QuotaPresentationTests.swift new file mode 100644 index 00000000000..08541890068 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/QuotaPresentationTests.swift @@ -0,0 +1,149 @@ +import Foundation +import HapiProtocol +import XCTest +@testable import HapiClient + +final class QuotaPresentationTests: XCTestCase { + // MARK: - ConciseErrorSummary + + func testConciseErrorExtractsFirstMeaningfulLineFromStackTrace() { + let raw = """ + RPC call timed out after 5000ms + at queryCodexQuota (/Users/dev/hapi/cli/src/agent/agentQuotas.ts:595:17) + at async Promise.all (index 0) + """ + let concise = ConciseErrorSummary.concise(raw) + XCTAssertEqual(concise, "RPC call timed out after 5000ms") + XCTAssertTrue(ConciseErrorSummary.hasExtraDetail(raw: raw, concise: concise)) + } + + func testConciseErrorExtractsNestedJSONMessage() { + let raw = """ + { + "error": { + "type": "rate_limit_error", + "message": "Too many requests; retry later." + } + } + """ + let concise = ConciseErrorSummary.concise(raw) + XCTAssertEqual(concise, "Too many requests; retry later.") + XCTAssertTrue(ConciseErrorSummary.hasExtraDetail(raw: raw, concise: concise)) + } + + func testConciseErrorExtractsPrefixedJSONMessage() { + let raw = #"HTTP 429: {"error":{"message":"Quota check rate limited"}}"# + let concise = ConciseErrorSummary.concise(raw) + XCTAssertEqual(concise, "HTTP 429: Quota check rate limited") + XCTAssertTrue(ConciseErrorSummary.hasExtraDetail(raw: raw, concise: concise)) + } + + func testConciseErrorLeavesShortSingleLineUntouched() { + let raw = "Not signed in to Codex" + let concise = ConciseErrorSummary.concise(raw) + XCTAssertEqual(concise, raw) + XCTAssertFalse(ConciseErrorSummary.hasExtraDetail(raw: raw, concise: concise)) + } + + func testConciseErrorTruncatesLongSingleLineCleanly() { + let raw = String(repeating: "a", count: 160) + let concise = ConciseErrorSummary.concise(raw, maxLength: 40) + XCTAssertEqual(concise.count, 40) + XCTAssertTrue(concise.hasSuffix("…")) + XCTAssertTrue(ConciseErrorSummary.hasExtraDetail(raw: raw, concise: concise)) + } + + // MARK: - QuotaPresentation + + func testPartitionAccountsSeparatesHealthyFromUnavailable() { + let bucket = UsageQuotasResponse.Bucket( + id: "5h", + label: "5h window", + window: "5h", + remainingPercent: 80, + usedPercent: 20 + ) + let codexOk = UsageQuotasResponse.Account(agent: .codex, status: "ok", buckets: [bucket]) + let custom = UsageQuotasResponse.Account(agent: .claude, status: "custom_provider", note: "API key") + let agyErr = UsageQuotasResponse.Account(agent: .agy, status: "error", note: "CLI crashed\nstack...") + let geminiUnauth = UsageQuotasResponse.Account(agent: .gemini, status: "unauthenticated") + + let partition = QuotaPresentation.partitionAccounts([codexOk, custom, agyErr, geminiUnauth]) + XCTAssertEqual(partition.healthy.map(\.agent), [.codex, .claude]) + XCTAssertEqual(partition.unavailable.map(\.agent), [.agy, .gemini]) + } + + func testPlanWithoutPreferredMachineSeparatesHealthyAndFailingMachines() { + let bucket = UsageQuotasResponse.Bucket( + id: "5h", + label: "5h", + remainingPercent: 75, + usedPercent: 25 + ) + let okMachine = UsageQuotasResponse.Machine( + machineId: "m-ok", + machineName: "MacBook Pro", + accounts: [.init(agent: .codex, status: "ok", buckets: [bucket])] + ) + let failedMachine = UsageQuotasResponse.Machine( + machineId: "m-err", + machineName: "Linux Box", + error: "RPC timed out" + ) + let oldRunner = UsageQuotasResponse.Machine( + machineId: "m-old", + machineName: "Old Runner", + supported: false + ) + + let plan = QuotaPresentation.plan(machines: [okMachine, failedMachine, oldRunner]) + XCTAssertEqual(plan.primaryMachines.map(\.machineId), ["m-ok"]) + XCTAssertEqual(plan.unavailableMachines.map(\.machineId), ["m-err", "m-old"]) + XCTAssertTrue(plan.otherMachines.isEmpty) + } + + func testPlanWithPreferredMachineTucksOtherMachinesAndErrorsOutOfPrimaryView() { + let bucket = UsageQuotasResponse.Bucket( + id: "5h", + label: "5h", + remainingPercent: 60, + usedPercent: 40 + ) + let current = UsageQuotasResponse.Machine( + machineId: "m-1", + machineName: "Mac Studio", + accounts: [ + .init(agent: .codex, status: "ok", buckets: [bucket]), + .init(agent: .claude, status: "error", note: "Long error\nline 2") + ] + ) + let failingOther = UsageQuotasResponse.Machine( + machineId: "m-2", + machineName: "Mini", + error: "RPC failed" + ) + + let plan = QuotaPresentation.plan(machines: [current, failingOther], preferredMachineId: "m-1") + XCTAssertEqual(plan.primaryMachines.map(\.machineId), ["m-1"]) + XCTAssertTrue(plan.unavailableMachines.isEmpty) + XCTAssertEqual(plan.otherMachines.map(\.machineId), ["m-2"]) + } + + func testPlanWithFailingPreferredMachineKeepsCurrentMachineFocusedWithoutDumpingOthers() { + let currentFailing = UsageQuotasResponse.Machine( + machineId: "m-1", + machineName: "Mac Studio", + error: "RPC timed out" + ) + let healthyOther = UsageQuotasResponse.Machine( + machineId: "m-2", + machineName: "MacBook", + accounts: [.init(agent: .codex, status: "ok", creditsLabel: "Unlimited credits")] + ) + + let plan = QuotaPresentation.plan(machines: [currentFailing, healthyOther], preferredMachineId: "m-1") + XCTAssertTrue(plan.primaryMachines.isEmpty) + XCTAssertEqual(plan.unavailableMachines.map(\.machineId), ["m-1"]) + XCTAssertEqual(plan.otherMachines.map(\.machineId), ["m-2"]) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/ProjectGroupCollapseStoreTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/ProjectGroupCollapseStoreTests.swift new file mode 100644 index 00000000000..e7c92b055c0 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/ProjectGroupCollapseStoreTests.swift @@ -0,0 +1,53 @@ +import Foundation +import HapiClient +import Testing + +@Suite("ProjectGroupCollapseStore & ProjectGroupIdentity") +@MainActor +struct ProjectGroupCollapseStoreTests { + @Test func buildsDistinctKeysPerMachineAndDisambiguatesSameMachineDuplicates() { + let k1 = ProjectGroupIdentity.groupKey(machineId: "mac", path: "/Users/dev/work/hapi/") + let k2 = ProjectGroupIdentity.groupKey(machineId: "mac", path: "/Users/dev/oss/hapi") + let k3 = ProjectGroupIdentity.groupKey(machineId: "linux", path: "/Users/dev/work/hapi") + let k4 = ProjectGroupIdentity.groupKey(machineId: "mac", path: nil) + + #expect(k1 != k2) + #expect(k1 != k3) + #expect(k1 == "mac|/Users/dev/work/hapi") + + let titles = ProjectGroupIdentity.disambiguatedTitles(for: [ + (key: k1, machineId: "mac", path: "/Users/dev/work/hapi/"), + (key: k2, machineId: "mac", path: "/Users/dev/oss/hapi"), + (key: k3, machineId: "linux", path: "/Users/dev/work/hapi"), + (key: k4, machineId: "mac", path: nil), + ]) + + // Same machine duplicate basenames get shortest distinguishing parent suffix. + #expect(titles[k1] == "work/hapi") + #expect(titles[k2] == "oss/hapi") + // Different machine has no collision on that machine, so keeps clean basename. + #expect(titles[k3] == "hapi") + #expect(titles[k4] == "Other") + } + + @Test func persistsCollapsedProjectKeysPerScope() { + let suite = "hapi.projectCollapse.tests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + + let store = ProjectGroupCollapseStore(scope: "hub-1", defaults: defaults) + #expect(!store.isCollapsed("mac|/work/hapi")) + + store.toggle("mac|/work/hapi") + #expect(store.isCollapsed("mac|/work/hapi")) + + let reloaded = ProjectGroupCollapseStore(scope: "hub-1", defaults: defaults) + #expect(reloaded.isCollapsed("mac|/work/hapi")) + + reloaded.expand("mac|/work/hapi") + #expect(!reloaded.isCollapsed("mac|/work/hapi")) + + let reloadedAgain = ProjectGroupCollapseStore(scope: "hub-1", defaults: defaults) + #expect(!reloadedAgain.isCollapsed("mac|/work/hapi")) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionGroupsTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionGroupsTests.swift new file mode 100644 index 00000000000..bd7d504e9e8 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionGroupsTests.swift @@ -0,0 +1,423 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif +@testable import HapiClient +import HapiProtocol +import Testing + +/// Ports `web/src/lib/sessionGroups.test.ts` and the dissolve orchestration cases +/// from `web/src/components/SessionList.groups.test.tsx`. +@MainActor +@Suite("SessionGroups") +struct SessionGroupsTests { + private func makeSession( + _ id: String, + active: Bool = false, + thinking: Bool = false, + updatedAt: Int = 0, + createdAt: Int? = 0, + lastUserMessageAt: Int? = nil, + pinned: Bool? = nil, + globalPinned: Bool? = nil, + path: String = "/repo", + machineId: String? = nil, + name: String? = nil, + groupLeaderId: String? = nil, + lifecycleState: String? = nil, + worktree: WorktreeMetadata? = nil, + pendingRequestsCount: Int = 0, + backgroundTaskCount: Int = 0, + derivedToolWork: Bool? = nil, + attachedJob: AttachedJob? = nil + ) -> SessionSummary { + SessionSummary( + id: id, + active: active, + thinking: thinking, + activeAt: 0, + updatedAt: updatedAt, + createdAt: createdAt, + lastUserMessageAt: lastUserMessageAt, + pinned: pinned, + globalPinned: globalPinned, + metadata: SessionSummaryMetadata( + name: name, + path: path, + machineId: machineId, + flavor: "claude", + worktree: worktree, + groupLeaderId: groupLeaderId, + lifecycleState: lifecycleState + ), + metadataVersion: 0, + agentStateVersion: 0, + todosUpdatedAt: 0, + pendingRequestsCount: pendingRequestsCount, + backgroundTaskCount: backgroundTaskCount, + derivedToolWork: derivedToolWork, + attachedJob: attachedJob + ) + } + + private nonisolated func archived(_ session: SessionSummary) -> SessionSummary { + var copy = session + copy.active = false + copy.metadata?.lifecycleState = SessionLifecycle.archived + return copy + } + + // MARK: - layout + + @Test func nestsMembersUnderLeaderAndLeavesOtherSessionsAtTopLevel() { + let sessions = [ + makeSession("leader"), + makeSession("m1", groupLeaderId: "leader"), + makeSession("solo"), + makeSession("m2", groupLeaderId: "leader"), + ] + let layout = SessionGroups.layout(known: sessions, visible: sessions) + + #expect(layout.topLevel.map(\.id) == ["leader", "solo"]) + #expect(layout.membersByLeader["leader"]?.map(\.id) == ["m1", "m2"]) + #expect(layout.leaderIdByMember["m2"] == "leader") + } + + @Test func nestsMemberInAnotherDirectoryOrMachine() { + let sessions = [ + makeSession("leader"), + makeSession("m1", path: "/elsewhere", machineId: "other", groupLeaderId: "leader"), + ] + let layout = SessionGroups.layout(known: sessions, visible: sessions) + #expect(layout.topLevel.map(\.id) == ["leader"]) + #expect(layout.membersByLeader["leader"]?.map(\.id) == ["m1"]) + } + + @Test func keepsMemberAsOrdinaryRowWhenLeaderIsAbsent() { + let sessions = [makeSession("m1", groupLeaderId: "deleted")] + let layout = SessionGroups.layout(known: sessions, visible: sessions) + #expect(layout.topLevel.map(\.id) == ["m1"]) + #expect(layout.membersByLeader.isEmpty) + } + + @Test func bringsBackFilteredOutLeaderAsContainerForMatchingMember() { + let leader = makeSession("leader") + let member = makeSession("m1", groupLeaderId: "leader") + let solo = makeSession("solo") + + let layout = SessionGroups.layout(known: [leader, member, solo], visible: [member]) + #expect(layout.topLevel.map(\.id) == ["leader"]) + #expect(layout.membersByLeader["leader"]?.map(\.id) == ["m1"]) + } + + @Test func showsOnlyMembersThatPassedFilter() { + let leader = makeSession("leader") + let m1 = makeSession("m1", groupLeaderId: "leader") + let m2 = makeSession("m2", groupLeaderId: "leader") + + let layout = SessionGroups.layout(known: [leader, m1, m2], visible: [leader, m2]) + #expect(layout.membersByLeader["leader"]?.map(\.id) == ["m2"]) + } + + @Test func leavesGloballyPinnedMemberAtTopLevel() { + let sessions = [ + makeSession("leader"), + makeSession("m1", globalPinned: true, groupLeaderId: "leader"), + ] + let layout = SessionGroups.layout(known: sessions, visible: sessions) + #expect(layout.topLevel.map(\.id) == ["leader", "m1"]) + #expect(layout.membersByLeader.isEmpty) + } + + @Test func doesNotNestUnderASessionThatIsItselfAMember() { + let sessions = [ + makeSession("leader"), + makeSession("m1", groupLeaderId: "leader"), + makeSession("stray", groupLeaderId: "m1"), + ] + let layout = SessionGroups.layout(known: sessions, visible: sessions) + #expect(layout.topLevel.map(\.id) == ["leader", "stray"]) + #expect(layout.membersByLeader["leader"]?.map(\.id) == ["m1"]) + } + + // MARK: - summarizeMembers & sortMembers & search boost + + @Test func summarizesWaitingWorkingAndUnreadMembers() { + let now = 50_000 + let members = [ + makeSession("waiting", active: true, thinking: true, pendingRequestsCount: 1), + makeSession("working", active: true, thinking: true), + makeSession("tools", active: true, derivedToolWork: true), + makeSession("job", active: false, attachedJob: AttachedJob( + key: "j", label: "Import", heartbeatAt: now - 1_000, startedAt: now - 5_000, updatedAt: now - 1_000 + )), + makeSession("unread"), + makeSession("quiet"), + // Requests left on a stopped session cannot be answered. + makeSession("stopped", active: false, pendingRequestsCount: 2), + ] + + let status = SessionGroups.summarizeMembers( + members, + isUnread: { $0.id == "unread" || $0.id == "waiting" }, + nowMs: now + ) + #expect(status == SessionGroupStatus(waiting: 1, working: 3, unread: 2)) + } + + @Test func sortsProjectPinnedMembersFirstThenOrderOrSearchScore() { + let newer = makeSession("newer", active: true, lastUserMessageAt: 300, groupLeaderId: "leader") + let pinned = makeSession("pinned", active: false, lastUserMessageAt: 100, pinned: true, groupLeaderId: "leader") + let older = makeSession("older", active: true, lastUserMessageAt: 200, groupLeaderId: "leader") + + let byOrder = SessionGroups.sortMembers([older, newer, pinned], order: .default) + #expect(byOrder.map(\.id) == ["pinned", "newer", "older"]) + + let index = SessionListSearch.ScoreIndex(scores: ["older": 50, "newer": 10, "pinned": 5]) + let bySearch = SessionGroups.sortMembers([newer, older, pinned], order: .default, searchScores: index) + #expect(bySearch.map(\.id) == ["pinned", "older", "newer"]) + } + + @Test func boostsLeaderSearchScoreToBestMemberScore() { + let leader = makeSession("leader", name: "Release leader") + let weak = makeSession("weak", name: "Other work", groupLeaderId: "leader") + let exact = makeSession("exact", name: "zebra", groupLeaderId: "leader") + let layout = SessionGroups.layout(known: [leader, weak, exact], visible: [weak, exact]) + let base = SessionListSearch.ScoreIndex(scores: ["weak": 10, "exact": 67.5]) + + let boosted = SessionGroups.boostSearchScores(base, layout: layout) + #expect(boosted.scores["leader"] == 67.5) + } + + // MARK: - Persistence stores + + @Test func openStorePersistsPerScopeAndMigratesOnLeaderReopen() throws { + let suite = "session-group-open-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + + let storeA = SessionGroupOpenStore(scope: "hubA:ns1", defaults: defaults) + #expect(!storeA.isOpen("leader-1")) + storeA.setOpen(true, leaderId: "leader-1") + #expect(storeA.isOpen("leader-1")) + + let reloadedA = SessionGroupOpenStore(scope: "hubA:ns1", defaults: defaults) + #expect(reloadedA.isOpen("leader-1")) + let storeB = SessionGroupOpenStore(scope: "hubB:ns1", defaults: defaults) + #expect(!storeB.isOpen("leader-1")) + + reloadedA.move(from: "leader-1", to: "leader-2") + let afterMove = SessionGroupOpenStore(scope: "hubA:ns1", defaults: defaults) + #expect(!afterMove.isOpen("leader-1")) + #expect(afterMove.isOpen("leader-2")) + } + + // MARK: - GroupDissolver + + private actor ArchiveRecorder { + var attempted: [String] = [] + var failIds: Set + init(failIds: Set = []) { self.failIds = failIds } + func archive(_ id: String) throws { + attempted.append(id) + if failIds.contains(id) { + throw APIError(status: 500, code: "cleanup not confirmed") + } + } + func setFailIds(_ next: Set) { failIds = next } + func resetAttempted() { attempted = [] } + } + + @Test func dissolvesMembersBeforeLeaderAndSummarizesImpact() async { + let leader = makeSession("leader", active: true, name: "Release leader") + let memberA = makeSession("member-a", active: true, thinking: true, groupLeaderId: "leader") + let memberB = makeSession( + "member-b", + active: true, + groupLeaderId: "leader", + worktree: WorktreeMetadata(basePath: "/work/other", branch: "docs", name: "docs") + ) + let memberDone = archived(makeSession("member-done", groupLeaderId: "leader")) + let allMembers = [memberA, memberB, memberDone] + + let targets = SessionGroups.dissolveTargets(leader: leader, allMembers: allMembers, unconfirmed: []) + #expect(targets.live.count == 3) + let impact = SessionGroups.summarizeDissolve(targets.live, nowMs: 1_000) + #expect(impact.working == 1) + #expect(impact.worktree == 1) + + let store = SessionGroupDissolveStore(scope: "test", defaults: nil) + let recorder = ArchiveRecorder() + let outcome = await GroupDissolver.dissolve( + leader: leader, + allMembers: allMembers, + store: store, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [leader, self.archived(memberA), self.archived(memberB), memberDone] }, + refreshSessions: {} + ) + + #expect(outcome == .succeeded) + let attempted = await recorder.attempted + #expect(attempted.count == 3) + #expect(attempted.prefix(2).sorted() == ["member-a", "member-b"]) + #expect(attempted.last == "leader") + #expect(store.unconfirmedIds(forLeaderId: "leader").isEmpty) + } + + @Test func keepsLeaderRunningWhenMemberArchiveFails() async { + let leader = makeSession("leader", active: true) + let memberA = makeSession("member-a", active: true, groupLeaderId: "leader") + let memberB = makeSession("member-b", active: true, groupLeaderId: "leader") + let store = SessionGroupDissolveStore(scope: "test", defaults: nil) + let recorder = ArchiveRecorder(failIds: ["member-a"]) + + let outcome = await GroupDissolver.dissolve( + leader: leader, + allMembers: [memberA, memberB], + store: store, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [leader, memberA, memberB] }, + refreshSessions: {} + ) + + #expect(outcome == .membersFailed(failed: 1, total: 2)) + let attempted = await recorder.attempted + #expect(attempted.sorted() == ["member-a", "member-b"]) + #expect(store.unconfirmedIds(forLeaderId: "leader") == ["member-a"]) + } + + @Test func retriesUnconfirmedMemberAfterReloadEvenWhenReadingAsArchived() async throws { + let suite = "session-group-dissolve-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + + let leader = makeSession("leader", active: true) + let memberA = makeSession("member-a", active: true, groupLeaderId: "leader") + let memberB = makeSession("member-b", active: true, groupLeaderId: "leader") + + let firstStore = SessionGroupDissolveStore(scope: "hub:ns", defaults: defaults) + let recorder = ArchiveRecorder(failIds: ["member-a"]) + _ = await GroupDissolver.dissolve( + leader: leader, + allMembers: [memberA, memberB], + store: firstStore, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [leader, memberA, memberB] }, + refreshSessions: {} + ) + + // Simulate app relaunch where both members now read as archived. + let reloadedStore = SessionGroupDissolveStore(scope: "hub:ns", defaults: defaults) + #expect(reloadedStore.unconfirmedIds(forLeaderId: "leader") == ["member-a"]) + await recorder.setFailIds([]) + await recorder.resetAttempted() + + let archivedA = archived(memberA) + let archivedB = archived(memberB) + let outcome = await GroupDissolver.dissolve( + leader: leader, + allMembers: [archivedA, archivedB], + store: reloadedStore, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [leader, archivedA, archivedB] }, + refreshSessions: {} + ) + + #expect(outcome == .succeeded) + #expect(await recorder.attempted == ["member-a", "leader"]) + #expect(reloadedStore.unconfirmedIds(forLeaderId: "leader").isEmpty) + } + + @Test func keepsLeaderRunningWhenMemberJoinedReopenedOrIsStarting() async { + let leader = makeSession("leader", active: true) + let memberA = makeSession("member-a", active: true, groupLeaderId: "leader") + let store = SessionGroupDissolveStore(scope: "test", defaults: nil) + let recorder = ArchiveRecorder() + + // 1. Late-joined active member + let joined = makeSession("member-late", active: true, groupLeaderId: "leader") + let outcomeJoined = await GroupDissolver.dissolve( + leader: leader, + allMembers: [memberA], + store: store, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [leader, self.archived(memberA), joined] }, + refreshSessions: {} + ) + #expect(outcomeJoined == .membersRunning(count: 1)) + #expect(await recorder.attempted == ["member-a"]) + + // 2. Starting member (inactive, no lifecycleState, created within 2 min) + await recorder.resetAttempted() + let starting = makeSession("member-starting", active: false, createdAt: 100_000, groupLeaderId: "leader") + let outcomeStarting = await GroupDissolver.dissolve( + leader: leader, + allMembers: [memberA], + store: store, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [leader, self.archived(memberA), starting] }, + refreshSessions: {}, + nowMs: { 100_000 + 30_000 } + ) + #expect(outcomeStarting == .membersRunning(count: 1)) + #expect(await recorder.attempted == ["member-a"]) + + // 3. Re-check fetch failure + await recorder.resetAttempted() + let outcomeUnchecked = await GroupDissolver.dissolve( + leader: leader, + allMembers: [memberA], + store: store, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { throw URLError(.notConnectedToInternet) }, + refreshSessions: {} + ) + #expect(outcomeUnchecked == .uncheckedMembers) + #expect(await recorder.attempted == ["member-a"]) + } + + @Test func retainsRetryWhenLeaderArchiveFailsEvenOnceWholeGroupReadsAsArchived() async { + let leader = makeSession("leader", active: true) + let memberA = makeSession("member-a", active: true, groupLeaderId: "leader") + let store = SessionGroupDissolveStore(scope: "test", defaults: nil) + let recorder = ArchiveRecorder(failIds: ["leader"]) + + let first = await GroupDissolver.dissolve( + leader: leader, + allMembers: [memberA], + store: store, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [leader, self.archived(memberA)] }, + refreshSessions: {} + ) + #expect(first == .leaderFailed(total: 2)) + #expect(store.unconfirmedIds(forLeaderId: "leader") == ["leader"]) + + // Whole group now reads as archived, yet leader still gets retried. + await recorder.setFailIds([]) + await recorder.resetAttempted() + let second = await GroupDissolver.dissolve( + leader: archived(leader), + allMembers: [archived(memberA)], + store: store, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [self.archived(leader), self.archived(memberA)] }, + refreshSessions: {} + ) + #expect(second == .succeeded) + #expect(await recorder.attempted == ["leader"]) + #expect(store.unconfirmedIds(forLeaderId: "leader").isEmpty) + + // Nothing left to dissolve once confirmed. + let third = await GroupDissolver.dissolve( + leader: archived(leader), + allMembers: [archived(memberA)], + store: store, + archiveSession: { id in try await recorder.archive(id) }, + fetchSessions: { [] }, + refreshSessions: {} + ) + #expect(third == .nothingToDissolve) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalInputHelpersTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalInputHelpersTests.swift new file mode 100644 index 00000000000..a84daeee780 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalInputHelpersTests.swift @@ -0,0 +1,44 @@ +import Foundation +import HapiClient +import Testing + +@Suite("TerminalInputEncoding") +struct TerminalInputHelpersTests { + @Test func appliesCtrlAndAltModifiers() { + #expect(TerminalInputEncoding.applyModifiers("c", state: .init(ctrl: true)) == "\u{03}") + #expect(TerminalInputEncoding.applyModifiers("C", state: .init(ctrl: true)) == "\u{03}") + #expect(TerminalInputEncoding.applyModifiers(" ", state: .init(ctrl: true)) == "\u{00}") + #expect(TerminalInputEncoding.applyModifiers("x", state: .init(alt: true)) == "\u{1b}x") + #expect(TerminalInputEncoding.applyModifiers("c", state: .init(ctrl: true, alt: true)) == "\u{1b}\u{03}") + // Multi-char sequences receive Alt prefix only, never Ctrl mapping. + #expect(TerminalInputEncoding.applyModifiers("\u{1b}[A", state: .init(ctrl: true, alt: true)) == "\u{1b}\u{1b}[A") + } + + @Test func respectsApplicationCursorKeysMode() { + #expect(TerminalSpecialKey.arrowUp.sequence(applicationCursorKeys: false) == "\u{1b}[A") + #expect(TerminalSpecialKey.arrowUp.sequence(applicationCursorKeys: true) == "\u{1b}OA") + #expect(TerminalSpecialKey.home.sequence(applicationCursorKeys: false) == "\u{1b}[H") + #expect(TerminalSpecialKey.home.sequence(applicationCursorKeys: true) == "\u{1b}OH") + #expect(TerminalSpecialKey.shiftTab.sequence() == "\u{1b}[Z") + } + + @Test func wrapsBracketedPasteAndSanitizesEndEscape() { + let plain = TerminalInputEncoding.encodePaste("a\r\nb\nc", bracketedPasteMode: false) + #expect(plain == "a\rb\rc") + + let bracketed = TerminalInputEncoding.encodePaste("echo 1\n\u{1b}[201~rm -rf", bracketedPasteMode: true) + #expect(bracketed == "\u{1b}[200~echo 1\rrm -rf\u{1b}[201~") + + // Removing a nested terminator must not rebuild one from its halves. + let nested = TerminalInputEncoding.encodePaste("\u{1b}[20\u{1b}[201~1~rm -rf ~\n", bracketedPasteMode: true) + let body = nested.dropFirst("\u{1b}[200~".count).dropLast("\u{1b}[201~".count) + #expect(!body.contains("\u{1b}[201~")) + #expect(nested.hasSuffix("rm -rf ~\r\u{1b}[201~")) + } + + @Test func formatsExcerptForChatWithSafeFence() { + #expect(TerminalInputEncoding.formatExcerptForChat(" hello \n") == "```text\nhello\n```") + #expect(TerminalInputEncoding.formatExcerptForChat("```swift\nx\n```") == "~~~~text\n```swift\nx\n```\n~~~~") + #expect(TerminalInputEncoding.formatExcerptForChat(" \n ") == "") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalSocketClientTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalSocketClientTests.swift new file mode 100644 index 00000000000..18f451a2df9 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalSocketClientTests.swift @@ -0,0 +1,195 @@ +import Foundation +import HapiClient +import Testing + +private final class ScriptedWebSocketConnection: TerminalWebSocketConnection, @unchecked Sendable { + private let lock = NSLock() + private var inboundQueue: [Result] + private var waiters: [CheckedContinuation] = [] + private var _sentFrames: [String] = [] + private var isClosed = false + + init(inbound: [Result] = []) { + self.inboundQueue = inbound + } + + var sentFrames: [String] { + lock.withLock { _sentFrames } + } + + func push(_ frame: String) { + let waiter: CheckedContinuation? = lock.withLock { + if !waiters.isEmpty { + return waiters.removeFirst() + } + inboundQueue.append(.success(frame)) + return nil + } + waiter?.resume(returning: frame) + } + + func fail(_ error: Error) { + let waiter: CheckedContinuation? = lock.withLock { + if !waiters.isEmpty { + return waiters.removeFirst() + } + inboundQueue.append(.failure(error)) + return nil + } + waiter?.resume(throwing: error) + } + + func send(text: String) async throws { + lock.withLock { + _sentFrames.append(text) + } + } + + func receive() async throws -> String { + try await withCheckedThrowingContinuation { cont in + let immediate: Result? = lock.withLock { + if !inboundQueue.isEmpty { + return inboundQueue.removeFirst() + } + if isClosed { + return .failure(CancellationError()) + } + waiters.append(cont) + return nil + } + if let immediate { + cont.resume(with: immediate) + } + } + } + + func close() { + let pending: [CheckedContinuation] = lock.withLock { + isClosed = true + let all = waiters + waiters.removeAll() + return all + } + for waiter in pending { + waiter.resume(throwing: CancellationError()) + } + } +} + +private final class ScriptedWebSocketTransport: TerminalWebSocketTransport, @unchecked Sendable { + private let lock = NSLock() + private var connections: [ScriptedWebSocketConnection] + private var _connectedURLs: [URL] = [] + + init(connections: [ScriptedWebSocketConnection]) { + self.connections = connections + } + + var connectedURLs: [URL] { + lock.withLock { _connectedURLs } + } + + func connect(url: URL) async throws -> any TerminalWebSocketConnection { + lock.withLock { + _connectedURLs.append(url) + return connections.isEmpty ? ScriptedWebSocketConnection() : connections.removeFirst() + } + } +} + +private actor RefreshRecorder { + private(set) var calls: [String?] = [] + func record(_ rejectedToken: String?) -> String { + calls.append(rejectedToken) + return rejectedToken == nil ? "jwt-stale" : "jwt-fresh" + } +} + +@Suite("TerminalSocketClient") +struct TerminalSocketClientTests { + @Test func handshakesPongsAndDeliversShellAndAgentEvents() async throws { + let conn = ScriptedWebSocketConnection() + let transport = ScriptedWebSocketTransport(connections: [conn]) + let client = TerminalSocketClient( + configuration: .init( + baseURL: URL(string: "https://hub.example.com")!, + tokenProvider: { _ in "jwt-ok" }, + reconnectInitialDelayMs: 50, + reconnectMaxDelayMs: 100 + ), + transport: transport + ) + + let stream = await client.start() + var iterator = stream.makeAsyncIterator() + + #expect(await iterator.next() == .stateChanged(.connecting)) + + // Queue command before handshake completes — must flush right after namespaceConnected. + await client.createShell(sessionId: "s1", terminalId: "t1", cols: 80, rows: 24) + + conn.push(#"0{"sid":"eio-1","pingInterval":25000,"pingTimeout":20000}"#) + conn.push(#"40/terminal,{"sid":"sio-1"}"#) + #expect(await iterator.next() == .stateChanged(.connected)) + + // Heartbeat ping -> client replies pong "3". + conn.push("2") + conn.push(#"42/terminal,["terminal:ready",{"terminalId":"t1"}]"#) + #expect(await iterator.next() == .shellReady(terminalId: "t1")) + + conn.push(#"42/terminal,["terminal:output",{"terminalId":"t1","data":"$ ls\r\n"}]"#) + #expect(await iterator.next() == .shellOutput(terminalId: "t1", data: "$ ls\r\n")) + + conn.push(#"42/terminal,["agent-terminal:output",{"sessionId":"s1","terminalId":"agent","data":"hi"}]"#) + #expect(await iterator.next() == .agentOutput(sessionId: "s1", data: "hi")) + + conn.push(#"42/terminal,["terminal:exit",{"terminalId":"t1","code":0,"signal":null}]"#) + #expect(await iterator.next() == .shellExit(terminalId: "t1", code: 0, signal: nil)) + + await client.writeShell(terminalId: "t1", data: "pwd\r") + await client.stop() + + let sent = conn.sentFrames + #expect(sent.contains(#"40/terminal,{"token":"jwt-ok"}"#)) + #expect(sent.contains("3")) + #expect(sent.contains(#"42/terminal,["terminal:create",{"cols":80,"rows":24,"sessionId":"s1","terminalId":"t1"}]"#)) + #expect(sent.contains(#"42/terminal,["terminal:write",{"data":"pwd\r","terminalId":"t1"}]"#)) + } + + @Test func refreshesTokenOnceOnAuthConnectError() async throws { + let firstConn = ScriptedWebSocketConnection() + let secondConn = ScriptedWebSocketConnection() + let transport = ScriptedWebSocketTransport(connections: [firstConn, secondConn]) + let recorder = RefreshRecorder() + + let client = TerminalSocketClient( + configuration: .init( + baseURL: URL(string: "https://hub.example.com")!, + tokenProvider: { rejectedToken in + await recorder.record(rejectedToken) + }, + reconnectInitialDelayMs: 50, + reconnectMaxDelayMs: 100 + ), + transport: transport + ) + + let stream = await client.start() + var iterator = stream.makeAsyncIterator() + #expect(await iterator.next() == .stateChanged(.connecting)) + + firstConn.push(#"0{"sid":"e1","pingInterval":25000,"pingTimeout":20000}"#) + firstConn.push(#"44/terminal,{"message":"Invalid token"}"#) + + secondConn.push(#"0{"sid":"e2","pingInterval":25000,"pingTimeout":20000}"#) + secondConn.push(#"40/terminal,{"sid":"s2"}"#) + #expect(await iterator.next() == .stateChanged(.connected)) + + await client.stop() + + // The retry names the rejected JWT so the provider refreshes past it. + #expect(await recorder.calls == [nil, "jwt-stale"]) + #expect(firstConn.sentFrames.contains(#"40/terminal,{"token":"jwt-stale"}"#)) + #expect(secondConn.sentFrames.contains(#"40/terminal,{"token":"jwt-fresh"}"#)) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalSocketCodecTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalSocketCodecTests.swift new file mode 100644 index 00000000000..f02670fd0ed --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Terminal/TerminalSocketCodecTests.swift @@ -0,0 +1,57 @@ +import Foundation +import HapiClient +import Testing + +@Suite("TerminalSocketCodec") +struct TerminalSocketCodecTests { + @Test func buildsWebSocketURLForHTTPAndHTTPSHubs() throws { + let https = try #require(TerminalSocketCodec.webSocketURL(from: URL(string: "https://hub.example.com:8443/ignored")!)) + #expect(https.absoluteString == "wss://hub.example.com:8443/socket.io/?EIO=4&transport=websocket") + + let http = try #require(TerminalSocketCodec.webSocketURL(from: URL(string: "http://127.0.0.1:3006")!)) + #expect(http.absoluteString == "ws://127.0.0.1:3006/socket.io/?EIO=4&transport=websocket") + + #expect(TerminalSocketCodec.webSocketURL(from: URL(string: "ftp://hub.example.com")!) == nil) + } + + @Test func encodesConnectAndNamespaceEvents() throws { + let connect = try TerminalSocketCodec.encodeConnect(token: "jwt-123") + #expect(connect == #"40/terminal,{"token":"jwt-123"}"#) + + struct Create: Encodable { let cols: Int; let rows: Int; let sessionId: String; let terminalId: String } + let frame = try TerminalSocketCodec.encodeEvent( + "terminal:create", + payload: Create(cols: 80, rows: 24, sessionId: "s1", terminalId: "t1") + ) + #expect(frame == #"42/terminal,["terminal:create",{"cols":80,"rows":24,"sessionId":"s1","terminalId":"t1"}]"#) + } + + @Test func decodesEngineIOAndSocketIOFrames() throws { + let open = TerminalSocketCodec.decode(#"0{"sid":"abc","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#) + #expect(open == .engineOpen(.init(sid: "abc", pingIntervalMs: 25_000, pingTimeoutMs: 20_000))) + #expect(TerminalSocketCodec.decode("2") == .enginePing) + #expect(TerminalSocketCodec.decode("3") == .enginePong) + #expect(TerminalSocketCodec.decode("1") == .engineClose) + #expect(TerminalSocketCodec.decode("6") == .engineNoop) + + #expect(TerminalSocketCodec.decode(#"40/terminal,{"sid":"ns-1"}"#) == .namespaceConnected(sid: "ns-1")) + #expect(TerminalSocketCodec.decode("41/terminal,") == .namespaceDisconnected) + #expect(TerminalSocketCodec.decode(#"44/terminal,{"message":"Invalid token"}"#) == .namespaceConnectError(message: "Invalid token")) + + // Other namespaces are ignored cleanly. + #expect(TerminalSocketCodec.decode(#"40/cli,{"sid":"x"}"#) == .ignored) + #expect(TerminalSocketCodec.decode(#"42["root-event",{}]"#) == .ignored) + + // Events on /terminal (with or without ack id). + guard case .event(let name, let payloadData) = TerminalSocketCodec.decode( + #"42/terminal,17["terminal:output",{"terminalId":"t1","data":"hello\r\n"}]"# + ) else { + Issue.record("expected event frame") + return + } + #expect(name == "terminal:output") + let decoded = try JSONSerialization.jsonObject(with: payloadData) as? [String: String] + #expect(decoded?["terminalId"] == "t1") + #expect(decoded?["data"] == "hello\r\n") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Voice/DictationControllerTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Voice/DictationControllerTests.swift index 217d0345f10..0de902435cb 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Voice/DictationControllerTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Voice/DictationControllerTests.swift @@ -41,8 +41,8 @@ private actor FakeDictationApi: DictationTranscribing { providersFailure = message.map { TestError(message: $0) } } - func setTranscribeFailure(_ message: String) { - transcribeFailure = TestError(message: message) + func setTranscribeFailure(_ message: String?) { + transcribeFailure = message.map { TestError(message: $0) } } func transcriptionProviders() async throws -> TranscriptionProvidersResponse { @@ -81,6 +81,8 @@ private final class FakeRecorder: DictationRecorder { var startFailure: TestError? var stopResult: Data? = Data([1, 2, 3]) + var simulatedLevel: Float = 0.65 + private var interruptionHandler: (@MainActor () -> Void)? private(set) var startCalls = 0 private(set) var stopCalls = 0 private(set) var cancelCalls = 0 @@ -100,6 +102,18 @@ private final class FakeRecorder: DictationRecorder { func cancel() { cancelCalls += 1 } + + func currentAudioLevel() -> Float { + simulatedLevel + } + + func setInterruptionHandler(_ handler: (@MainActor () -> Void)?) { + interruptionHandler = handler + } + + func simulateInterruption() { + interruptionHandler?() + } } // MARK: - Harness @@ -348,6 +362,86 @@ struct DictationControllerTests { #expect(await harness.api.transcribeCalls.isEmpty) #expect(harness.events.isEmpty) } + + @Test func stopAndSendEmitsTranscribedAndSendEvent() async throws { + let harness = DictationHarness() + + harness.controller.toggle() + #expect(await eventually { + if case .recording = harness.controller.state { return true } + return false + }) + harness.controller.stopAndSend() + #expect(await eventually { harness.controller.state == .idle && !harness.events.isEmpty }) + + #expect(harness.events == [.transcribedAndSend("hello world")]) + #expect(harness.controller.failedTake == nil) + } + + @Test func failedUploadRetainsAudioForRetryAndClearsOnSuccess() async throws { + let harness = DictationHarness() + await harness.api.setTranscribeFailure("network timeout") + + harness.controller.toggle() + #expect(await eventually { + if case .recording = harness.controller.state { return true } + return false + }) + harness.controller.stopAndSend() + #expect(await eventually { + harness.controller.state == .idle && harness.controller.failedTake != nil + }) + + #expect(harness.controller.failedTake == FailedDictationTake(message: "network timeout", autoSend: true)) + #expect(await harness.api.transcribeCalls.count == 1) + + await harness.api.setTranscribeFailure(nil) + harness.controller.retryFailedTranscription() + #expect(await eventually { + harness.controller.state == .idle && harness.events.count == 2 + }) + + #expect(harness.controller.failedTake == nil) + #expect(await harness.api.transcribeCalls.count == 2) + #expect(await harness.api.transcribeCalls[1].audio == Data([1, 2, 3])) + #expect(harness.events == [.error("network timeout"), .transcribedAndSend("hello world")]) + } + + @Test func discardFailedTranscriptionDropsRetainedAudio() async throws { + let harness = DictationHarness() + await harness.api.setTranscribeFailure("server 500") + + harness.controller.toggle() + #expect(await eventually { + if case .recording = harness.controller.state { return true } + return false + }) + harness.controller.toggle() + #expect(await eventually { + harness.controller.state == .idle && harness.controller.failedTake != nil + }) + + harness.controller.discardFailedTranscription() + #expect(harness.controller.failedTake == nil) + + await harness.api.setTranscribeFailure(nil) + harness.controller.retryFailedTranscription() + #expect(await harness.api.transcribeCalls.count == 1) + } + + @Test func systemInterruptionStopsRecordingAndEmitsError() async throws { + let harness = DictationHarness() + + harness.controller.toggle() + #expect(await eventually { + if case .recording = harness.controller.state { return true } + return false + }) + + harness.recorder.simulateInterruption() + #expect(harness.controller.state == .idle) + #expect(harness.events == [.error("Recording interrupted")]) + } } @Suite("appendTranscript") diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/BindLinkTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/BindLinkTests.swift index 6ed4e896298..6111bafa158 100644 --- a/ios/Packages/HapiKit/Tests/HapiProtocolTests/BindLinkTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/BindLinkTests.swift @@ -146,4 +146,41 @@ struct BindLinkTests { @Test func webFormRequiresAnHTTPHubValue() { #expect(BindLink.parse("https://app.hapi.run/?hub=ftp%3A%2F%2Fdemo.hapi.run&token=abc") == nil) } + + @Test func parsesTheFragmentWebDirectAccessQR() { + // Canonical `${officialWebUrl}/#${new URLSearchParams({hub, token})}` + // form emitted by hub/src/startHub.ts. + let link = BindLink.parse( + "https://app.hapi.run/#hub=https%3A%2F%2Fdemo.hapi.run&token=tok_9f8%3Adefault" + ) + + #expect(link?.hubUrl == "https://demo.hapi.run") + #expect(link?.accessToken == "tok_9f8:default") + } + + @Test func fragmentTakesPrecedenceOverQueryAndSupportsMixedForm() { + let mixed = BindLink.parse( + "https://app.hapi.run/?hub=https%3A%2F%2Fdemo.hapi.run#token=tok_from_fragment" + ) + #expect(mixed == BindLink(hubUrl: "https://demo.hapi.run", accessToken: "tok_from_fragment")) + + let override = BindLink.parse( + "https://app.hapi.run/?hub=https%3A%2F%2Fquery.example.com&token=query_tok#hub=https%3A%2F%2Ffrag.example.com&token=frag_tok" + ) + #expect(override == BindLink(hubUrl: "https://frag.example.com", accessToken: "frag_tok")) + + // Explicit blank fragment value does not fall back to query. + #expect( + BindLink.parse( + "https://app.hapi.run/?hub=https%3A%2F%2Fquery.example.com&token=query_tok#token=" + ) == nil + ) + // Unrelated fragment anchor still falls back to query params. + let anchored = BindLink.parse( + "https://app.hapi.run/?hub=https%3A%2F%2Fdemo.hapi.run&token=tok#section" + ) + #expect(anchored == BindLink(hubUrl: "https://demo.hapi.run", accessToken: "tok")) + // Invalid percent escapes in fragment are rejected. + #expect(BindLink.parse("https://app.hapi.run/#hub=https%3A%2F%2Fdemo.hapi.run&token=%zz") == nil) + } } diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/LocalSessionImportApiTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/LocalSessionImportApiTests.swift new file mode 100644 index 00000000000..70b78da4571 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/LocalSessionImportApiTests.swift @@ -0,0 +1,69 @@ +import Foundation +import HapiProtocol +import Testing + +@Suite("LocalSessionImportApi") +struct LocalSessionImportApiTests { + @Test func decodesListAndGenericImportResponses() throws { + let listJSON = """ + { + "success": true, + "machineId": "m-1", + "sessions": [ + { + "id": "native-1", + "title": "Refactor auth middleware", + "lastUserMessage": "Check token expiry", + "cwd": "/Users/dev/hapi", + "modifiedAt": 1700000000000, + "messageCount": 14, + "hapiSessionId": "s-existing" + } + ] + } + """ + let list = try JSONDecoder().decode(LocalSessionsListResponse.self, from: Data(listJSON.utf8)) + #expect(list.success) + #expect(list.machineId == "m-1") + let item = try #require(list.sessions?.first) + #expect(item.displayTitle == "Refactor auth middleware") + #expect(item.directoryName == "hapi") + #expect(item.hapiSessionId == "s-existing") + + let importJSON = """ + { + "success": true, + "machineId": "m-1", + "results": [ + { + "sessionId": "native-1", + "claudeSessionId": "native-1", + "hapiSessionId": "s-imported-1", + "action": "created", + "appended": 14 + } + ] + } + """ + let imported = try JSONDecoder().decode(LocalSessionImportResponse.self, from: Data(importJSON.utf8)) + #expect(imported.success) + #expect(imported.firstImportedSessionId == "s-imported-1") + #expect(imported.firstErrorMessage == nil) + } + + @Test func decodesCodexSyncSessionResponse() throws { + let codexJSON = """ + { + "success": true, + "message": "Codex session imported into a new Hapi session", + "hapiSessionIds": ["s-codex-99"], + "syncedCount": 1 + } + """ + let decoded = try JSONDecoder().decode(LocalSessionImportResponse.self, from: Data(codexJSON.utf8)) + #expect(decoded.success) + #expect(decoded.firstImportedSessionId == "s-codex-99") + #expect(LocalSessionSource.codex.importPath == "/api/codex/sync-session") + #expect(LocalSessionSource.claude.importPath == "/api/claude/import-sessions") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionExtrasApiTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionExtrasApiTests.swift new file mode 100644 index 00000000000..c8c4e2b7b7e --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionExtrasApiTests.swift @@ -0,0 +1,102 @@ +import Foundation +import HapiProtocol +import Testing + +@Suite("SessionExtrasApi") +struct SessionExtrasApiTests { + @Test func decodesContentSearchAndSkillsResponses() throws { + let searchJSON = """ + { + "matches": [ + { + "messageId": "m-1", + "role": "assistant", + "seq": 42, + "createdAt": 1700000000000, + "snippet": "Fixed the SSE reconnect race", + "truncated": false + } + ], + "total": 1, + "hasPotentiallyIncompleteResults": false + } + """ + let search = try JSONDecoder().decode(SessionContentMatchesResponse.self, from: Data(searchJSON.utf8)) + #expect(search.total == 1) + #expect(search.matches.first?.messageId == "m-1") + #expect(search.matches.first?.role == "assistant") + + let skillsJSON = """ + { + "success": true, + "skills": [ + { "name": "commit", "description": "Create a clean git commit" }, + { "name": "review" } + ] + } + """ + let skills = try JSONDecoder().decode(SkillsResponse.self, from: Data(skillsJSON.utf8)) + #expect(skills.success) + #expect(skills.skills?.count == 2) + #expect(skills.skills?.first?.name == "commit") + } + + @Test func resolvesPrChipDisplayPrecedenceAndStaleness() throws { + let nowMs = 1_700_000_000_000 + let fresh = nowMs - 60_000 + + let merged = ExternalRef( + repo: "tiann/hapi", + number: 123, + url: "https://github.com/tiann/hapi/pull/123", + role: "primary", + openState: "merged", + checks: "pass", + merge: "clean", + statusCheckedAt: fresh + ) + let mergedDisplay = PrChipDisplay.resolve(from: merged, nowMs: nowMs) + #expect(mergedDisplay.tone == .merged) + #expect(mergedDisplay.label == "merged") + #expect(!mergedDisplay.stale) + + let failing = ExternalRef( + repo: "tiann/hapi", + number: 456, + url: "https://github.com/tiann/hapi/pull/456", + role: "primary", + openState: "open", + checks: "fail", + merge: "clean", + statusCheckedAt: fresh + ) + #expect(PrChipDisplay.resolve(from: failing, nowMs: nowMs).tone == .needsWork) + #expect(PrChipDisplay.resolve(from: failing, nowMs: nowMs).label == "checks failed") + + let ready = ExternalRef( + repo: "tiann/hapi", + number: 789, + url: "https://github.com/tiann/hapi/pull/789", + role: "primary", + openState: "open", + checks: "pass", + merge: "clean", + statusCheckedAt: fresh + ) + #expect(PrChipDisplay.resolve(from: ready, nowMs: nowMs).tone == .ok) + #expect(PrChipDisplay.resolve(from: ready, nowMs: nowMs).label == "ready to merge") + + let stale = ExternalRef( + repo: "tiann/hapi", + number: 999, + url: "https://github.com/tiann/hapi/pull/999", + role: "primary", + openState: "open", + checks: "pass", + statusCheckedAt: nowMs - (3 * 60 * 60 * 1_000) + ) + let staleDisplay = PrChipDisplay.resolve(from: stale, nowMs: nowMs) + #expect(staleDisplay.stale) + #expect(staleDisplay.tone == .unknown) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/SummaryPatchingTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/SummaryPatchingTests.swift index df237df05ab..b51aa0a9b6b 100644 --- a/ios/Packages/HapiKit/Tests/HapiProtocolTests/SummaryPatchingTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/SummaryPatchingTests.swift @@ -279,6 +279,88 @@ struct SummaryPatchingTests { #expect(next.metadata?.agentSessionId == "dsh-1") } + @Test func groupLeaderIdProjectsThroughMetadataAndChangesAreRenderRelevant() throws { + let session = makeSession( + metadata: SessionMetadata( + path: "/repo", + host: "host", + flavor: "claude", + groupLeaderId: "leader-1" + ) + ) + let summary = SummaryPatching.toSessionSummary(session) + #expect(summary.metadata?.groupLeaderId == "leader-1") + + let replaced = SummaryPatching.applySessionSummaryPatch( + summary, + SessionPatch(metadata: VersionedValue( + version: 4, + value: SessionMetadata(path: "/repo", host: "host", flavor: "claude", groupLeaderId: "leader-2") + )) + ) + #expect(replaced.metadata?.groupLeaderId == "leader-2") + #expect(!SummaryPatching.sameSessionSummaryMetadata(summary.metadata, replaced.metadata)) + #expect(!SummaryPatching.isRenderIrrelevantPatch(current: summary, next: replaced)) + + let wire = #"{"metadata":{"version":5,"value":{"path":"/repo","host":"host","groupLeaderId":"leader-3"}},"derivedToolWork":true}"# + let patch = try JSONDecoder().decode(SessionPatch.self, from: Data(wire.utf8)) + #expect(patch.metadata?.value?.groupLeaderId == "leader-3") + #expect(patch.derivedToolWork == true) + + let patched = SummaryPatching.applySessionSummaryPatch(replaced, patch) + #expect(patched.metadata?.groupLeaderId == "leader-3") + #expect(patched.derivedToolWork == true) + #expect(!SummaryPatching.isRenderIrrelevantPatch(current: replaced, next: patched)) + + let detailPatched = applySessionDetailPatch(session: session, patch: SessionPatch(derivedToolWork: true)) + #expect(detailPatched?.derivedToolWork == true) + } + + @Test func lifecycleAndWorkHelpersMatchHubAndWebRules() { + #expect(SessionLifecycle.isLive("running")) + #expect(SessionLifecycle.isLive("idle")) + #expect(!SessionLifecycle.isLive("archived")) + #expect(!SessionLifecycle.isLive(nil)) + + let runningInactive = makeSummary( + active: false, + metadata: SessionSummaryMetadata(path: "/repo", lifecycleState: "running") + ) + let idleInactive = makeSummary( + active: false, + metadata: SessionSummaryMetadata(path: "/repo", lifecycleState: "idle") + ) + let archived = makeSummary( + active: false, + metadata: SessionSummaryMetadata(path: "/repo", lifecycleState: "archived") + ) + #expect(runningInactive.isArchivable) + #expect(idleInactive.isArchivable) + #expect(!archived.isArchivable) + + var starting = makeSummary(active: false, metadata: SessionSummaryMetadata(path: "/repo")) + starting.createdAt = 10_000 + #expect(starting.isStarting(nowMs: 10_000 + 60_000)) + #expect(!starting.isStarting(nowMs: 10_000 + SessionSummary.startingMemberWindowMs)) + #expect(!archived.isStarting(nowMs: 10_000)) + + var withJob = makeSummary(active: false, metadata: SessionSummaryMetadata(path: "/repo")) + withJob.attachedJob = AttachedJob( + key: "job", + label: "Import", + heartbeatAt: 1, + latestRunningHeartbeatAt: 100_000, + startedAt: 1, + updatedAt: 100_000 + ) + #expect(withJob.hasInProgressJob(nowMs: 100_000 + 10_000)) + #expect(!withJob.hasInProgressJob(nowMs: 100_000 + AttachedJob.staleAfterMs + 1)) + + var archivedJob = withJob + archivedJob.metadata?.lifecycleState = "archived" + #expect(!archivedJob.hasInProgressJob(nowMs: 100_000)) + } + @Test func staleVersionedPatchesAreRejected() { let current = makeSummary( metadataVersion: 5, diff --git a/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownAdmonitionAndCopyTests.swift b/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownAdmonitionAndCopyTests.swift new file mode 100644 index 00000000000..cfa7d4859f0 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownAdmonitionAndCopyTests.swift @@ -0,0 +1,72 @@ +import Foundation +import HapiUI +import Testing + +@Suite("MarkdownAdmonitionAndCopy") +struct MarkdownAdmonitionAndCopyTests { + @Test func parsesAllFiveGfmAdmonitions() throws { + let samples: [(String, MarkdownAdmonitionKind)] = [ + ("> [!NOTE]\n> Useful context.", .note), + ("> [!TIP]\n> Try keyboard shortcuts.", .tip), + ("> [!IMPORTANT]\n> Keep tokens secret.", .important), + ("> [!WARNING]\n> Breaking change ahead.", .warning), + ("> [!caution]\n> Destructive action.", .caution), + ] + for (source, expected) in samples { + let blocks = MarkdownBlockTree.build(from: source) + guard case .admonition(let kind, let children) = try #require(blocks.first) else { + Issue.record("Expected admonition for \(source)") + return + } + #expect(kind == expected) + #expect(!children.isEmpty) + #expect(MarkdownPlainText.text(of: blocks).hasPrefix("\(expected.title): ")) + } + } + + @Test func leavesRegularBlockquotesUnchanged() throws { + let blocks = MarkdownBlockTree.build(from: "> Just a normal quote.") + guard case .blockquote(let children) = try #require(blocks.first) else { + Issue.record("Expected plain blockquote") + return + } + #expect(children.count == 1) + } + + @Test func extractsCleanMarkdownAndPlainTextFromSelections() { + let source = """ + ## Summary + + Check **bold**, *italic*, `code`, and [Docs](https://example.com). + + - First item + - Second item + """ + let blocks = MarkdownBlockTree.build(from: source) + let annotated = MarkdownSelectionExtractor.buildMetadataAttributedString(from: blocks) + let fullRange = NSRange(location: 0, length: annotated.length) + + // Plain text must never contain synthetic "•\t" bullet tabs. + let plain = MarkdownSelectionExtractor.extractPlainText(from: annotated, range: fullRange) + #expect(!plain.contains("•\t")) + #expect(plain.contains("First item")) + #expect(plain.contains("Second item")) + + let extracted = MarkdownSelectionExtractor.extractMarkdown(from: annotated, range: fullRange) + #expect(extracted.contains("## Summary")) + #expect(extracted.contains("**bold**")) + #expect(extracted.contains("*italic*")) + #expect(extracted.contains("`code`")) + #expect(extracted.contains("[Docs](https://example.com)")) + #expect(extracted.contains("- First item\n- Second item")) + } + + @Test func extractsPartialMidParagraphSelectionWithoutHeadingPrefix() { + let blocks = MarkdownBlockTree.build(from: "# Welcome to HAPI") + let annotated = MarkdownSelectionExtractor.buildMetadataAttributedString(from: blocks) + let full = annotated.string as NSString + let subRange = full.range(of: "HAPI") + let extracted = MarkdownSelectionExtractor.extractMarkdown(from: annotated, range: subRange) + #expect(extracted == "HAPI") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownRenderCacheTests.swift b/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownRenderCacheTests.swift index 46d33b9f43d..cb7b340638a 100644 --- a/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownRenderCacheTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownRenderCacheTests.swift @@ -1,3 +1,4 @@ +import Foundation import HapiUI import Testing @@ -21,4 +22,78 @@ struct MarkdownRenderCacheTests { #expect(cache.cached("one") == nil) #expect(cache.cached("second") != nil) } + + @Test func streamingUpdatesDoNotPolluteSharedLRUCacheAndMatchFullParse() async { + let cache = MarkdownRenderCache(maxCost: 8 * 1024) + let history = "Settled history message that must stay cached." + await cache.prepare([history]) + #expect(cache.settledEntryCount == 1) + + // Simulate a long streaming reply growing across multiple paragraphs and a code fence. + let para1 = String(repeating: "Alpha beta gamma delta. ", count: 60) + let codeBlock = "```swift\nlet value = 42\nprint(value)\n```" + let para2 = "Final summary paragraph with **bold** and `inline.swift`." + + let steps = [ + para1, + para1 + "\n\n```swift\nlet value =", + para1 + "\n\n" + codeBlock, + para1 + "\n\n" + codeBlock + "\n\n" + para2, + ] + for (idx, step) in steps.enumerated() { + await cache.prepare(settled: [], streaming: [.init(id: "msg-1", text: step)]) + #expect(cache.cached(step) == MarkdownBlockTree.build(from: step)) + // Intermediate prefixes never enter the shared LRU or evict settled history. + #expect(cache.settledEntryCount == 1) + #expect(cache.cached(history) != nil) + if idx == 1 { + #expect(cache.hasOpenCodeFence(for: step)) + } else { + #expect(!cache.hasOpenCodeFence(for: step)) + } + } + + // Settling promotes the final text once and drops the streaming slot. + let finalText = steps.last! + await cache.prepare(settled: [finalText], streaming: []) + #expect(cache.settledEntryCount == 2) + #expect(cache.cached(finalText) == MarkdownBlockTree.build(from: finalText)) + #expect(!cache.hasOpenCodeFence(for: finalText)) + } + + @Test func splitterBailsOutOnReferenceDefinitionsAndLooseLists() { + let refDoc = String(repeating: "Paragraph with [ref]. ", count: 60) + "\n\n[ref]: https://example.com" + #expect(!StreamingMarkdownSplitter.canSplitIncrementally(refDoc)) + #expect(StreamingMarkdownSplitter.safeSealOffset(in: refDoc) == nil) + + let htmlDoc = String(repeating: "Intro text. ", count: 100) + "\n\n
\nhello\n
" + #expect(!StreamingMarkdownSplitter.canSplitIncrementally(htmlDoc)) + #expect(StreamingMarkdownSplitter.safeSealOffset(in: htmlDoc) == nil) + + let looseList = "- " + String(repeating: "item one ", count: 150) + "\n\n- item two" + #expect(StreamingMarkdownSplitter.safeSealOffset(in: looseList) == nil) + + #expect(StreamingMarkdownSplitter.hasUnclosedCodeFence("```python\nx = 1")) + #expect(!StreamingMarkdownSplitter.hasUnclosedCodeFence("```python\nx = 1\n```")) + #expect(StreamingMarkdownSplitter.hasUnclosedCodeFence("~~~~\n```nested\n```")) + #expect(!StreamingMarkdownSplitter.hasUnclosedCodeFence("~~~~\n```nested\n~~~~")) + } + + @Test func markdownTableModelSerializesToMarkdownAndTSV() { + let table = MarkdownTableModel( + columnAlignments: [.left, .center, .right], + header: [AttributedString("Name"), AttributedString("Role"), AttributedString("Score")], + rows: [ + [AttributedString("Alice"), AttributedString("Lead | iOS"), AttributedString("98")], + [AttributedString("Bob"), AttributedString("Backend\nHub"), AttributedString("95")], + ] + ) + #expect(table.markdownText() == """ + | Name | Role | Score | + | :--- | :---: | ---: | + | Alice | Lead \\| iOS | 98 | + | Bob | Backend
Hub | 95 | + """) + #expect(table.tsvText() == "Name\tRole\tScore\nAlice\tLead | iOS\t98\nBob\tBackend Hub\t95") + } } diff --git a/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownSegmentTests.swift b/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownSegmentTests.swift new file mode 100644 index 00000000000..7316db43d6d --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiUITests/MarkdownSegmentTests.swift @@ -0,0 +1,34 @@ +import Foundation +@testable import HapiUI +import Testing + +/// Prose runs share one selectable view; blockquote copy text. +@Suite("MarkdownSegment") +struct MarkdownSegmentTests { + @Test func mergesConsecutiveProseAcrossParagraphsHeadingsAndLists() { + let blocks = MarkdownBlockTree.build(from: "# Title\n\nfirst\n\nsecond\n\n- a\n- b\n\n```swift\nlet x = 1\n```\n\nafter") + let segments = MarkdownSegment.segments(of: blocks) + #expect(segments.count == 3) + guard case .text(let prose) = segments[0] else { Issue.record("expected prose run"); return } + #expect(prose.count == 4) + guard case .block(.codeBlock) = segments[1] else { Issue.record("expected code block"); return } + guard case .text(let tail) = segments[2] else { Issue.record("expected trailing prose"); return } + #expect(tail.count == 1) + } + + @Test func keepsBlockquotesAndListsWithCodeAsTheirOwnBlocks() { + let blocks = MarkdownBlockTree.build(from: "intro\n\n> quoted\n\n- item\n\n ```\n code\n ```\n") + let segments = MarkdownSegment.segments(of: blocks) + #expect(segments.count == 3) + guard case .block(.blockquote) = segments[1] else { Issue.record("expected blockquote"); return } + guard case .block(.list) = segments[2] else { Issue.record("expected standalone list"); return } + } + + @Test func blockquotePlainTextKeepsParagraphsAndListMarkers() throws { + let blocks = MarkdownBlockTree.build(from: "> line **one**\n>\n> - a\n> - b\n>\n> 2. two") + guard case .blockquote(let children) = try #require(blocks.first) else { + Issue.record("expected blockquote"); return + } + #expect(MarkdownPlainText.text(of: children) == "line one\n\n• a\n• b\n\n2. two") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiUITests/SessionPathLinkTests.swift b/ios/Packages/HapiKit/Tests/HapiUITests/SessionPathLinkTests.swift new file mode 100644 index 00000000000..984a0cb1c11 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiUITests/SessionPathLinkTests.swift @@ -0,0 +1,65 @@ +import Foundation +import HapiUI +import Testing + +/// Session citation links (`/sessions/` explicit + bare autolinks) and +/// `hapi-session://` URL round-trip tests. +@Suite("SessionPathLink") +struct SessionPathLinkTests { + private func paragraphText(_ node: MarkdownBlockNode) -> AttributedString? { + if case .paragraph(let text) = node { return text } + return nil + } + + private func runs(_ attributed: AttributedString) -> [(text: String, link: URL?)] { + attributed.runs.map { (String(attributed.characters[$0.range]), $0.link) } + } + + @Test func urlRoundTripsSessionId() throws { + let link = SessionPathLink(sessionId: "abc-123-def") + let url = try #require(link.url) + #expect(url.scheme == "hapi-session") + #expect(SessionPathLink(url: url) == link) + + let https = try #require(URL(string: "https://example.com/?id=abc")) + #expect(SessionPathLink(url: https) == nil) + } + + @Test func explicitSessionMarkdownLinkRewritesToHapiSession() throws { + let blocks = MarkdownBlockTree.build(from: "Check [Fix login](/sessions/member-123) for details.") + let text = try #require(paragraphText(blocks[0])) + let linked = runs(text).filter { $0.link != nil } + #expect(linked.count == 1) + #expect(linked[0].text == "Fix login") + #expect(SessionPathLink(url: try #require(linked[0].link)) == SessionPathLink(sessionId: "member-123")) + } + + @Test func bareSessionPathAutolinksWithoutStealingSourceFiles() throws { + let blocks = MarkdownBlockTree.build( + from: "See (/sessions/abc-def) and web/src/routes/sessions/chat.tsx for context." + ) + let text = try #require(paragraphText(blocks[0])) + let linked = runs(text).compactMap { run -> (String, URL)? in + guard let link = run.link else { return nil } + return (run.text, link) + } + #expect(linked.count == 2) + #expect(linked[0].0 == "/sessions/abc-def") + #expect(SessionPathLink(url: linked[0].1) == SessionPathLink(sessionId: "abc-def")) + #expect(linked[1].0 == "web/src/routes/sessions/chat.tsx") + #expect(FilePathLink(url: linked[1].1) == FilePathLink(path: "web/src/routes/sessions/chat.tsx", line: nil)) + } + + @Test func blocksSpoofedInternalSchemesInMarkdown() throws { + let blocks = MarkdownBlockTree.build(from: "[spoof](hapi-session://?id=victim) and hapi-session://?id=raw") + let text = try #require(paragraphText(blocks[0])) + #expect(runs(text).allSatisfy { $0.link == nil }) + } + + @Test func rejectsNonSessionPaths() { + #expect(MarkdownTransforms.sessionLinkTarget(forExplicitHref: "/settings") == nil) + #expect(MarkdownTransforms.sessionLinkTarget(forExplicitHref: "https://hapi.run/sessions/abc") == nil) + #expect(MarkdownTransforms.sessionLinkTarget(forExplicitHref: "routes/sessions/chat.tsx") == nil) + #expect(MarkdownTransforms.sessionLinkTarget(forExplicitHref: "/app/sessions/sess-1/") == SessionPathLink(sessionId: "sess-1")) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiUITests/TerminalEmulatorTests.swift b/ios/Packages/HapiKit/Tests/HapiUITests/TerminalEmulatorTests.swift new file mode 100644 index 00000000000..f9c0b576d49 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiUITests/TerminalEmulatorTests.swift @@ -0,0 +1,165 @@ +import Foundation +import HapiUI +import Testing + +@Suite("TerminalEmulator") +struct TerminalEmulatorTests { + @Test func printsTextHandlesCRLFAndScrollback() { + let emu = TerminalEmulator(cols: 10, rows: 3, maxScrollback: 10) + emu.feed("line1\r\nline2\r\nline3\r\nline4") + + #expect(emu.availableScrollbackCount == 1) + #expect(emu.row(atAbsoluteLine: 0)?.plainText() == "line1") + #expect(emu.grid[0].plainText() == "line2") + #expect(emu.grid[1].plainText() == "line3") + #expect(emu.grid[2].plainText() == "line4") + #expect(emu.cursorRow == 2) + #expect(emu.cursorCol == 5) + } + + @Test func clampsHugeCSIParametersFromUntrustedOutput() { + let emu = TerminalEmulator(cols: 10, rows: 3) + // Int.max and beyond-Int digit runs must not overflow cursor math. + emu.feed("a\u{1b}[9223372036854775807C") + #expect(emu.cursorRow == 0) + #expect(emu.cursorCol == 9) + emu.feed("\u{1b}[H\u{1b}[99999999999999999999999B") + #expect(emu.cursorRow == 2) + emu.feed("\u{1b}[1;1H\u{1b}[9223372036854775807E\u{1b}[9223372036854775807X") + #expect(emu.cursorRow == 2) + #expect(emu.cursorCol == 0) + // Tab counts beyond the width stop at the edge instead of looping. + emu.feed("\u{1b}[1;1H\u{1b}[999999999999I") + #expect(emu.cursorCol == 9) + emu.feed("\u{1b}[999999999999Z") + #expect(emu.cursorCol == 0) + } + + @Test func decodesSplitUTF8AndWideCJKAndEmoji() { + let emu = TerminalEmulator(cols: 6, rows: 3) + // "中文" split mid-UTF-8 byte sequence across chunks. + let utf8 = Array("中".utf8) + emu.feed([utf8[0]]) + emu.feed([utf8[1], utf8[2]]) + emu.feed("文A🚀") + + // Col 0-1: 中, Col 2-3: 文, Col 4: A, Col 5: blank (🚀 width 2 wraps to row 1!) + #expect(emu.grid[0].cells[0].grapheme == "中") + #expect(emu.grid[0].cells[0].width == 2) + #expect(emu.grid[0].cells[1].width == 0) + #expect(emu.grid[0].cells[2].grapheme == "文") + #expect(emu.grid[0].cells[4].grapheme == "A") + #expect(emu.grid[0].wrapped == true) + #expect(emu.grid[1].cells[0].grapheme == "🚀") + #expect(emu.grid[1].cells[0].width == 2) + #expect(emu.grid[1].cells[1].width == 0) + } + + @Test func parsesSGRColorsInStandard256AndTruecolorColonFormats() { + let emu = TerminalEmulator(cols: 20, rows: 2) + emu.feed("\u{1b}[1;3;4;38;5;196;48;2;10;20;30mA") + emu.feed("\u{1b}[0;38:2::200:100:50;4:3mB") + emu.feed("\u{1b}[38:5:42mC") + + let cellA = emu.grid[0].cells[0] + #expect(cellA.grapheme == "A") + #expect(cellA.style.contains([.bold, .italic, .underline])) + #expect(cellA.fg == .ansi(196)) + #expect(cellA.bg == .rgb(10, 20, 30)) + + let cellB = emu.grid[0].cells[1] + #expect(cellB.grapheme == "B") + #expect(cellB.style == [.underline]) + #expect(cellB.fg == .rgb(200, 100, 50)) + #expect(cellB.bg == .defaultBackground) + + let cellC = emu.grid[0].cells[2] + #expect(cellC.fg == .ansi(42)) + } + + @Test func handlesAlternateScreenSaveRestoreAndScrollRegions() { + let emu = TerminalEmulator(cols: 12, rows: 4) + emu.feed("primary-0\r\nprimary-1") + #expect(!emu.isUsingAlternateScreen) + + // Enter alt screen (1049h), set scroll region rows 2..3, scroll inside it. + emu.feed("\u{1b}[?1049h\u{1b}[1;1Hheader\u{1b}[4;1Hfooter\u{1b}[2;3r\u{1b}[2;1Ha\r\nb\r\nc") + #expect(emu.isUsingAlternateScreen) + #expect(emu.grid[0].plainText() == "header") + #expect(emu.grid[1].plainText() == "b") + #expect(emu.grid[2].plainText() == "c") + #expect(emu.grid[3].plainText() == "footer") + + // Full-region scroll-up must not crash when count >= region height. + emu.feed("\u{1b}[10S\u{1b}[10T") + #expect(emu.grid[0].plainText() == "header") + #expect(emu.grid[3].plainText() == "footer") + + // Leave alt screen (1049l) restores primary grid and cursor. + emu.feed("\u{1b}[?1049l") + #expect(!emu.isUsingAlternateScreen) + #expect(emu.grid[0].plainText() == "primary-0") + #expect(emu.grid[1].plainText() == "primary-1") + } + + @Test func answersCursorPositionDAAndOSCColorQueries() { + let emu = TerminalEmulator(cols: 40, rows: 10) + emu.palette = .forTheme(.dark) + var replies: [String] = [] + emu.onReply = { replies.append($0) } + + emu.feed("\u{1b}[3;7H\u{1b}[6n\u{1b}[c\u{1b}]11;?\u{07}") + + #expect(replies.count == 3) + #expect(replies[0] == "\u{1b}[3;7R") + #expect(replies[1] == "\u{1b}[?62;22c") + #expect(replies[2] == "\u{1b}]11;\(emu.palette.background.oscRGBString)\u{1b}\\") + } + + @Test func batchesGenerationDuringSynchronizedOutputAndHandlesDECSpecialGraphics() { + let emu = TerminalEmulator(cols: 20, rows: 4) + let before = emu.generation + + emu.feed("\u{1b}[?2026h") + #expect(emu.synchronizedOutputActive) + let midGen = emu.generation + emu.feed("\u{1b}(0lqqk\u{1b}(B") + #expect(emu.generation == midGen) // Held during sync block + + emu.feed("\u{1b}[?2026l") + #expect(!emu.synchronizedOutputActive) + #expect(emu.generation > before) + #expect(emu.grid[0].plainText() == "┌──┐") + } + + @Test func extractsSelectionJoiningSoftWrappedLines() { + let emu = TerminalEmulator(cols: 5, rows: 4) + // "abcdefgh" wraps across row 0 ("abcde") + row 1 ("fgh"); row 2 is separate. + emu.feed("abcdefgh\r\nxyz") + + let selection = TerminalSelection( + anchor: TerminalGridPosition(line: 0, col: 0), + focus: TerminalGridPosition(line: 2, col: 2) + ) + #expect(emu.extractText(for: selection) == "abcdefgh\nxyz") + } + + @Test func computesWholePixelGridMetricsAndRecognizesVectorBoxGlyphs() { + let metrics = TerminalGridMetrics(fontSize: 13, scale: 3.0) + #expect(metrics.cellWidth > 0) + #expect(metrics.cellHeight > 0) + #expect((metrics.cellWidth * 3.0).rounded() == metrics.cellWidth * 3.0) + #expect((metrics.cellHeight * 3.0).rounded() == metrics.cellHeight * 3.0) + + let (cols, rows) = metrics.gridSize(for: CGSize(width: 390, height: 600)) + #expect(cols >= 35 && cols <= 70) + #expect(rows >= 20 && rows <= 50) + + #expect(TerminalVectorGlyphs.canDraw("─")) + #expect(TerminalVectorGlyphs.canDraw("╭")) + #expect(TerminalVectorGlyphs.canDraw("█")) + #expect(TerminalVectorGlyphs.canDraw("▓")) + #expect(!TerminalVectorGlyphs.canDraw("A")) + #expect(!TerminalVectorGlyphs.canDraw("中")) + } +} diff --git a/ios/README.md b/ios/README.md index 74d8540747b..a181cf79c20 100644 --- a/ios/README.md +++ b/ios/README.md @@ -10,8 +10,8 @@ This README covers development builds. ## Current capabilities The app provides sessions/chat, approvals and questions, new sessions, -attachments, scheduled sends, `/` command suggestions, `@` session/file references, -files/Git, Scratchlist, standard dictation, usage/storage, +attachments, scheduled sends, `/` command suggestions, skills picker, `@` session/file references, +files/Git, native CoreText remote terminal (interactive shell + live Agent PTY for active sessions), Scratchlist, standard dictation, usage/storage, settings and encrypted APNs notifications. It pairs with multiple hubs and keeps one active. The chat's … menu also forks the conversation, rewinds or forks at a loaded user message with a native history point (a separate sheet, @@ -19,7 +19,18 @@ so transcript rows are untouched), and exports the session as JSON through the Files save panel (Markdown export stays web-only). Session lists support machine filtering, pinning, rename and archive (active) or reopen/delete (inactive), from the row's context menu or the chat's … menu; sending to an inactive session or reopening it can resume it and -migrate the draft/navigation when the returned session ID changes. +migrate the draft/navigation when the returned session ID changes. Spawned peer +sessions (`metadata.groupLeaderId`) nest under their leader, folded by default +(persisted per hub and namespace). The leader's detail line carries the member +summary (`2 members · 1 waiting · 1 working ⌄`; only waiting is coloured, member +unread rolls up onto the folded leader's title, and an open group shows just the +count); tapping it unfolds the members as compact rows indented under the leader, +with one separator closing the group. Under a project header the row drops the +repeated project name when a worktree or the member summary fills the line. Search/filter +auto-expands groups and ranks leaders by their best member; **Dissolve group** in +the leader's context menu archives members before the leader, with +unconfirmed-archive retry persistence. In-chat `/sessions/` +citations also open the referenced session directly. Agent-displayed media (`display_image`, `display_video`, `display_media`) uses MIME-based cards: images load automatically, while video, audio and other files @@ -289,10 +300,10 @@ background/lock-screen delivery and actions on a signed physical device. |---|---| | `Hapi.xcodeproj/` | App, notification extension and app-hosted tests. App sources use Xcode synchronized folders. | | `Hapi/Models/` | `AppModel` pairing/navigation, active `HubSession`, per-chat `ChatSession`, and `PushCoordinator`. | -| `Hapi/Features/` | SwiftUI screens and app models for pairing, sessions, chat, new sessions, files, Scratchlist and settings; UIKit transcript hosting. | +| `Hapi/Features/` | SwiftUI screens and app models for pairing, sessions, chat, new sessions, files, native terminal, Scratchlist and settings; UIKit transcript hosting. | | `Packages/HapiKit/Sources/HapiProtocol/` | Foundation wire models, catalogs, pairing parser, versioned patches, chat reduction, message-window logic and Git parsers. | -| `Packages/HapiKit/Sources/HapiClient/` | Auth/REST/SSE, stores and disk snapshots, message windows, chat interaction, attachments, dictation, push and testable feature logic. | -| `Packages/HapiKit/Sources/HapiUI/` | Reusable Markdown, syntax highlighting, diff rendering, theme and typography. | +| `Packages/HapiKit/Sources/HapiClient/` | Auth/REST/SSE, direct-WebSocket `/terminal` Socket.IO client, stores and disk snapshots, message windows, chat interaction, attachments, dictation, push and testable feature logic. | +| `Packages/HapiKit/Sources/HapiUI/` | Reusable Markdown, syntax highlighting, diff rendering, CoreText VT100/xterm terminal renderer, theme and typography. | | `HapiNotificationService/` | SDK-only extension that decrypts APNs content using the shared Keychain key. | | `Packages/HapiKit/Tests/`, `HapiTests/` | Package and app-hosted verification. | @@ -502,7 +513,7 @@ Mac-specific behavior, compiled with `targetEnvironment(macCatalyst)`: Shared with iPad: the menu bar / hardware-keyboard commands in `AppCommands.swift` — New Session ⌘N, Settings ⌘, Toggle Sidebar ⌃⌘S, and a -Session menu (Session Settings ⌘I, Session Files ⌘⇧O, Rename, Export, Stop ⌘., +Session menu (Session Settings ⌘I, Session Files ⌘⇧O, Terminal ⌘⇧T, Rename, Export, Stop ⌘., Previous/Next Session ⌥⌘↑/↓). Dropping files on the composer or pasting an image-only clipboard or copied files adds attachments (`ItemProviderAttachmentLoader` copies the provider file before preparing it). diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index f93a6f30012..2c824aa6e8f 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -23,6 +23,7 @@ import type { Machine, Session } from './schemas' +import { BLOCKED_ACK_REASON_MAX_CHARS } from './notifyAttention' import type { SessionSummary } from './sessionSummary' export const CreateOrLoadMachineRequestSchema = z.object({ @@ -151,7 +152,8 @@ export type AuthResponse = { } } -export type SessionsResponse = { sessions: SessionSummary[]; serverTime?: number } +/** `hubGeneration`: see `SessionCache.hubGeneration` (#1717 cold-review round 29). */ +export type SessionsResponse = { sessions: SessionSummary[]; serverTime?: number; hubGeneration?: string } export type ScratchlistSessionIdsResponse = { sessionIds: string[] } export type SessionContentMatch = { messageId: string @@ -546,6 +548,21 @@ export const SetSessionPinnedRequestSchema = z.object({ }) export type SetSessionPinnedRequest = z.infer + +/** Manual unblock (#1717). Reason is required — see `SessionBlockedAck`. */ +export const SetSessionBlockedAckRequestSchema = z.object({ + reason: z.string().trim().min(1).max(BLOCKED_ACK_REASON_MAX_CHARS), + /** Timestamp of the blocker the operator was looking at when they opened + * the dialog. The watermark is set to this rather than to the hub's + * receive time, so a blocker that arrived while the dialog was open is + * not silently covered by a reason written for an earlier one. + * Optional: an older client omits it and keeps the previous behaviour. */ + observedAt: z.number().int().nonnegative().safe().optional(), + /** Identity of that blocker, so the acknowledgement covers exactly it + * rather than everything older than its timestamp. */ + observedKey: z.string().max(256).optional() +}) +export type SetSessionBlockedAckRequest = z.infer export type SessionPinMode = SetSessionPinnedRequest['mode'] /** diff --git a/shared/src/buildInfo.ts b/shared/src/buildInfo.ts index ca80872a444..f3ea92389a2 100644 --- a/shared/src/buildInfo.ts +++ b/shared/src/buildInfo.ts @@ -1 +1 @@ -export const APP_VERSION = '0.37.0' +export const APP_VERSION = '0.37.1' diff --git a/shared/src/index.ts b/shared/src/index.ts index 672f0f8f334..54dcf3d7783 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -9,6 +9,7 @@ export * from './externalRefs' export * from './projectRegistry' export * from './prChipDisplay' export * from './messages' +export * from './notifyAttention' export * from './buildInfo' export * from './conversationHistory' export * from './effort' diff --git a/shared/src/notifyAttention.ts b/shared/src/notifyAttention.ts new file mode 100644 index 00000000000..88222825e29 --- /dev/null +++ b/shared/src/notifyAttention.ts @@ -0,0 +1,183 @@ +/** + * Blocked-agent attention derived from the agent's `AGENT_NOTIFY_SUMMARY` + * footer (see `extractNotifySummary` in `./messages`). + * + * This is a distinct axis from `SessionAttention` (permission / input / + * background / unread): those describe a session that is *live and waiting on + * a click*, this describes a turn that *ended* with the agent declaring it + * cannot proceed. Both can be true at once, so they never contend — the web + * list renders them in different visual channels. + */ + +/** Note (`action`, else `summary`) carried onto the session list for tooltips. */ +export const NOTIFY_NOTE_MAX_CHARS = 160 + +/** + * Notify statuses that mean "a human is needed before this can continue". + * + * Deliberately wider than the documented contract vocabulary, because agents + * emit synonyms in practice. Measured on a 683-session fleet: `pending` (92) + * and `completed` (2) both occur and neither is in the contract. Treating an + * unrecognised status as blocking would cry wolf, and treating `pending` as + * unrecognised would miss the single most common waiting signal there is. + */ +export const BLOCKING_NOTIFY_STATUSES: readonly string[] = [ + 'blocked', + // Self-reported stuck; the hub's work_ad mapping already folds this to blocked. + 'stalled', + // "There is a question that needs answering" / "I need a call from you". + 'needs_decision', + 'needs_review', + 'awaiting_review', + // Errors are blockers too — nothing proceeds until someone looks. + 'failed', + 'error', + // Not in the contract, but the most-emitted waiting status in the wild. + 'pending', + 'waiting', + 'needs_input', + 'blocked_on_operator' +] + +/** + * Statuses that explicitly mean "no human needed". Kept separate from + * "unrecognised" so a new synonym for done cannot start alarming, and so + * `completed` (non-contract, observed) clears a prior blocked report. + */ +export const NON_BLOCKING_NOTIFY_STATUSES: readonly string[] = [ + 'done', + 'completed', + 'complete', + 'success', + 'ok', + 'in_progress', + 'running', + 'started', + 'stale' +] + +/** Back-compat alias: the original narrow set. Prefer BLOCKING_NOTIFY_STATUSES. */ +export const BLOCKED_NOTIFY_STATUSES: readonly string[] = ['blocked', 'stalled'] + +/** + * How a blocking status should be presented. Collapses synonyms onto the small + * set of chips the session list actually draws. + */ +export type NotifyBlockReason = 'blocked' | 'stalled' | 'needs_decision' | 'needs_review' | 'failed' + +const NOTIFY_BLOCK_REASON: Record = { + blocked: 'blocked', + pending: 'blocked', + waiting: 'blocked', + needs_input: 'blocked', + blocked_on_operator: 'blocked', + stalled: 'stalled', + needs_decision: 'needs_decision', + needs_review: 'needs_review', + awaiting_review: 'needs_review', + failed: 'failed', + error: 'failed' +} + +export function getNotifyBlockReason(status: string | null | undefined): NotifyBlockReason | null { + const normalized = normalizeNotifyStatus(status) + if (normalized === '' || !BLOCKING_NOTIFY_STATUSES.includes(normalized)) return null + return NOTIFY_BLOCK_REASON[normalized] ?? 'blocked' +} + +export function isNonBlockingNotifyStatus(status: string | null | undefined): boolean { + return NON_BLOCKING_NOTIFY_STATUSES.includes(normalizeNotifyStatus(status)) +} + +/** + * How long blocked chrome stays loud. Past this a row demotes to a muted + * variant (still counted, still filterable) so an abandoned session does not + * hold a permanent alarm. Matches the work-graph work_ad default TTL. + */ +export const BLOCKED_NOTIFY_STALE_MS = 24 * 60 * 60 * 1000 + +/** Max length of an operator's manual-unblock rationale. */ +export const BLOCKED_ACK_REASON_MAX_CHARS = 500 + +/** + * Operator's manual "this is not blocked" acknowledgement (#1717). + * + * A watermark rather than a flag, so it survives the next blocker: anything + * reported at or before `at` is dismissed, anything newer blocks again. That + * makes one uniform mechanism cover both blocker sources — a stale notify + * footer and an abandoned prompt — without the UI needing to know which it is. + * + * `reason` is mandatory by design. Replying to an agent carries the rationale + * implicitly (it is right there in the transcript); dismissing silently would + * leave the event log with a state change and no "why". + */ +export type SessionBlockedAck = { + at: number + reason: string + /** + * Identity of the blocker the operator actually dismissed. + * + * A bare timestamp watermark cannot tell two blockers apart, so it + * suppressed everything older than itself — including a blocker belonging + * to the other session in a merge, or one that arrived while the dialog + * was open. `notify:` for a self-reported footer, `request:` for a + * prompt. Absent on rows written before this existed, which fall back to + * the old watermark behaviour. + * + * A SET, not one value: a session can hold several prompts at once, and + * dismissing the newer one then the older one must leave both dismissed. + * With a single slot the second dismissal overwrote the first — and, + * because the write was timestamp-monotonic, dismissing the older prompt + * failed outright. + */ + keys?: string[] | null +} + +/** Stable identity for a self-reported footer. */ +export function notifyBlockerKey(at: number): string { + return `notify:${at}` +} + +/** Stable identity for a prompt the agent is parked on. */ +export function requestBlockerKey(requestId: string): string { + return `request:${requestId}` +} + +/** Last `AGENT_NOTIFY_SUMMARY` footer seen for a session. */ +export type SessionNotifySignal = { + /** Raw self-reported status, lowercased. Kept verbatim so new vocabulary + * survives a hub older than the agent emitting it. */ + status: string + /** Epoch ms of the message carrying the footer. */ + at: number + /** Short operator-facing hint; only stored for blocked statuses. */ + note: string | null +} + +export function normalizeNotifyStatus(status: string | null | undefined): string { + return typeof status === 'string' ? status.trim().toLowerCase() : '' +} + +export function isBlockedNotifyStatus(status: string | null | undefined): boolean { + return getNotifyBlockReason(status) !== null +} + +export function clampNotifyNote(note: string | null | undefined): string | null { + if (typeof note !== 'string') return null + const trimmed = note.trim() + if (trimmed.length === 0) return null + return trimmed.length <= NOTIFY_NOTE_MAX_CHARS + ? trimmed + : `${trimmed.slice(0, NOTIFY_NOTE_MAX_CHARS - 1)}…` +} + +/** + * Pick the operator-facing note from a notify footer. + * `action` ("what remains", <=12 words) is more actionable than the prose + * `summary`, so it wins when present. + */ +export function pickNotifyNote( + footer: { action?: string; summary?: string } +): string | null { + return clampNotifyNote(footer.action) ?? clampNotifyNote(footer.summary) +} diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index b37e188d33b..ff1ba47099b 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -4,6 +4,7 @@ import { COPILOT_AGENT_MODES, type CopilotAgentMode } from './copilotModes' import { CODEX_COLLABORATION_MODES, PERMISSION_MODES } from './modes' import { AgentConfigDescriptorSchema } from './agentConfig' import { githubPrIdentityKey, isValidGitHubHost } from './projectRegistry' +import { SUPPORTED_LIVE_DISMISSAL_CAP } from './sessionSummary' export const PermissionModeSchema = z.enum(PERMISSION_MODES) export const CodexCollaborationModeSchema = z.enum(CODEX_COLLABORATION_MODES) @@ -568,6 +569,26 @@ export const TeamStateSchema = z.object({ export type TeamState = z.infer +/** Last `AGENT_NOTIFY_SUMMARY` footer the agent emitted (see `notifyAttention`). */ +export const SessionNotifySignalSchema = z.object({ + status: z.string(), + at: z.number(), + note: z.string().nullable().default(null) +}) + +/** Operator's manual unblock acknowledgement (#1717). */ +export const SessionBlockedAckSchema = z.object({ + at: z.number(), + reason: z.string(), + // Bounded by SUPPORTED_LIVE_DISMISSAL_CAP (#1717 cold-review rounds + // 22-24): a key must stay dismissed-but-live for as long as its request + // (or the current footer) is tracked at all, and `AgentState.requests` + // has no enforced limit, so this is a generous practical ceiling, not a + // derived one — a cap tied to an unrelated preview limit rejected a + // full-session snapshot at 202 genuinely live dismissals. + keys: z.array(z.string().max(256)).max(SUPPORTED_LIVE_DISMISSAL_CAP).nullish() +}) + export const ThreadGoalStatusSchema = z.enum([ 'active', 'paused', @@ -609,6 +630,10 @@ export const DecryptedMessageSchema = z.object({ localId: z.string().nullable(), content: z.unknown(), createdAt: z.number(), + /** When the HUB received this message, vs `createdAt`'s runner clock + * (#1717). The blocked clear boundary is a hub stamp, so only this can be + * ordered against it. Optional: older hubs and senders omit it. */ + receivedAt: z.number().nullable().optional(), invokedAt: z.number().nullable().optional(), scheduledAt: z.number().nullable().optional(), // The agent was sent the steer but its final outcome could not be proven. @@ -652,6 +677,32 @@ export const SessionSchema = z.object({ agentStateVersion: z.number(), thinking: z.boolean(), thinkingAt: z.number(), + // Monotonic hub-issued counter, bumped on every `thinking`/ + // `thinkingConfirmed` transition (#1717 cold-review round 27). `thinkingAt` + // is the CLI's clamped alive-report time, not a hub-issued revision — two + // transitions processed within the same clamped-to-"now" millisecond (a + // CLI reconnect replaying buffered ticks, or plain bad luck) can carry + // the SAME `thinkingAt`, which a strict `>` ordering check cannot then + // tell apart. This counter can't collide: it increments once per + // transition regardless of wall-clock resolution. Optional so an older + // hub's objects (reconstructed before this field existed) still parse; + // defaults to 0 wherever read. + thinkingRevision: z.number().optional(), + // One value per hub process (#1717 cold-review round 30); see + // `SessionCache.hubGeneration`. `thinkingRevision` resets to 0 on a + // restart, but a restarted hub's counter can tick past 0 again before a + // reconnecting client's first update lands — the zero-exception alone + // only covers the instant nothing has ticked yet. This lets a client + // detect "this came from a different process" directly, regardless of + // what the revision number itself reads. + hubGeneration: z.string().optional(), + // False only during the hub's optimistic queue-to-delivery grace window + // (#1717 cold-review round 22): `markMessageQueued` sets `thinking: true` + // before the CLI has confirmed it ever saw the prompt, so a reply + // cancelled in that window never genuinely started a turn. Absent on + // older hubs and once the CLI confirms, so a client that ignores it keeps + // today's behaviour. + thinkingConfirmed: z.boolean().optional(), activeTurnStartedAt: z.number().nullable().optional(), backgroundTaskCount: z.number().optional(), backgroundTasks: z.array(BackgroundTaskSchema).optional(), @@ -668,6 +719,16 @@ export const SessionSchema = z.object({ // full-session payloads and hand-built Session literals stay valid. todosUpdatedAt: z.number().optional(), teamStateUpdatedAt: z.number().optional(), + /** Last agent notify footer. Drives the session list's blocked chrome; + * nullish on hubs that have not seen a footer for this session yet. */ + lastNotify: SessionNotifySignalSchema.nullish(), + /** Operator dismissed blocked chrome up to this point; newer blockers still + * count. See `SessionBlockedAck`. */ + blockedAck: SessionBlockedAckSchema.nullish(), + /** Monotonic watermark for `lastNotify` / `blockedAck` (#1717). Both ride + * full-session snapshots on two SSE streams, so a client needs an ordering + * key to reject a stale snapshot that would revive a cleared blocker. */ + notifyUpdatedAt: z.number().int().nonnegative().safe().optional(), model: z.string().nullable().optional().default(null), modelReasoningEffort: z.string().nullable().optional().default(null), effort: z.string().nullable().optional().default(null), @@ -803,6 +864,15 @@ export const SessionPatchSchema = z.object({ lastUserMessageAt: z.number().optional(), active: z.boolean().optional(), thinking: z.boolean().optional(), + thinkingConfirmed: z.boolean().optional(), + thinkingAt: z.number().optional(), + // Monotonic ordering value for `thinking`/`thinkingConfirmed` (#1717 + // cold-review round 27); see `Session.thinkingRevision`. A wall-clock + // `thinkingAt` cannot order two transitions that land in the same + // clamped-to-"now" millisecond — this hub-issued counter always can. + thinkingRevision: z.number().optional(), + // See `Session.hubGeneration` (#1717 cold-review round 30). + hubGeneration: z.string().optional(), activeTurnStartedAt: z.number().nullable().optional(), activeAt: z.number().optional(), updatedAt: z.number().optional(), diff --git a/shared/src/sessionSummary.test.ts b/shared/src/sessionSummary.test.ts index df72baac693..6f652625a62 100644 --- a/shared/src/sessionSummary.test.ts +++ b/shared/src/sessionSummary.test.ts @@ -3,7 +3,10 @@ import type { Session } from './schemas' import { PENDING_REQUEST_SUMMARY_CAP, computePendingRequestKinds, + computePendingRequestRefs, + computePendingRequests, computePendingRequestsCount, + computePendingRequestsNewestAt, computeTodoProgress, getPendingRequestKinds, getPendingRequests, @@ -364,6 +367,49 @@ describe('summary derivation helpers', () => { expect(computePendingRequestsCount(undefined)).toBe(0) }) + it('computePendingRequestsNewestAt ignores the summary cap (#1717)', () => { + // `pendingRequests` keeps the five OLDEST, so the carried slice cannot + // answer "did anything arrive after the operator dismissed this?". + // This watermark is computed over every request for exactly that. + const requests: Record = {} + for (let i = 0; i < 7; i += 1) { + requests[`req${i}`] = { tool: 'Bash', arguments: {}, createdAt: 1_000 + i } + } + expect(computePendingRequestsNewestAt({ requests } as never, 0)).toBe(1_006) + expect(computePendingRequests({ requests } as never, 0)).toHaveLength(5) + }) + + it('does not classify a genuine permission as non-blocking just because its own tool input has an isBlocking field (#1717 cold-review round 36)', () => { + // `arguments` on a permission request is the generic adapter's + // pass-through of the TOOL's own call input, not a hapi signal. An + // MCP tool with its own `isBlocking` parameter called with `false` + // must not be read the same way as Codex's async question tool — + // the approval still pauses the agent either way. + const requests = { + 'mcp-permission': { + tool: 'some_mcp_tool', + arguments: { isBlocking: false, path: '/tmp/x' }, + createdAt: 1_000 + }, + 'async-question': { + tool: 'request_user_input', + arguments: { isBlocking: false, questions: ['ok?'] }, + createdAt: 2_000 + } + } + const items = computePendingRequests({ requests } as never, 0) + expect(items.find(r => r.id === 'mcp-permission')?.nonBlocking).toBeUndefined() + expect(items.find(r => r.id === 'async-question')?.nonBlocking).toBe(true) + }) + + it('computePendingRequestsNewestAt falls back and handles empty state', () => { + expect(computePendingRequestsNewestAt(null, 42)).toBe(0) + expect(computePendingRequestsNewestAt( + { requests: { a: { tool: 'Bash', arguments: {} } } } as never, + 777 + )).toBe(777) + }) + it('includes attachedJob when provided via extras', () => { const job = { key: 'beets', @@ -434,3 +480,114 @@ describe('summary derivation helpers', () => { expect(summary?.conversationHistory).toEqual({ forkCurrent: true, forkAtMessage: true }) }) }) + +describe('computePendingRequestRefs', () => { + it('prefers an undismissed overflow request over an older dismissed one (cold-review round 23)', () => { + // 201 pending requests: the oldest 200 (req-000..req-199) are all + // dismissed, and the 201st (req-200, newest) is not. Plain + // oldest-first truncation to 200 keeps req-000..req-199 and drops + // req-200 — the one genuinely unanswered request — off the list + // entirely, so `getSessionBlockedState` (which only ever sees this + // capped list) reads the session as clear even though + // `pendingRequestsCount` says 201. + const requests: Record = {} + for (let i = 0; i < 201; i += 1) { + requests[`req-${i.toString().padStart(3, '0')}`] = { tool: 'Bash', arguments: {}, createdAt: i } + } + const session = makeSession({ agentState: { requests } }) + const dismissedKeys = new Set( + Array.from({ length: 200 }, (_, i) => `request:req-${i.toString().padStart(3, '0')}`) + ) + + const refs = computePendingRequestRefs(session.agentState, session.updatedAt, dismissedKeys) + expect(refs).toHaveLength(200) + expect(refs.map(r => r.id)).toContain('req-200') + // Still oldest-first in the RETURNED order, just not oldest-first in + // which ones survived truncation. + expect(refs[refs.length - 1]!.id).toBe('req-200') + }) + + it('falls back to plain oldest-first truncation when nothing is dismissed', () => { + const requests: Record = {} + for (let i = 0; i < 201; i += 1) { + requests[`req-${i.toString().padStart(3, '0')}`] = { tool: 'Bash', arguments: {}, createdAt: i } + } + const session = makeSession({ agentState: { requests } }) + + const refs = computePendingRequestRefs(session.agentState, session.updatedAt) + expect(refs).toHaveLength(200) + expect(refs.map(r => r.id)).not.toContain('req-200') + }) + + it('keeps the newest undismissed question over 200 older undismissed permissions (cold-review round 27)', () => { + // Truncation with no dismissedKeys fell back to plain oldest-first, + // with no kind awareness at all — so a genuinely higher-priority + // question that happened to be newest was indistinguishable from + // any other overflow request and got dropped just the same. + const requests: Record = {} + for (let i = 0; i < 200; i += 1) { + requests[`perm-${i.toString().padStart(3, '0')}`] = { tool: 'Bash', arguments: {}, createdAt: i } + } + requests['question-1'] = { tool: 'AskUserQuestion', arguments: {}, createdAt: 300 } + const session = makeSession({ agentState: { requests } }) + + const refs = computePendingRequestRefs(session.agentState, session.updatedAt) + expect(refs).toHaveLength(200) + expect(refs.map(r => r.id)).toContain('question-1') + expect(refs.find(r => r.id === 'question-1')?.kind).toBe('input') + }) + + it('ranks an undismissed question ahead of an undismissed permission, both ahead of anything dismissed', () => { + const requests: Record = {} + for (let i = 0; i < 199; i += 1) { + requests[`perm-dismissed-${i.toString().padStart(3, '0')}`] = { tool: 'Bash', arguments: {}, createdAt: i } + } + requests['perm-undismissed'] = { tool: 'Bash', arguments: {}, createdAt: 200 } + requests['question-undismissed'] = { tool: 'AskUserQuestion', arguments: {}, createdAt: 300 } + const session = makeSession({ agentState: { requests } }) + const dismissedKeys = new Set( + Array.from({ length: 199 }, (_, i) => `request:perm-dismissed-${i.toString().padStart(3, '0')}`) + ) + + const refs = computePendingRequestRefs(session.agentState, session.updatedAt, dismissedKeys) + expect(refs).toHaveLength(200) + expect(refs.map(r => r.id)).toContain('question-undismissed') + expect(refs.map(r => r.id)).toContain('perm-undismissed') + }) + + it('keeps a genuine blocking permission over 200 non-blocking async questions (#1717 cold-review round 29)', () => { + // `getPendingBlockedState` returns early the moment `pendingRequestRefs` + // is non-empty — filtering to blocking refs THERE, with no fallback + // to the uncapped totals if that leaves nothing. 200 accumulated + // Codex async questions (non-blocking) filling every cap slot would + // push a genuinely pending permission out of this list entirely, + // and the session would never show as blocked at all despite it. + const requests: Record = {} + for (let i = 0; i < 200; i += 1) { + requests[`async-${i.toString().padStart(3, '0')}`] = { + tool: 'request_user_input', + arguments: { isBlocking: false, questions: ['ok?'] }, + createdAt: i + } + } + requests['perm-blocking'] = { tool: 'Bash', arguments: {}, createdAt: 300 } + const session = makeSession({ agentState: { requests } }) + + const refs = computePendingRequestRefs(session.agentState, session.updatedAt) + expect(refs).toHaveLength(200) + expect(refs.map(r => r.id)).toContain('perm-blocking') + expect(refs.find(r => r.id === 'perm-blocking')?.nonBlocking).toBeUndefined() + }) + + it('returns everything unordered-by-dismissal when the full set already fits the cap', () => { + const session = makeSession({ + agentState: { requests: { + 'req-a': { tool: 'Bash', arguments: {}, createdAt: 100 }, + 'req-b': { tool: 'Edit', arguments: {}, createdAt: 200 } + } } + }) + const dismissedKeys = new Set(['request:req-a']) + const refs = computePendingRequestRefs(session.agentState, session.updatedAt, dismissedKeys) + expect(refs.map(r => r.id)).toEqual(['req-a', 'req-b']) + }) +}) diff --git a/shared/src/sessionSummary.ts b/shared/src/sessionSummary.ts index da08d98cf72..aea84dd9883 100644 --- a/shared/src/sessionSummary.ts +++ b/shared/src/sessionSummary.ts @@ -2,6 +2,8 @@ import type { AgentState, AttachedJob, ExternalRef, Metadata, Session, TodoItem, import type { SessionReadState } from './sessionReadState' import type { ConversationHistoryCapabilities } from './conversationHistory' import { isKnownFlavor } from './flavors' +import type { SessionBlockedAck, SessionNotifySignal } from './notifyAttention' +import { requestBlockerKey } from './notifyAttention' import type { AgentFlavor } from './modes' export type ForkSessionSummary = { @@ -25,6 +27,13 @@ export function buildForkSessionSummary( export type PendingRequestKind = 'permission' | 'input' +/** + * Requests that are a *question for the operator* rather than a permission to + * act. `CursorCreatePlan` is Cursor's plan-approval prompt — the direct + * analogue of Claude's `ExitPlanMode`, and the second most common request tool + * in the wild (16 occurrences on a 683-session fleet) — so omitting it left + * every Cursor plan review misclassified as a plain permission. + */ const INPUT_REQUEST_TOOLS = new Set([ 'AskUserQuestion', 'ask_user_question', @@ -32,7 +41,9 @@ const INPUT_REQUEST_TOOLS = new Set([ 'cursor_ask_question', 'ExitPlanMode', 'exit_plan_mode', - 'request_user_input' + 'request_user_input', + 'CursorCreatePlan', + 'cursor_create_plan' ]) /** Cap on `pendingRequests` carried in `SessionSummary`. The list is meant for @@ -41,6 +52,35 @@ const INPUT_REQUEST_TOOLS = new Set([ * is the authoritative total — `pendingRequests.length` may be smaller. */ export const PENDING_REQUEST_SUMMARY_CAP = 5 +/** Cap on `pendingRequestRefs`: how many pending-request identities the + * SUMMARY surfaces for preview/dismissal-matching purposes. NOT a ceiling on + * how many requests can exist — `AgentState.requests` is `z.record(...)` + * with no `.max()`, so an agent can genuinely hold more than this many + * simultaneously pending tool/question requests at once; this just bounds + * what one list-row payload carries (#1717 cold-review round 22, corrected + * round 24 — see `SUPPORTED_LIVE_DISMISSAL_CAP`, which used to be derived + * from this value as if it WERE that ceiling and broke at 202 live + * dismissals as a result). */ +export const PENDING_REQUEST_REFS_CAP = 200 + +/** + * How many dismissal keys `SessionBlockedAck.keys` carries at once, full + * stop — not derived from, or chasing, any other number (#1717 cold-review + * rounds 22-25). `AgentState.requests` has no enforced limit, so earlier + * attempts to derive this from "the true number of concurrent requests" + * (64, then `PENDING_REQUEST_REFS_CAP + 1` = 201) just relocated the N+1 + * failure every time a bigger real case showed up — most recently at 202, + * then again at 2001 before this constant stopped being advisory. + * `serialiseAckKeys` now enforces this as a HARD bound: once every + * resolved/superseded key is already evicted, it evicts the oldest LIVE + * ones too rather than growing past it, so the wire schema (bounded by the + * SAME constant) can never reject a snapshot this hub produced. A dismissal + * on a request that is still pending can, in the pathological case of more + * than this many simultaneous live dismissals, eventually be evicted — a + * documented, bounded trade, not a silent one. + */ +export const SUPPORTED_LIVE_DISMISSAL_CAP = 2_000 + export type PendingRequest = { id: string kind: PendingRequestKind @@ -49,6 +89,15 @@ export type PendingRequest = { * `fallbackSince` (typically `session.updatedAt`) for older requests * stored without `createdAt`. */ since: number + /** True when the request itself declares `arguments.isBlocking: false` — + * Codex's asynchronous `request_user_input` questions, which the agent + * asked without pausing for an answer and keeps working through. Same + * `tool` as a genuinely blocking question, so this is the only signal + * that tells them apart; callers that decide whether the OPERATOR is + * the one the agent is stuck waiting on (the Blocked section, arrival + * alerts) must exclude these, while the ordinary per-row attention dot + * still shows them. */ + nonBlocking?: boolean } /** Whether a request asks the user to answer something (a question, a plan) @@ -57,6 +106,19 @@ export function classifyKind(tool: string): PendingRequestKind { return INPUT_REQUEST_TOOLS.has(tool) ? 'input' : 'permission' } +/** `arguments.isBlocking === false` on Codex's own async question tool. + * `arguments` on a PERMISSION request is the generic adapter's pass- + * through of the tool's own call input (cli/src/agent/permissionAdapter.ts), + * not a hapi-authored signal — an MCP tool with its own `isBlocking` + * parameter called with `false` would otherwise read as non-blocking here + * even though the approval still pauses the agent (#1717 cold-review + * round 36). Scoped to the one tool this signal actually comes from. */ +function isNonBlockingRequest(tool: string, args: unknown): boolean { + return tool === 'request_user_input' + && typeof args === 'object' && args !== null && !Array.isArray(args) + && (args as Record).isBlocking === false +} + export type SessionSummaryMetadata = { name?: string titleLocked?: boolean @@ -99,6 +161,31 @@ export type SessionSummary = { id: string active: boolean thinking: boolean + /** False only during the hub's optimistic queue-to-delivery grace window + * (#1717 cold-review round 22); see `Session.thinkingConfirmed`. */ + thinkingConfirmed?: boolean + /** Ordering value for `thinking`/`thinkingConfirmed` (#1717 cold-review + * round 26); see `Session.thinkingAt`. Neither field carries its own + * revision otherwise, so a REST list GET captured while the agent was + * still thinking can land after an SSE idle patch and restore a stale + * `thinking: true` — which then hides a genuinely unanswered blocker, + * since the attention classifier treats "still thinking" as "nothing to + * show yet". Optional so an older hub (no column to read it from) can + * omit it; absent on either side, the merge takes the incoming value, + * matching today's behaviour. */ + thinkingAt?: number + /** Monotonic hub-issued counter, bumped on every `thinking`/ + * `thinkingConfirmed` transition (#1717 cold-review round 27); see + * `Session.thinkingRevision`. `thinkingAt` is the CLI's clamped + * alive-report time, not a hub-issued revision — two transitions + * processed within the same clamped-to-"now" millisecond can carry the + * SAME `thinkingAt`, which a strict `>` check on it cannot then tell + * apart. This field is the actual ordering value; `thinkingAt` is + * carried for display only. Optional for the same reason `thinkingAt` + * is — absent on either side, the merge takes the incoming value. */ + thinkingRevision?: number + /** See `Session.hubGeneration` (#1717 cold-review round 30). */ + hubGeneration?: string activeAt: number updatedAt: number /** Creation time is the stable order key before the first user message. */ @@ -121,6 +208,16 @@ export type SessionSummary = { * / per-row UX. The full count (which may exceed the cap) is in * `pendingRequestsCount`. */ pendingRequests: PendingRequest[] + /** Newest request time across ALL pending requests, ignoring the cap above. + * Optional so an older hub can omit it. Lets a client tell "every prompt + * was acknowledged" from "the acknowledged ones are merely the only ones + * the capped slice carried". */ + pendingRequestsNewestAt?: number + /** Every pending request id, uncapped. `pendingRequests` keeps only the + * oldest few, so an overflow prompt had no identity and fell back to a + * synthetic one — a dismissal then stopped matching the moment the real + * request entered the capped slice. Ids are small; the bodies are not. */ + pendingRequestRefs?: Array<{ id: string; kind: PendingRequestKind; since: number; nonBlocking?: boolean }> backgroundTaskCount: number /** * Hub-derived "open tool work exists in the transcript tail" (work-scoped @@ -130,6 +227,14 @@ export type SessionSummary = { * Optional because older hubs never send it. */ derivedToolWork?: boolean + /** Last `AGENT_NOTIFY_SUMMARY` footer. Orthogonal to `pendingRequestKinds`: + * pending requests mean "live, waiting on a click", this means "the turn + * ended and the agent said it is stuck". See `./notifyAttention`. */ + lastNotify?: SessionNotifySignal | null + /** Operator's manual "not blocked" watermark + rationale. */ + blockedAck?: SessionBlockedAck | null + /** Ordering key for the two fields above; see `Session.notifyUpdatedAt`. */ + notifyUpdatedAt?: number futureScheduledMessageCount: number /** Epoch ms of the soonest uninvoked future scheduled message, or null. */ nextScheduledAt: number | null @@ -180,7 +285,8 @@ export function computePendingRequests( id, kind: classifyKind(request.tool), tool: request.tool, - since: typeof request.createdAt === 'number' ? request.createdAt : fallbackSince + since: typeof request.createdAt === 'number' ? request.createdAt : fallbackSince, + ...(isNonBlockingRequest(request.tool, request.arguments) ? { nonBlocking: true as const } : {}) }) } @@ -207,6 +313,114 @@ export function computePendingRequestsCount(agentState: AgentState | null | unde return agentState?.requests ? Object.keys(agentState.requests).length : 0 } +/** + * Newest request time across ALL pending requests, uncapped (0 when none). + * + * `pendingRequests` is capped at `PENDING_REQUEST_SUMMARY_CAP` and keeps the + * OLDEST entries, so once the cap is full the carried slice cannot answer + * "did anything arrive after the operator dismissed this?" — the newer prompt + * is simply absent. Computed from `agentState` like `pendingRequestsCount`, + * so it costs no storage and needs no migration. + */ +/** + * A light descriptor for EVERY pending request, uncapped (#1717). + * + * `pendingRequests` keeps only the oldest few, so a session whose previewed + * prompts have all been dismissed says nothing about the ones behind them. + * The id alone was not enough either: the chip read its label and age off + * aggregate fields that describe all prompts at once, so an overflow question + * could be drawn as a Permission with another prompt's timestamp. Carrying the + * kind and `since` with the id keeps the chip, the dismissal target and the + * age all describing the same request. Same order as `pendingRequests`, so the + * capped list is always this list's prefix — UNLESS truncation had to choose, + * in which case the smaller list is still guaranteed to be a SUBSET (see + * below), just not necessarily a strict prefix. + * + * `dismissedKeys` lets truncation prefer an UNDISMISSED request over a + * dismissed one when there are more than `PENDING_REQUEST_REFS_CAP` pending + * at once (#1717 cold-review round 23). Without it, truncation is purely + * oldest-first: if the operator dismisses the oldest 200 of 201 pending + * requests, the 201st — genuinely unanswered — falls off this list entirely, + * and `getSessionBlockedState` (which only ever sees THIS list, not the full + * `agentState`) reads the session as clear. + * + * Truncation also prefers a QUESTION over a PERMISSION within the same + * dismissed/undismissed tier (#1717 cold-review round 27): the classifier + * ranks a question ahead of a permission among whatever refs it is handed, + * but only ever sees this capped list — oldest-first (or dismissal-blind-to- + * kind) truncation could drop the one question off a page of 200 older + * permissions before the classifier ever got the chance to contest it. + */ +export function computePendingRequestRefs( + agentState: AgentState | null | undefined, + fallbackSince: number, + dismissedKeys?: ReadonlySet +): Array<{ id: string; kind: PendingRequestKind; since: number; nonBlocking?: boolean }> { + const all = computePendingRequests(agentState, fallbackSince, Number.MAX_SAFE_INTEGER) + if (all.length <= PENDING_REQUEST_REFS_CAP) { + return all.slice(0, PENDING_REQUEST_REFS_CAP).map(({ id, kind, since, nonBlocking }) => ({ id, kind, since, ...(nonBlocking ? { nonBlocking } : {}) })) + } + // Oldest-first truncation alone drops whichever request happens to be + // newest once the cap is full — even an undismissed QUESTION, if 200 + // older undismissed permissions already fill every slot (#1717 + // cold-review round 27). `getSessionAttentionReason` ranks a question + // ahead of a permission among whatever refs it is GIVEN, but it only + // ever sees this capped list, never the full request set — so a + // question truncated away here never gets the chance to win that + // contest, and the chip/dialog silently fall back to the lower-priority + // permission instead. + // + // Eight buckets, not four: BLOCKING-vs-non-blocking (round 29) outranks + // both of the other dimensions, because the classifier reads refs as an + // all-or-nothing list — `getPendingBlockedState` returns early the + // moment `pendingRequestRefs` is non-empty, filters to blocking refs + // THERE, and never falls back to the uncapped totals if that leaves + // nothing. A session that piles up enough non-blocking Codex async + // questions to fill the cap could push a genuine, still-pending + // permission out of this list entirely — the one case where "ref list + // is non-empty" and "a real blocker is being reported" can disagree. + // Dismissed-vs-undismissed (round 23) and question-vs-permission + // (round 27) still matter, but only after blocking status is decided. + const isUndismissed = (request: { id: string }) => + !dismissedKeys?.has(requestBlockerKey(request.id)) + const isQuestion = (request: { kind: PendingRequestKind }) => request.kind === 'input' + const isBlocking = (request: { nonBlocking?: boolean }) => !request.nonBlocking + const buckets = [ + all.filter((request) => isBlocking(request) && isUndismissed(request) && isQuestion(request)), + all.filter((request) => isBlocking(request) && isUndismissed(request) && !isQuestion(request)), + all.filter((request) => isBlocking(request) && !isUndismissed(request) && isQuestion(request)), + all.filter((request) => isBlocking(request) && !isUndismissed(request) && !isQuestion(request)), + all.filter((request) => !isBlocking(request) && isUndismissed(request) && isQuestion(request)), + all.filter((request) => !isBlocking(request) && isUndismissed(request) && !isQuestion(request)), + all.filter((request) => !isBlocking(request) && !isUndismissed(request) && isQuestion(request)), + all.filter((request) => !isBlocking(request) && !isUndismissed(request) && !isQuestion(request)) + ] + const selectedIds = new Set( + buckets.flat().slice(0, PENDING_REQUEST_REFS_CAP).map((request) => request.id) + ) + // `all` is already oldest-first; filtering it (rather than re-sorting the + // prioritized selection) keeps the returned order chronological. + return all + .filter((request) => selectedIds.has(request.id)) + .map(({ id, kind, since, nonBlocking }) => ({ id, kind, since, ...(nonBlocking ? { nonBlocking } : {}) })) +} + +export function computePendingRequestsNewestAt( + agentState: AgentState | null | undefined, + fallbackSince: number +): number { + const requests = agentState?.requests + if (!requests) { + return 0 + } + let newest = 0 + for (const request of Object.values(requests)) { + const since = typeof request.createdAt === 'number' ? request.createdAt : fallbackSince + if (since > newest) newest = since + } + return newest +} + export function computeTodoProgress(todos: TodoItem[] | undefined): SessionSummary['todoProgress'] { if (!todos?.length) { return null @@ -305,6 +519,10 @@ export function toSessionSummary( id: session.id, active: session.active, thinking: session.thinking, + thinkingConfirmed: session.thinkingConfirmed, + thinkingAt: session.thinkingAt, + thinkingRevision: session.thinkingRevision, + hubGeneration: session.hubGeneration, activeAt: session.activeAt, updatedAt: session.updatedAt, contentRevision: session.contentRevision, @@ -321,8 +539,17 @@ export function toSessionSummary( pendingRequestsCount: computePendingRequestsCount(session.agentState), pendingRequestKinds: computePendingRequestKinds(session.agentState), pendingRequests: computePendingRequests(session.agentState, session.updatedAt), + pendingRequestsNewestAt: computePendingRequestsNewestAt(session.agentState, session.updatedAt), + pendingRequestRefs: computePendingRequestRefs( + session.agentState, + session.updatedAt, + session.blockedAck?.keys ? new Set(session.blockedAck.keys) : undefined + ), backgroundTaskCount: session.backgroundTaskCount ?? 0, derivedToolWork: session.derivedToolWork === true, + lastNotify: session.lastNotify ?? null, + blockedAck: session.blockedAck ?? null, + notifyUpdatedAt: session.notifyUpdatedAt ?? 0, futureScheduledMessageCount: 0, nextScheduledAt: null, attachedJob, diff --git a/web/e2e-fixtures/session-list-blocked-fixture.html b/web/e2e-fixtures/session-list-blocked-fixture.html new file mode 100644 index 00000000000..085c82ceadb --- /dev/null +++ b/web/e2e-fixtures/session-list-blocked-fixture.html @@ -0,0 +1,12 @@ + + + + + + Blocked session-list fixture + + +
+ + + diff --git a/web/e2e-fixtures/session-list-blocked-fixture.tsx b/web/e2e-fixtures/session-list-blocked-fixture.tsx new file mode 100644 index 00000000000..5b3b80f6a41 --- /dev/null +++ b/web/e2e-fixtures/session-list-blocked-fixture.tsx @@ -0,0 +1,188 @@ +import React from 'react' +import ReactDOM from 'react-dom/client' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import '../src/index.css' +import type { SessionSummary } from '../src/types/api' +import { I18nProvider } from '../src/lib/i18n-context' +import { ToastProvider } from '../src/lib/toast-context' +import { SessionList } from '../src/components/SessionList' + +/** + * Fleet-scale session list for the #1717 blocked chrome. + * + * Deliberately seeds enough projects and rows that the blocked sessions fall + * outside the initial viewport — the off-viewport case is the whole point of + * the header pill, and a three-row fixture would prove nothing. + */ +// Relative to the wall clock on purpose: the loud-vs-stale split is measured +// against "now", so a frozen epoch would make every seeded footer stale. +const NOW = Date.now() +const HOUR = 60 * 60 * 1000 + +const PROJECTS = [ + 'hapi', 'cli', 'hub', 'web', 'shared', + 'relay', 'runner', 'protocol', 'website', 'docs', + 'android', 'ios', 'telemetry', 'billing', 'infra', + 'scratch', 'sandbox', 'bench', 'archive', 'tooling', + 'gateway', 'scheduler', 'importer', 'search' +] + +function base(id: string, index: number, project: string): SessionSummary { + return { + id, + active: false, + thinking: false, + activeAt: 0, + updatedAt: NOW - index * 7 * 60_000, + metadata: { + path: `/home/heavygee/coding/${project}`, + name: `${project} · task ${index + 1}`, + flavor: index % 3 === 0 ? 'claude' : index % 3 === 1 ? 'codex' : 'gemini' + }, + metadataVersion: 0, + agentStateVersion: 0, + todosUpdatedAt: 0, + todoProgress: null, + pendingRequestsCount: 0, + pendingRequestKinds: [], + pendingRequests: [], + backgroundTaskCount: 0, + lastNotify: null, + futureScheduledMessageCount: 0, + nextScheduledAt: null, + model: null, + effort: null + } +} + +const SESSIONS: SessionSummary[] = [] +let counter = 0 +for (const project of PROJECTS) { + for (let i = 0; i < 4; i += 1) { + SESSIONS.push(base(`${project}-${i}`, counter, project)) + counter += 1 + } +} + +// A working agent and an idle-connected agent, so the blocked treatment has to +// hold its own against the rest of the list's attention vocabulary rather than +// being the only thing on screen. +SESSIONS[1] = { ...SESSIONS[1]!, active: true, thinking: true } +SESSIONS[3] = { ...SESSIONS[3]!, active: true } + +// Prompt-parked agents. These count as blocked too: the operator cannot let +// them proceed without answering, which is the same problem as a self-reported +// blocked footer. +SESSIONS[2] = { + ...SESSIONS[2]!, + active: true, + pendingRequestsCount: 1, + pendingRequestKinds: ['permission'], + pendingRequests: [{ id: 'r1', kind: 'permission', tool: 'Bash', since: NOW - 2 * 60_000 }] +} +SESSIONS[61] = { + ...SESSIONS[61]!, + active: true, + pendingRequestsCount: 1, + pendingRequestKinds: ['input'], + pendingRequests: [{ id: 'r2', kind: 'input', tool: 'AskUserQuestion', since: NOW - 12 * 60_000 }] +} +// Cursor's plan-approval prompt — same class of ask as Claude's ExitPlanMode. +SESSIONS[70] = { + ...SESSIONS[70]!, + active: true, + pendingRequestsCount: 1, + pendingRequestKinds: ['input'], + pendingRequests: [{ id: 'r3', kind: 'input', tool: 'CursorCreatePlan', since: NOW - 20 * 60_000 }] +} + +// The rest of the vocabulary the operator counts as blocking. +SESSIONS[36] = { + ...SESSIONS[36]!, + lastNotify: { status: 'needs_decision', at: NOW - 25 * 60_000, note: 'pick auth approach' } +} +SESSIONS[42] = { + ...SESSIONS[42]!, + lastNotify: { status: 'needs_review', at: NOW - 90 * 60_000, note: 'diff ready for review' } +} +SESSIONS[55] = { + ...SESSIONS[55]!, + lastNotify: { status: 'failed', at: NOW - 8 * 60_000, note: 'migration threw on v29' } +} +// Non-contract but the most-emitted waiting status in the wild (92 uses). +SESSIONS[66] = { + ...SESSIONS[66]!, + lastNotify: { status: 'pending', at: NOW - 35 * 60_000, note: 'awaiting operator call' } +} +// Must NOT light up — non-contract synonym for done. +SESSIONS[74] = { + ...SESSIONS[74]!, + lastNotify: { status: 'completed', at: NOW - 4 * 60_000, note: null } +} + +// Blocked rows, deliberately scattered deep into the list. +SESSIONS[14] = { + ...SESSIONS[14]!, + active: true, + lastNotify: { status: 'blocked', at: NOW - 5 * 60_000, note: 'needs prod DB credentials' } +} +SESSIONS[29] = { + ...SESSIONS[29]!, + lastNotify: { status: 'blocked', at: NOW - 40 * 60_000, note: 'upstream PR review required' } +} +SESSIONS[47] = { + ...SESSIONS[47]!, + lastNotify: { status: 'stalled', at: NOW - 3 * HOUR, note: 'cannot reproduce the failing test' } +} +// Past the loud window — must demote to muted rather than alarm forever. +SESSIONS[52] = { + ...SESSIONS[52]!, + lastNotify: { status: 'blocked', at: NOW - 40 * HOUR, note: 'abandoned three days ago' } +} + +const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } } +}) + +function Fixture() { + // Test seam: let the spec push a NEW blocker in so the arrival alert can be + // observed. Arrival is the whole point — a static fixture can only ever + // show the resting state. + const [extra, setExtra] = React.useState([]) + React.useEffect(() => { + ;(window as unknown as { __addBlocker?: () => void }).__addBlocker = () => { + setExtra([{ + ...base('late-blocker', 0, 'hapi'), + lastNotify: { status: 'blocked', at: Date.now(), note: 'just now' } + }]) + } + }, []) + return ( +
+ {}} + onNewSession={() => {}} + onRefresh={() => {}} + isLoading={false} + api={null} + /> +
+ ) +} + +const root = document.getElementById('root') +if (root) { + ReactDOM.createRoot(root).render( + + + + + + + + + + ) +} diff --git a/web/src/App.tsx b/web/src/App.tsx index 39accecd80c..e2973a12c52 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -250,8 +250,8 @@ function AppInner() { } const { pathname, search, hash, state } = router.history.location const browserUrl = new URL(window.location.href) - const nextHref = pathname + cleanParams(search, '?') + (dropLaunchData ? cleanParams(hash, '#') : hash) - const browserHref = browserUrl.pathname + cleanParams(browserUrl.search, '?') + (dropLaunchData ? cleanParams(browserUrl.hash, '#') : browserUrl.hash) + const nextHref = pathname + cleanParams(search, '?') + cleanParams(hash, '#') + const browserHref = browserUrl.pathname + cleanParams(browserUrl.search, '?') + cleanParams(browserUrl.hash, '#') if (nextHref !== pathname + search + hash) router.history.replace(nextHref, state) // Telegram bootstrap may use memory history; auth reads the real URL. if (browserHref !== browserUrl.pathname + browserUrl.search + browserUrl.hash) window.history.replaceState(window.history.state, '', browserHref) diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 775f6362b59..1ae244cfb0a 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -1601,6 +1601,20 @@ export class ApiClient { }) } + /** #1717: manually mark a blocked session as not blocked, with a rationale. */ + async acknowledgeSessionBlocked( + sessionId: string, + reason: string, + observed?: { at: number; key: string } + ): Promise { + await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/blocked-ack`, { + method: 'PUT', + body: JSON.stringify(observed === undefined + ? { reason } + : { reason, observedAt: observed.at, observedKey: observed.key }) + }) + } + async clearStaleSessionJob(sessionId: string, job: AttachedJob): Promise { await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/jobs/${encodeURIComponent(job.key)}/clear-stale`, { method: 'POST', body: JSON.stringify({ runId: job.runId, startedAt: job.startedAt, heartbeatAt: job.heartbeatAt }) diff --git a/web/src/components/DissolveGroupButton.tsx b/web/src/components/DissolveGroupDialog.tsx similarity index 81% rename from web/src/components/DissolveGroupButton.tsx rename to web/src/components/DissolveGroupDialog.tsx index 2ac3a9acd8c..af0e9be528b 100644 --- a/web/src/components/DissolveGroupButton.tsx +++ b/web/src/components/DissolveGroupDialog.tsx @@ -1,4 +1,3 @@ -import { useState } from 'react' import { MutationObserver, useMutation, useQueryClient } from '@tanstack/react-query' import type { ApiClient } from '@/api/client' import type { SessionSummary } from '@/types/api' @@ -8,7 +7,6 @@ import { queryKeys } from '@/lib/query-keys' import { summarizeGroupDissolve } from '@/lib/sessionGroups' import { sessionArchiveMutationKey } from '@/hooks/mutations/useSessionActions' import { ConfirmDialog } from '@/components/ui/ConfirmDialog' -import { ArchiveIcon } from '@/components/icons' import { isArchivable } from '@/components/ProjectGroupRow' /** @@ -62,29 +60,42 @@ function isStarting(session: SessionSummary, now: number): boolean { } /** - * Dissolves a session group: archives its members, then its leader. The group - * is only the spawn relationship, so nothing else has to be removed, and the - * archived sessions stay grouped in the list. + * Sessions dissolving the group led by `leader` would archive: every running + * (or unconfirmed) member, then the leader if it is running or unconfirmed. + * Empty when there is nothing left to dissolve. + */ +export function getGroupDissolveTargets( + leader: SessionSummary, + members: readonly SessionSummary[], + scope: string | null +): { members: SessionSummary[]; leader: SessionSummary[]; live: SessionSummary[] } { + const unconfirmed = readUnconfirmed(scope, leader.id) + const targetMembers = members.filter(member => isArchivable(member) || unconfirmed.has(member.id)) + const liveLeader = isArchivable(leader) || unconfirmed.has(leader.id) ? [leader] : [] + return { members: targetMembers, leader: liveLeader, live: [...targetMembers, ...liveLeader] } +} + +/** + * Confirms and runs dissolving a session group: archives its members, then + * its leader. The group is only the spawn relationship, so nothing else has + * to be removed, and the archived sessions stay grouped in the list. * * `members` is every member of the leader, not only the rows the list shows. + * Opened from the leader row's action menu. */ -export function DissolveGroupButton(props: { +export function DissolveGroupDialog(props: { leader: SessionSummary members: readonly SessionSummary[] leaderTitle: string api: ApiClient | null - className?: string + onClose: () => void }) { - const { leader, api, leaderTitle } = props + const { leader, api, leaderTitle, onClose } = props const { t } = useTranslation() const addToast = useAddToast() const queryClient = useQueryClient() - const [confirmOpen, setConfirmOpen] = useState(false) const scope = api?.getReadStateScope?.() ?? null - const unconfirmed = readUnconfirmed(scope, leader.id) - const targetMembers = props.members.filter(member => isArchivable(member) || unconfirmed.has(member.id)) - const liveLeader = isArchivable(leader) || unconfirmed.has(leader.id) ? [leader] : [] - const live = [...targetMembers, ...liveLeader] + const { members: targetMembers, leader: liveLeader, live } = getGroupDissolveTargets(leader, props.members, scope) const dissolve = useMutation({ mutationFn: async () => { @@ -156,29 +167,16 @@ export function DissolveGroupButton(props: { ].filter(Boolean).join(' ') return ( - <> - - {confirmOpen ? ( - setConfirmOpen(false)} - title={t('sessions.members.dissolve')} - description={description} - confirmLabel={t('dialog.archive.confirm')} - confirmingLabel={t('dialog.archive.confirming')} - onConfirm={dissolve.mutateAsync} - isPending={dissolve.isPending} - destructive - /> - ) : null} - + ) } diff --git a/web/src/components/SessionActionMenu.tsx b/web/src/components/SessionActionMenu.tsx index 9c82af88dfc..7ddd12db25b 100644 --- a/web/src/components/SessionActionMenu.tsx +++ b/web/src/components/SessionActionMenu.tsx @@ -82,9 +82,13 @@ type SessionActionMenuProps = { translateInputEnabled?: boolean onForkSession?: () => void forkDisabledReason?: string + /** #1717: present only when the session currently reads as blocked. */ + onMarkUnblocked?: () => void onSyncCodex?: () => void onSyncPi?: () => void onArchive: () => void + /** Present on a group leader whose group still has sessions to archive. */ + onDissolveGroup?: () => void onReopen?: () => void reopenDisabledReason?: string /** Soft-fail tip when reopen is allowed but chat-store probe could not verify. */ @@ -284,9 +288,11 @@ export function SessionActionMenu(props: SessionActionMenuProps) { translateInputEnabled = false, onForkSession, forkDisabledReason, + onMarkUnblocked, onSyncCodex, onSyncPi, onArchive, + onDissolveGroup, onReopen, reopenDisabledReason, reopenHint, @@ -329,6 +335,11 @@ export function SessionActionMenu(props: SessionActionMenuProps) { onArchive() } + const handleDissolveGroup = () => { + onClose() + onDissolveGroup?.() + } + const handleReopen = () => { onClose() onReopen?.() @@ -349,6 +360,11 @@ export function SessionActionMenu(props: SessionActionMenuProps) { onForkSession?.() } + const handleMarkUnblocked = () => { + onClose() + onMarkUnblocked?.() + } + const handleSyncCodex = () => { onClose() onSyncCodex?.() @@ -376,6 +392,13 @@ export function SessionActionMenu(props: SessionActionMenuProps) { return (
@@ -479,6 +502,26 @@ export function SessionActionMenu(props: SessionActionMenuProps) { ) : null} + {onMarkUnblocked ? ( + + ) : null} + {readTarget ? : null} @@ -554,6 +597,17 @@ export function SessionActionMenu(props: SessionActionMenuProps) { ) : null} + {onDissolveGroup ? ( + + ) : null} {canArchive ? ( + ) +} + +function BlockedFlagIcon(props: { className?: string }) { + return ( + + ) +} + +/** + * Always-visible blocked counter (#1717). + * + * This is the off-viewport answer. Edge chevrons cannot do this job: the + * session list collapses directory groups and caps each group's preview, so a + * blocked row is frequently not merely scrolled out of view but absent from + * the DOM entirely — a "scroll down" hint would strand the operator on a + * collapsed header. A header counter is always on screen, states a number, and + * its click makes the row reachable before travelling to it. + * + * Deliberately a plain action button, not a toggle: the blocked-only lens is + * its own sibling control below, so keyboard and assistive activation reach + * both behaviours natively rather than depending on a long-press gesture. + */ +function BlockedJumpPill(props: { + count: number + direction: BlockedJumpDirection + /** Briefly true after a NEW blocker arrives — see `useBlockedArrivalAlert`. */ + alerting: boolean + onJump: (viaKeyboard: boolean) => void +}) { + const { t } = useTranslation() + const glyph = BLOCKED_DIRECTION_GLYPH[props.direction] + const label = t('sessions.blocked.jump', { count: props.count }) + + return ( + + ) +} export type SessionTimeRange = { start: number | null @@ -527,10 +734,210 @@ export function filterActiveSessionsOnly(sessions: SessionSummary[], selectedSes ) } +/** + * Re-add the selected session to a filtered list if the pipeline above + * dropped it (#1717). + * + * The jump-reveal exemption and the selected session's own exemption are + * not interchangeable: every lens filter above takes ONE exempt id + * (`revealBlockedSessionId ?? selectedSessionId`), so revealing a + * DIFFERENT stopped blocker replaces the selected session's exemption + * rather than adding to it, and the operator's already-open chat row + * disappears while the jump target is shown. `unfiltered` is searched + * (not `filtered`) because the session being restored is, by definition, + * the one a filter above already removed — it MUST be a base no + * `filterExemptId`-dependent filter has touched (e.g. `sidebarSessions`, + * not `visibleSessions`), or the saved "Active sessions only" status + * filter upstream (`listView.status`, applied against the CURRENT + * `filterExemptId` before this function ever runs) can have already + * dropped the selected session from `unfiltered` itself, leaving nothing + * to restore from (#1717 cold-review round 29). + */ +export function restoreSelectedSessionExemption( + filtered: T[], + unfiltered: T[], + selectedSessionId: string | null | undefined, + filterExemptId: string | null | undefined +): T[] { + if (selectedSessionId == null || selectedSessionId === filterExemptId) { + return filtered + } + if (filtered.some(session => session.id === selectedSessionId)) { + return filtered + } + const selectedSession = unfiltered.find(session => session.id === selectedSessionId) + return selectedSession ? [...filtered, selectedSession] : filtered +} + /** * List-view status filter with the #1404 jobs exception on "active": idle rows * that still have a running attachedJob stay visible (and stay out of archived). */ +/** + * Owns the dismissal dialog and its mutation for as long as one is open. + * + * Deliberately a separate component rather than a hook on `SessionList`: the + * row-render-isolation guard watches `useSessionActions` as its proxy for "no + * row re-rendered", and calling it on every `SessionList` render would both + * trip that guard and run a mutation hook for a null session continuously. + * Mounted while a target exists and unmounted when it clears, so the draft + * inside the dialog survives the row moving between sections — which is the + * whole point — without the row owning it. + */ +function UnblockDialogHost(props: { + target: UnblockDialogTarget + api: ApiClient | null + scrollContainer: React.RefObject + onClose: (token: UnblockDialogTarget) => void +}) { + const { target } = props + const { acknowledgeBlocked, isPending } = useSessionActions(props.api, target.sessionId) + return ( + props.scrollContainer.current + ?.querySelector( + `[data-session-id="${CSS.escape(target.sessionId)}"]` + ) + ?? document.querySelector('[data-testid="blocked-jump-pill"]') + ?? document.querySelector('[data-testid="session-list-header-row"]')} + onClose={() => props.onClose(props.target)} + onConfirm={async (reason) => { + await acknowledgeBlocked({ + reason, + observed: { at: target.at, key: target.key } + }) + }} + /> + ) +} + +/** + * Which blocked row the jump pill should travel to (#1717). + * + * The pill draws an arrow from measured off-screen counts, but the target was + * chosen by a cursor cycling through every blocker in update order — so with a + * newer blocker already visible and an older one below the fold, the arrow + * pointed down and the first click selected the row already on screen. The + * operator had to click twice to go where the arrow said. + * + * A single direction is honoured by travelling to the nearest off-screen row + * that way. With blockers both above and below, the arrow is not promising one + * direction, so the fallback order keeps cycling and repeated clicks still + * reach everything. + * + * `visited` breaks a second failure (cold-review round 21): a one-way arrow + * always re-selects the nearest off-screen row in that direction, so with a + * blocker pinned on screen, a second below the fold, and a third hidden by a + * machine filter (never present in `above`/`below` at all), a down arrow + * alternates between the first two forever and the third — which the pill's + * own count promises exists — is never reached. Skipping an already-visited + * directional candidate drops through to `fallbackOrder`, which the caller + * builds from every counted blocker, filtered ones included. + */ +export function chooseBlockedJumpTarget(options: { + direction: BlockedJumpDirection + above: string[] + below: string[] + visited: ReadonlySet + fallbackOrder: string[] +}): string { + const { direction, above, below, visited, fallbackOrder } = options + // `above` is in document order, so the LAST entry is nearest the viewport. + // `both` tries the SAME measured, guaranteed-off-screen candidates as + // the single-direction cases — nearest `above` first, then `below` — + // before ever reaching `fallbackOrder` below. Skipping straight to + // `fallbackOrder` for `both` used to let an already-ON-SCREEN row + // (not scoped to off-screen at all) win over a genuinely off-screen + // blocker the arrow was already promising existed (#1717 cold-review + // round 36). + if (direction === 'up' || direction === 'both') { + for (let i = above.length - 1; i >= 0; i -= 1) { + if (!visited.has(above[i]!)) return above[i]! + } + } + if (direction === 'down' || direction === 'both') { + for (const id of below) { + if (!visited.has(id)) return id + } + } + for (const id of fallbackOrder) { + if (!visited.has(id)) return id + } + // Every counted blocker was visited this cycle. The caller clears + // `visited` before the lap that would hit this, so it is only reachable + // from a stale snapshot mid-render — keep moving rather than return + // nothing. + return fallbackOrder[0] ?? above[above.length - 1] ?? below[0] ?? '' +} + +/** + * Off-screen blocked rows, above and below, as IDENTITIES (#1717). + * + * One list feeding both the arrow and the jump target, because two + * computations of "which blockers are off-screen" drifted apart twice: the + * arrow counted collapsed rows via their section header while the click could + * only see mounted rows, so an up arrow from a collapsed section was answered + * by a click that landed on a visible row below it. + * + * A collapsed section's rows leave the DOM once its transition settles, so + * they are taken from state and positioned at the section header — which is + * both where the arrow was computed from and where activating the pill lands. + */ +export function collectOffscreenBlockers(options: { + bounds: { top: number; bottom: number } + mounted: Array<{ id: string; top: number; bottom: number; height: number; collapsed: boolean }> + collapsedSections: Array<{ ids: string[]; headerRect: { top: number; bottom: number } | null }> +}): { above: string[]; below: string[] } { + // Collected into ONE position-ordered list before splitting into + // above/below (#1717 cold-review round 30) — appending every collapsed + // section's ids after all mounted ones (the previous two-pass shape) + // put them last in `above` regardless of where their header actually + // sits. A collapsed Pinned section above an expanded Blocked section + // (both off-screen) made `chooseBlockedJumpTarget`'s "up" branch — + // `above[above.length - 1]`, nearest the viewport — pick Pinned's id + // over Blocked's, even though Blocked's mounted rows sit CLOSER to the + // viewport than Pinned's collapsed header. + const seen = new Set() + const positioned: Array<{ id: string; top: number; bottom: number }> = [] + for (const row of options.mounted) { + if (row.collapsed) continue + if (row.height <= 0) continue + seen.add(row.id) + positioned.push({ id: row.id, top: row.top, bottom: row.bottom }) + } + for (const section of options.collapsedSections) { + const rect = section.headerRect + if (!rect) continue + for (const id of section.ids) { + if (seen.has(id)) continue + seen.add(id) + positioned.push({ id, top: rect.top, bottom: rect.bottom }) + } + } + positioned.sort((a, b) => a.top - b.top) + const above: string[] = [] + const below: string[] = [] + for (const item of positioned) { + if (item.bottom <= options.bounds.top) above.push(item.id) + else if (item.top >= options.bounds.bottom) below.push(item.id) + } + return { above, below } +} + export function filterSessionsForListStatus( sessions: SessionSummary[], status: SessionListView['status'], @@ -889,12 +1296,33 @@ function ChevronIcon(props: { className?: string; collapsed?: boolean }) { strokeLinecap="round" strokeLinejoin="round" className={`${props.className ?? ''} transition-transform duration-200 ${props.collapsed ? '' : 'rotate-90'}`} + aria-hidden="true" > ) } +function FolderIcon(props: { className?: string }) { + return ( + + ) +} + function SessionPreviewArrowIcon(props: { direction: 'up' | 'down'; className?: string }) { return ( void) | null>(null) +/** + * Lets a row declare that its dismissal dialog is open. + * + * `CollapsiblePanelHoldContext` does NOT cover this: it gates whether a panel's + * children render while the panel collapses, but a row removed from + * `blockedSectionSessions` by a filter is not among those children at all, so + * there is nothing for the hold to keep alive. The jump exemption has to be + * withheld explicitly instead. + */ +const BlockedDialogHoldContext = createContext<((sessionId: string | null) => void) | null>(null) + +/** + * Opening the Mark-unblocked dialog hands its target UP to `SessionList` + * rather than rendering it on the row (#1717). + * + * The row is not a stable place for it: a reply from another client clears the + * blocker, the row moves out of the Blocked section on the next session + * update, React unmounts it — and the dialog goes with it, discarding a reason + * the operator was part-way through typing. `SessionList` outlives any row + * movement, so the dialog and the draft inside it survive. + */ +export type UnblockDialogTarget = { + sessionId: string + title: string + at: number + key: string + label: string | null + note: string | null +} +const UnblockDialogRequestContext = createContext<((target: UnblockDialogTarget) => void) | null>(null) +/** Which row, if any, currently has the dismissal dialog open against it. */ +const BlockedDialogOpenContext = createContext(null) const CollapsiblePanelOpenContext = createContext(true) type QuickUnpinFocusTarget = { sessionId: string; pending: boolean } @@ -1430,16 +1897,98 @@ type SessionItemProps = { targetMessageId?: string targetMessageQuery?: string lastSeenVersion: number + /** Brief ring after jump-to-next-blocked, so the row the list travelled to + * is obvious once the scroll settles. */ + flashHighlight?: boolean /** Stopped rows show the stop time they are ordered by (Active first). */ showStoppedTime?: boolean + /** Leader of a session group: its members, folded under this row. */ + groupSummary?: SessionGroupRowSummary + /** Every member of the group this row leads, for the dissolve action. */ + groupMembers?: readonly SessionSummary[] + onToggleGroup?: (leaderId: string, open: boolean) => void +} + +/** + * The folded member list a leader row reports on its second line. `open` is + * null when no member is nested here (all pinned elsewhere or filtered out). + */ +type SessionGroupRowSummary = { + memberCount: number + waiting: number + working: number + unread: number + open: boolean | null } -function shallowEqualExcept(previous: T, next: T, ignored: keyof T): boolean { +function shallowEqualExcept(previous: T, next: T, ...ignored: Array): boolean { if (previous === next) return true const keys = Object.keys(previous) as Array return keys.length === Object.keys(next).length && keys.every(key => Object.hasOwn(next, key) - && (key === ignored || Object.is(previous[key], next[key]))) + && (ignored.includes(key) || Object.is(previous[key], next[key]))) +} + +function sameGroupSummary(previous?: SessionGroupRowSummary, next?: SessionGroupRowSummary): boolean { + if (!previous || !next) return previous === next + return shallowEqualExcept(previous, next) +} + +/** + * A group leader's second line: how many members are folded under it and what + * they are doing. A sibling of the row button (not nested inside it), aligned + * with the title column, so it toggles the member list on its own. + */ +function GroupSummaryLine(props: { + leaderId: string + summary: SessionGroupRowSummary + onToggle?: (leaderId: string, open: boolean) => void +}) { + const { t } = useTranslation() + const { leaderId, summary, onToggle } = props + const countLabel = summary.memberCount === 1 + ? t('sessions.members.countOne') + : t('sessions.members.count', { n: summary.memberCount }) + const content = ( + <> + {countLabel} + {summary.waiting > 0 ? ( + + · {t('sessions.members.waiting', { n: summary.waiting })} + + ) : null} + {summary.working > 0 ? ( + + · {t('sessions.members.working', { n: summary.working })} + + ) : null} + {summary.unread > 0 ? ( + + · {t('sessions.members.unread', { n: summary.unread })} + + ) : null} + + ) + // Indented past the agent icon (row padding + icon + gap) to the title column. + return ( +
+ {summary.open === null ? ( + + {content} + + ) : ( + + )} +
+ ) } const SessionItem = memo(function SessionItem(props: SessionItemProps) { @@ -1463,7 +2012,11 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { targetMessageId, targetMessageQuery, lastSeenVersion, - showStoppedTime = false + flashHighlight = false, + showStoppedTime = false, + groupSummary, + groupMembers, + onToggleGroup } = props const { haptic } = usePlatform() const [menuOpen, setMenuOpen] = useState(false) @@ -1472,6 +2025,7 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { const [linkPrOpen, setLinkPrOpen] = useState(false) const [exportOpen, setExportOpen] = useState(false) const [archiveOpen, setArchiveOpen] = useState(false) + const [dissolveOpen, setDissolveOpen] = useState(false) const githubPrAwarenessEnabled = Boolean(features?.githubPrAwareness.enabled) const prChipDisplay = features?.prChipDisplay const forkFlow = useForkFlow({ @@ -1485,6 +2039,11 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { const rowButtonRef = useRef(null) const quickUnpinFocusRef = useContext(QuickUnpinFocusContext) const panelOpen = useContext(CollapsiblePanelOpenContext) + const requestUnblockDialog = useContext(UnblockDialogRequestContext) + // The dialog itself lives in `SessionList` so it outlives this row moving + // between sections; the row only reports whether one is open against it, + // which `overlayOpen` below needs. + const unblockOpen = useContext(BlockedDialogOpenContext) === s.id const { status: cursorChatStoreStatus, isApplicable: cursorChatStoreApplicable, @@ -1510,14 +2069,17 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { ? t('session.action.reopenCursorUnverified') : undefined - const { archiveSession, reopenSession, renameSession, upsertExternalRef, removePrimaryExternalRef, suggestSessionTitle, updateSessionSummary, setPinMode, isPending } = useSessionActions( + const { archiveSession, reopenSession, renameSession, upsertExternalRef, removePrimaryExternalRef, suggestSessionTitle, updateSessionSummary, setPinMode, acknowledgeBlocked, isPending } = useSessionActions( api, s.id, s.metadata?.flavor ?? null ) const [reopenError, setReopenError] = useState(null) const holdPanel = useContext(CollapsiblePanelHoldContext) - const overlayOpen = menuOpen || renameOpen || linkPrOpen || exportOpen || archiveOpen || forkFlowOpen || reopenError !== null + // `unblockOpen` belongs here with the other dialogs: without it, a row + // revealed by the jump exemption unmounted two seconds later and took the + // open Mark-unblocked dialog with it, mid-entry. + const overlayOpen = menuOpen || renameOpen || linkPrOpen || exportOpen || archiveOpen || dissolveOpen || forkFlowOpen || unblockOpen || reopenError !== null useEffect(() => { if (!overlayOpen || !holdPanel) return holdPanel(true) @@ -1695,6 +2257,10 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { onSelect(s.id, undefined, undefined, pendingRequestId) } const sessionName = getSessionTitle(s) + // Read only while the menu is open: it consults the unconfirmed-archive store. + const canDissolveGroup = menuOpen && api && groupMembers && groupMembers.length > 0 + ? getGroupDissolveTargets(s, groupMembers, api.getReadStateScope?.() ?? null).live.length > 0 + : false const primaryPrRef = getPrimaryGithubPrRef(s.metadata?.externalRefs) const linkedPr = useMemo(() => { if (!githubPrAwarenessEnabled || !primaryPrRef) return null @@ -1717,6 +2283,32 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { : null, [s, selected, showDetailedStatus, lastSeenVersion] ) + // The rail lives on the button rather than inside SessionRowSummary so it + // escapes the `opacity-50` disconnected-row treatment — a blocked agent + // whose CLI dropped is precisely the one worth spotting. + // Re-evaluated on a timer, not only when props change (#1717). Age is + // computed at render, and a memoized row on an open list has no update + // scheduled when its blocker crosses the 24h staleness deadline — so an + // abandoned row kept its loud warning styling until something unrelated + // happened to re-render it. The rail and the chip both read this one + // value, so they cannot disagree about it. + const [staleTick, setStaleTick] = useState(0) + const blocked = useMemo( + () => getSessionBlockedState(s, { now: Date.now() }), + [s, staleTick] // eslint-disable-line react-hooks/exhaustive-deps + ) + const blockedAt = blocked?.at ?? null + const blockedStale = blocked?.stale ?? false + useEffect(() => { + if (blockedAt === null || blockedStale) return + const due = blockedAt + BLOCKED_NOTIFY_STALE_MS - Date.now() + if (due <= 0) { + setStaleTick((tick) => tick + 1) + return + } + const timer = setTimeout(() => setStaleTick((tick) => tick + 1), due + 1) + return () => clearTimeout(timer) + }, [blockedAt, blockedStale]) const hasScheduleTooltip = showDetailedStatus && s.futureScheduledMessageCount > 0 const { attentionId, scheduleId, describedBy } = useSessionRowTooltipIds( Boolean(attention), @@ -1726,7 +2318,7 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { <>
0 ? quickActionCount : undefined} data-quick-action-pending={quickArchivePending || quickUnpinPending ? '' : undefined} @@ -1741,7 +2333,27 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { && event.target.closest('[data-session-pending-request-id]') !== null }} data-session-scroll-anchor - className="session-list-item group/session-row flex min-w-0 flex-1 flex-col gap-1 py-2 pl-2.5 pr-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--app-link)] select-none rounded-lg" + data-session-id={s.id} + data-session-blocked={blocked ? (blocked.stale ? 'stale' : 'active') : undefined} + className={cn( + // Upstream layout classes kept verbatim; pl-2.5 becomes pl-2 + // because the blocked rail below adds the missing 2px. + // Selection highlight now lives in CSS, keyed off + // aria-current on this element (upstream), so no inline + // selected/bg class or duplicate transition-colors here. + 'session-list-item group/session-row flex min-w-0 flex-1 flex-col gap-1 py-2 pl-2 pr-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--app-link)] select-none rounded-lg', + // Reserve the rail width on every row so blocked rows do + // not shift their neighbours when the flag appears. + 'border-l-2', + blocked && blocked.stale + ? 'border-[var(--app-hint)]' + : blocked && sessionBlockedIsError(blocked) + ? 'border-[var(--app-badge-error-text)]' + : blocked + ? 'border-[var(--app-badge-warning-text)]' + : 'border-transparent', + flashHighlight ? 'ring-2 ring-[var(--app-badge-warning-text)]' : '' + )} style={{ WebkitTouchCallout: 'none' }} aria-current={selected ? 'page' : undefined} aria-describedby={describedBy} @@ -1816,6 +2428,13 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { ) : null}
) : null} + {groupSummary ? ( + + ) : null}
forkFlow.openFork() : undefined} forkDisabledReason={forkDisabledReason} + onMarkUnblocked={blocked + ? () => { + // Freeze identity AND copy together. Freezing only the + // timestamp let the dialog keep rendering a newer + // footer while confirming against the older one, so + // the operator read one blocker and dismissed another. + requestUnblockDialog?.({ + sessionId: s.id, + title: sessionName, + at: blocked.at, + key: blocked.key, + label: t(getSessionBlockedLabelKey(blocked)), + note: blocked.note ?? null + }) + } + : undefined} onArchive={() => setArchiveOpen(true)} + onDissolveGroup={canDissolveGroup ? () => setDissolveOpen(true) : undefined} onReopen={cursorReopenDisabledReason ? undefined : () => void handleReopen()} reopenDisabledReason={cursorReopenDisabledReason} reopenHint={cursorReopenUnverifiedHint} @@ -1949,10 +2585,21 @@ const SessionItem = memo(function SessionItem(props: SessionItemProps) { /> ) : null} + {dissolveOpen && groupMembers ? ( + setDissolveOpen(false)} + /> + ) : null} + ) }, (previous, next) => - shallowEqualExcept(previous, next, 'session') + shallowEqualExcept(previous, next, 'session', 'groupSummary') + && sameGroupSummary(previous.groupSummary, next.groupSummary) // The watermark orders REST and SSE updates in the cache. The row renders the job value. && shallowEqualExcept(previous.session, next.session, 'attachedJobUpdatedAt') ) @@ -2044,6 +2691,15 @@ export function SessionList(props: { const { sessionListStatusMode } = useSessionListStatusMode() const { view: listView, setView: setListView } = useSessionListView() const listComparator = useMemo(() => createSessionComparator(listView), [listView]) + // Pinned and Blocked pull sessions out of the regular active/stopped flow + // for an operator-attention reason — a session disconnecting there must + // not reorder it ahead of one the operator engaged with more recently, + // which `listComparator`'s stopped-recency grouping (upstream main #2518) + // would otherwise do purely because disconnecting bumps `updatedAt`. + const attentionSectionComparator = useMemo( + () => createSessionComparator(listView, { groupStoppedByRecency: false }), + [listView] + ) const lastSeenVersion = useSessionLastSeenVersion() // Date, scratchlist, active, and working are transient; unread uses the @@ -2069,9 +2725,76 @@ export function SessionList(props: { const { keepUnreadSessionsVisible } = useKeepUnreadSessionsVisible() // Unread rows may bypass the preview cap, never their parent folder. const previewIsUnread = keepUnreadSessionsVisible ? isSessionUnread : undefined + // Blocked lens + travel state (#1717). Transient for the same reason. + const [showBlockedOnly, setShowBlockedOnly] = useState(false) + const [blockedSectionCollapsed, setBlockedSectionCollapsed] = useState(false) + const [pendingBlockedScrollId, setPendingBlockedScrollId] = useState(null) + /** One row exempted from the saved status / machine / date filters so the + * jump can reach it without rewriting the operator's preferences. */ + const [revealBlockedSessionId, setRevealBlockedSessionId] = useState(null) + /** Set while a row's dismissal dialog is open, so the exemption above is + * not withdrawn mid-entry and take the dialog and its draft with it. */ + const [blockedDialogSessionId, setBlockedDialogSessionId] = useState(null) + // The dismissal dialog's target lives here, not on the row: a reply from + // another client can move the row to a different section mid-typing, and + // React would unmount the row — and the half-written reason with it. + const [unblockTarget, setUnblockTarget] = useState(null) + const requestUnblockDialog = useCallback((target: UnblockDialogTarget) => { + setUnblockTarget(target) + setBlockedDialogSessionId(target.sessionId) + }, []) + // Compared by identity so a LATE success from a dialog the operator has + // already dismissed cannot close the one they opened next (#1717). The + // first request's handler still holds this callback after its host + // unmounted, and without the token it cleared the new target and + // discarded a second half-written reason. + const unblockTargetRef = useRef(null) + unblockTargetRef.current = unblockTarget + const closeUnblockDialog = useCallback((token?: UnblockDialogTarget) => { + if (token !== undefined && unblockTargetRef.current !== token) return + setUnblockTarget(null) + setBlockedDialogSessionId(null) + }, []) + + const holdBlockedDialog = useCallback( + (sessionId: string | null) => setBlockedDialogSessionId(sessionId), + [] + ) + const [flashBlockedSessionId, setFlashBlockedSessionId] = useState(null) + // Non-null for the window between the flash ending and focus actually + // leaving the revealed row (#1717 cold-review round 27) — driven by its + // OWN effect below, independent of `flashBlockedSessionId`'s lifecycle, + // so tearing down THAT effect (triggered by the very transition that + // starts this hold) does not also tear down the listener that is + // supposed to outlive it. + const [focusHoldSessionId, setFocusHoldSessionId] = useState(null) + // Read synchronously by the effect that releases the exemption on OTHER + // triggers (dialog close, etc.) — state alone cannot do this because + // `setFocusHoldSessionId` and `setFlashBlockedSessionId` land on the + // SAME render, and that effect must see the hold already in place. + const focusHeldAfterFlashRef = useRef(false) + const [blockedOffscreen, setBlockedOffscreen] = useState<{ above: number; below: number }>( + { above: 0, below: 0 } + ) + const blockedJumpCursorRef = useRef(0) + // Targets already visited in the current jump cycle (#1717 cold-review + // round 21): a one-way arrow otherwise re-picks the same off-screen row + // forever, so a blocker hidden behind a filter — never in `above`/`below` + // — is never reached. + const blockedJumpVisitedRef = useRef>(new Set()) + // Whether the jump currently in flight was activated by keyboard + // (#1717 cold-review round 26) — read once the target row mounts, so + // the scroll effect below knows whether to also move focus there. A + // mouse click already leaves focus exactly where the operator put it + // (the pill); only a keyboard activation needs the destination row to + // become the new focus, or Tab continues from the pill through + // intervening toolbar and list controls instead of landing on the + // blocker just jumped to. + const blockedJumpViaKeyboardRef = useRef(false) const { pinInProgressMode } = usePinInProgressSessions() // List sort/filter lives in SessionListView (#2263); jobs mode is #1404. const effectivePinInProgressMode: PinInProgressMode = pinInProgressMode + const { blockedAlertMode } = useBlockedAlertMode() const { machineFilter, setMachineFilter } = useSessionListMachineFilter() const showDetailedStatus = sessionListStatusMode === 'detailed' const [searchQuery, setSearchQuery] = useState('') @@ -2093,7 +2816,8 @@ export function SessionList(props: { const actionsObserverRef = useRef(null) const [headerRowWidth, setHeaderRowWidth] = useState(0) const [toolbarSlotWidths, setToolbarSlotWidths] = useState>({}) - const [toolbarChrome, setToolbarChrome] = useState({ morePx: TOOLBAR_MORE_PX, gapPx: TOOLBAR_GAP_PX }) + const [toolbarChrome, setToolbarChrome] = useState({ morePx: TOOLBAR_MORE_PX, gapPx: TOOLBAR_GAP_PX, blockedPx: 0 }) + const blockedControlsRef = useRef(null) const [searchChromePx, setSearchChromePx] = useState(0) const [searchMaxPx, setSearchMaxPx] = useState(0) // jsdom reports clientWidth 0; the row observer publishes the stubbed width. @@ -2231,7 +2955,7 @@ export function SessionList(props: { const normalizedQuery = normalizeSearch(searchQuery) const timeRange = getSessionTimeRange(customStart, customEnd) const isSearchFiltering = normalizedQuery.length > 0 || timeRange !== null - const ephemeralFilter = isSearchFiltering || showScratchlistOnly || showActiveOnly || showWorkingOnly + const ephemeralFilter = isSearchFiltering || showScratchlistOnly || showActiveOnly || showWorkingOnly || showBlockedOnly const isFiltering = ephemeralFilter || listView.unreadOnly const contentSearchActive = searchMode === 'content' && normalizedQuery.length > 0 @@ -2253,6 +2977,10 @@ export function SessionList(props: { return t('machine.unknown') } + // Split so the blocked count can be taken BEFORE status/unread narrowing: + // a blocked agent whose CLI disconnected is exactly the one worth + // surfacing, and it is not "active" — `sidebarSessions` stays the + // pre-narrowed base those fleet-wide counts read from. const sidebarSessions = useMemo( () => prepareSidebarSessions(props.sessions, selectedSessionId), [props.sessions, selectedSessionId] @@ -2264,9 +2992,35 @@ export function SessionList(props: { // Keep status filtering separate from the unread lens. Machine choices are // derived from this set, so selecting a machine with no unread matches must // stay an empty intersection instead of falling back to another machine. + // The jump target is exempted exactly where the selected session already + // is, so revealing one row needs no change to saved preferences. + const filterExemptId = revealBlockedSessionId ?? selectedSessionId + // Release a held exemption once nothing is using it — in practice, after an + // unblock dialog opened on the revealed row is closed. + // + // `flashBlockedSessionId === null` cannot carry that decision on its own: + // it reads the same before the flash starts as after it ends. This effect + // ran on the render right after the pill set the exemption and revoked it + // immediately, so the jump target was filtered back out before the scroll + // effect below could ever find it — the jump did nothing at all. + // `pendingBlockedScrollId` is what distinguishes the two: it is non-null + // for exactly the in-flight window between the two. + useEffect(() => { + if (blockedDialogSessionId !== null) return + if (revealBlockedSessionId === null) return + if (pendingBlockedScrollId !== null) return + if (flashBlockedSessionId !== null) return + // A keyboard-focused control can still be inside the row the flash + // just stopped highlighting (#1717 cold-review round 27) — the + // focus-hold effect below owns releasing the exemption once focus + // actually leaves it; releasing here too would unmount the row + // regardless of where focus still is. + if (focusHeldAfterFlashRef.current) return + setRevealBlockedSessionId(null) + }, [blockedDialogSessionId, revealBlockedSessionId, flashBlockedSessionId, pendingBlockedScrollId]) const allSessions = useMemo( - () => filterSessionsForListStatus(sidebarSessions, listView.status, selectedSessionId), - [sidebarSessions, selectedSessionId, listView.status] + () => filterSessionsForListStatus(sidebarSessions, listView.status, filterExemptId), + [sidebarSessions, filterExemptId, listView.status] ) const unreadSessionCount = useMemo( () => getUnreadSessionCount(readableSessions), @@ -2280,8 +3034,8 @@ export function SessionList(props: { const timeScopedSessions = useMemo( () => timeRange === null ? allSessions - : allSessions.filter(session => sessionMatchesTimeRange(session, timeRange, selectedSessionId)), - [allSessions, selectedSessionId, timeRange?.start, timeRange?.end] // eslint-disable-line react-hooks/exhaustive-deps + : allSessions.filter(session => sessionMatchesTimeRange(session, timeRange, filterExemptId)), + [allSessions, filterExemptId, timeRange?.start, timeRange?.end] // eslint-disable-line react-hooks/exhaustive-deps ) const searchScoreIndex = useMemo( () => searchMatchMode === 'default' && hasTextQuery @@ -2289,16 +3043,29 @@ export function SessionList(props: { : null, [hasTextQuery, searchMatchMode, timeScopedSessions, normalizedQuery, machineLabelsById] // eslint-disable-line react-hooks/exhaustive-deps ) + // A content-search result's own `session` snapshot is only as fresh as + // the request that returned it. Dismissing a blocker while the query + // stays open and the candidate id set is unchanged no longer forces a + // refetch (#1717 cold-review round 37) — the stable-ids fix above means + // a search hit's snippet/nav target now outlives a live field like + // dismissal, so render each hit against the current session by id + // rather than the frozen one the search response carried. + const sessionsById = useMemo( + () => new Map(props.sessions.map(session => [session.id, session])), + [props.sessions] + ) const visibleSessions = useMemo( () => { if (contentSearchActive) { - const results = contentSearchResponse?.results.map((result) => result.session) ?? [] - const prepared = prepareSidebarSessions(results, selectedSessionId) - const byStatus = filterSessionsForListStatus(prepared, listView.status, selectedSessionId) + const results = (contentSearchResponse?.results ?? []).map( + (result) => sessionsById.get(result.session.id) ?? result.session + ) + const prepared = prepareSidebarSessions(results, filterExemptId) + const byStatus = filterSessionsForListStatus(prepared, listView.status, filterExemptId) const unreadFiltered = listView.unreadOnly - ? filterUnreadSessionsOnly(byStatus, isSessionUnread, selectedSessionId) + ? filterUnreadSessionsOnly(byStatus, isSessionUnread, filterExemptId) : byStatus - return unreadFiltered.filter(session => sessionMatchesTimeRange(session, timeRange, selectedSessionId)) + return unreadFiltered.filter(session => sessionMatchesTimeRange(session, timeRange, filterExemptId)) } if (!isFiltering) return allSessions const matched = searchMatchMode === 'exclude' @@ -2320,7 +3087,7 @@ export function SessionList(props: { } return matched }, - [allSessions, contentSearchActive, contentSearchResponse, hasTextQuery, isFiltering, normalizedQuery, searchMatchMode, searchScoreIndex, selectedSessionId, listView.status, listView.unreadOnly, isSessionUnread, machineLabelsById, timeScopedSessions, timeRange?.start, timeRange?.end] // eslint-disable-line react-hooks/exhaustive-deps + [allSessions, contentSearchActive, contentSearchResponse, sessionsById, hasTextQuery, isFiltering, normalizedQuery, searchMatchMode, searchScoreIndex, filterExemptId, listView.status, listView.unreadOnly, isSessionUnread, machineLabelsById, timeScopedSessions, timeRange?.start, timeRange?.end] // eslint-disable-line react-hooks/exhaustive-deps ) const contentSnippetBySessionId = useMemo(() => { const snippets = new Map() @@ -2397,23 +3164,34 @@ export function SessionList(props: { : null const contentSearchCandidateSessions = useMemo(() => { - let filtered = allSessions.filter(session => sessionMatchesTimeRange(session, timeRange, selectedSessionId)) + let filtered = allSessions.filter(session => sessionMatchesTimeRange(session, timeRange, filterExemptId)) if (listView.unreadOnly) { filtered = filterUnreadSessionsOnly( filtered, isSessionUnread, - selectedSessionId + filterExemptId ) } if (showActiveOnly) { - filtered = filterActiveSessionsOnly(filtered, selectedSessionId) + filtered = filterActiveSessionsOnly(filtered, filterExemptId) } if (showWorkingOnly) { - filtered = filterWorkingSessionsOnly(filtered, selectedSessionId) + filtered = filterWorkingSessionsOnly(filtered, filterExemptId) } if (showScratchlistOnly) { if (isScratchlistStatusLoading || scratchlistStatusError) return [] - filtered = filterScratchlistSessionsOnly(filtered, selectedSessionId, scratchlistSessionIds) + filtered = filterScratchlistSessionsOnly(filtered, filterExemptId, scratchlistSessionIds) + } + // The blocked lens has to narrow the candidate ids too, not just the + // rendered rows. `searchMessageContent` keeps only the 100 most + // recently updated matching sessions, so submitting unblocked + // candidates lets them consume the budget and drop an older blocked + // match the lens is specifically asking for. + if (showBlockedOnly) { + const now = Date.now() + filtered = filtered.filter(session => + session.id === filterExemptId || sessionIsBlocked(session, { now }) + ) } return activeMachineFilter === null ? filtered @@ -2427,19 +3205,57 @@ export function SessionList(props: { lastSeenVersion, scratchlistSessionIds, scratchlistStatusError, - selectedSessionId, + filterExemptId, showScratchlistOnly, showActiveOnly, showWorkingOnly, + showBlockedOnly, listView.unreadOnly, timeRange?.start, timeRange?.end ]) - const contentSearchSessionIds = useMemo( - () => contentSearchCandidateSessions.map(session => session.id), - [contentSearchCandidateSessions] - ) + // Not a plain `useMemo`: `contentSearchCandidateSessions` is a NEW array + // (with new session object references for any patched session) on + // every SSE patch, including a revision-only keepalive that changes + // nothing visible — `isRenderIrrelevantPatch` treats a bare + // `thinkingRevision` bump as render-relevant on purpose (#1717 cold- + // review rounds 22/28/30), so this recomputes on every such tick too. + // A `useMemo` keyed on that array's REFERENCE would then return a new + // ids array every tick even when the ACTUAL ids are identical, and the + // search effect below — keyed on this array by reference — would + // abort and restart the same search on every keepalive while it was + // open (#1717 cold-review round 36). Comparing against the previous + // VALUE and reusing that array when nothing actually changed is what + // keeps the effect's own dependency stable across a revision-only tick. + const contentSearchSessionIdsRef = useRef([]) + const contentSearchSessionIds = useMemo(() => { + const next = contentSearchCandidateSessions.map(session => session.id) + const previous = contentSearchSessionIdsRef.current + const unchanged = next.length === previous.length + && next.every((id, index) => id === previous[index]) + if (unchanged) return previous + contentSearchSessionIdsRef.current = next + return next + }, [contentSearchCandidateSessions]) + + // The id-stability fix above deliberately drops a refetch when + // membership is unchanged, but a NEW matching message inside an + // existing candidate's transcript doesn't change membership either. + // `contentRevision` only advances for eligible AGENT output — by + // design, for the unread badge this field actually exists for — so a + // new OPERATOR prompt, also indexed by content search, needs a + // separate signal: `lastUserMessageAt` is the hub's own monotonic + // watermark for exactly that, already carried on every SessionSummary + // (#1717 cold-review round 37). A rewind that deletes an indexed + // message has no equivalent signal on the summary today and is + // tracked separately (tiann/hapi#2708) rather than folded in here. A + // plain string of these two per candidate compares by VALUE in the + // effect's dependency array below, so it only forces a refetch when + // one of them actually changed. + const contentSearchRevisionSignature = contentSearchCandidateSessions + .map(session => `${session.id}:${session.contentRevision ?? 0}:${session.lastUserMessageAt ?? 0}`) + .join(',') useEffect(() => { if (!contentSearchReady || !api) { @@ -2487,7 +3303,7 @@ export function SessionList(props: { window.clearTimeout(timer) controller.abort() } - }, [api, contentSearchReady, contentSearchSessionIds, normalizedQuery]) + }, [api, contentSearchReady, contentSearchSessionIds, contentSearchRevisionSignature, normalizedQuery]) // Apply the session lens after search/time and before machine scope — so @@ -2496,15 +3312,15 @@ export function SessionList(props: { // machine selection. const sessionFilteredSessions = useMemo(() => { let filtered = listView.unreadOnly - ? filterUnreadSessionsOnly(visibleSessions, isSessionUnread, selectedSessionId) + ? filterUnreadSessionsOnly(visibleSessions, isSessionUnread, filterExemptId) : visibleSessions // Active and Working are AND-composed with the other lenses (#2002). // These temporary filters leave the saved Show choice intact. if (showActiveOnly) { - filtered = filterActiveSessionsOnly(filtered, selectedSessionId) + filtered = filterActiveSessionsOnly(filtered, filterExemptId) } if (showWorkingOnly) { - filtered = filterWorkingSessionsOnly(filtered, selectedSessionId) + filtered = filterWorkingSessionsOnly(filtered, filterExemptId) } if (showScratchlistOnly) { if (isScratchlistStatusLoading || scratchlistStatusError) { @@ -2512,31 +3328,59 @@ export function SessionList(props: { } filtered = filterScratchlistSessionsOnly( filtered, - selectedSessionId, + filterExemptId, scratchlistSessionIds ) } - return filtered + // Blocked lens. Sits alongside the native unread-only view filter + // rather than inside it: "you have not looked at this" and "it stopped + // and needs you" are different questions, and a blocked session you + // already read is still blocked. + if (showBlockedOnly) { + const now = Date.now() + filtered = filtered.filter(session => + session.id === filterExemptId || sessionIsBlocked(session, { now }) + ) + } + // `filterExemptId` is `revealBlockedSessionId ?? selectedSessionId` + // — see `restoreSelectedSessionExemption`'s own doc comment for why + // the two are not interchangeable. Restoring from `sidebarSessions`, + // not `visibleSessions`: the saved "Active sessions only" status + // filter (`listView.status`) already ran against the CURRENT + // `filterExemptId` upstream of `visibleSessions`, so a jump that + // just replaced the selected session's exemption can have already + // erased it from `visibleSessions` too, with nothing left there to + // restore (#1717 cold-review round 29). + return restoreSelectedSessionExemption(filtered, sidebarSessions, selectedSessionId, filterExemptId) }, [ + showBlockedOnly, isScratchlistStatusLoading, lastSeenVersion, scratchlistSessionIds, scratchlistStatusError, + filterExemptId, selectedSessionId, showScratchlistOnly, showActiveOnly, showWorkingOnly, listView.unreadOnly, - visibleSessions + visibleSessions, + sidebarSessions ]) const machineFilteredSessions = useMemo( () => activeMachineFilter === null ? sessionFilteredSessions : sessionFilteredSessions.filter(session => - (session.metadata?.machineId ?? UNKNOWN_MACHINE_ID) === activeMachineFilter + // `revealBlockedSessionId`, NOT `filterExemptId`. The latter + // falls back to the selected session, which widened the base + // machine filter: with a machine-A session open, switching the + // list to machine B left A's row on screen with no jump + // involved. Only an in-flight jump may cross machines, and + // only for as long as it holds its exemption. + session.id === revealBlockedSessionId + || (session.metadata?.machineId ?? UNKNOWN_MACHINE_ID) === activeMachineFilter ), - [sessionFilteredSessions, activeMachineFilter] - + [sessionFilteredSessions, activeMachineFilter, revealBlockedSessionId] ) // Members of a session group render under their leader, so every section // below works with leaders and ungrouped sessions only. @@ -2580,8 +3424,56 @@ export function SessionList(props: { if (rowSearchScoreIndex && hasTextQuery) { return sortSessionsBySearchRelevance(pinned, rowSearchScoreIndex) } - return [...pinned].sort(listComparator) - }, [topLevelSessions, rowSearchScoreIndex, hasTextQuery, listComparator]) + return [...pinned].sort(attentionSectionComparator) + }, [topLevelSessions, rowSearchScoreIndex, hasTextQuery, attentionSectionComparator]) + // Fleet-wide count, deliberately computed BEFORE search / time / unread / + // machine narrowing: the pill exists to tell the operator how much blocked + // work exists, and a count that silently shrank behind a filter would be + // worse than no count at all. `jumpToNextBlocked` drops those filters when + // it has to reach one of these rows. + const blockedSessions = useMemo(() => { + const now = Date.now() + return sidebarSessions + .filter(session => sessionIsBlocked(session, { now })) + .sort((a, b) => b.updatedAt - a.updatedAt) + }, [sidebarSessions]) + const blockedCount = blockedSessions.length + const blockedAlerting = useBlockedArrivalAlert( + useMemo(() => blockedSessions.map(session => session.id), [blockedSessions]), + blockedAlertMode, + props.sessions.length > 0 + ) + + // Rows for the pinned Blocked section. Globally pinned rows keep their own + // section (the operator put them there on purpose) and still carry the + // rail + chip where they sit. + const blockedSectionSessions = useMemo(() => { + const now = Date.now() + const blocked = machineFilteredSessions + .filter(session => !session.globalPinned && sessionIsBlocked(session, { now })) + // Same ordering rule as the global-pinned section. A bare `updatedAt` + // sort discarded the search ranking the matches had already been + // given, so a recently touched path-only match outranked an older + // exact title match — and outside search it silently overrode the + // operator's configured list order too. + if (searchScoreIndex && hasTextQuery) { + return sortSessionsBySearchRelevance(blocked, searchScoreIndex) + } + return [...blocked].sort(attentionSectionComparator) + }, [machineFilteredSessions, searchScoreIndex, hasTextQuery, attentionSectionComparator]) + // Globally pinned blockers stay in Pinned rather than moving to Blocked, + // so their collapsed rows are attributed to THAT header (#1717). + const pinnedBlockedIds = useMemo(() => { + const now = Date.now() + return globalPinnedSessions + .filter((session) => sessionIsBlocked(session, { now })) + .map((session) => session.id) + }, [globalPinnedSessions]) + const blockedSectionIds = useMemo( + () => new Set(blockedSectionSessions.map(session => session.id)), + [blockedSectionSessions] + ) + const runningSessions = useMemo(() => { const byRelevanceOrRecent = (a: SessionSummary, b: SessionSummary) => { if (rowSearchScoreIndex && hasTextQuery) { @@ -2589,8 +3481,15 @@ export function SessionList(props: { } return listComparator(a, b) } - return bucketRunningGroups(topLevelSessions, groupMembersByLeader, effectivePinInProgressMode, byRelevanceOrRecent, api?.hubClock?.now()) - }, [api, listClockTick, topLevelSessions, groupMembersByLeader, effectivePinInProgressMode, rowSearchScoreIndex, hasTextQuery, listComparator]) + // Floated into the Blocked section instead. Without this a blocked + // but still-connected agent renders twice — and worse, the quiet + // grey "Active" bucket is exactly where it used to hide. A blocked + // leader is excluded here the same way; a blocked group MEMBER never + // needs the same treatment, since `bucketRunningGroups` only ever + // pushes the leader into a bucket, never a member directly. + const candidates = topLevelSessions.filter(session => !blockedSectionIds.has(session.id)) + return bucketRunningGroups(candidates, groupMembersByLeader, effectivePinInProgressMode, byRelevanceOrRecent, api?.hubClock?.now()) + }, [api, listClockTick, topLevelSessions, groupMembersByLeader, blockedSectionIds, effectivePinInProgressMode, rowSearchScoreIndex, hasTextQuery, listComparator]) // Stopped rows show their stop time only where the list orders them by it: // Active first, and no text query (which orders rows by relevance or, for // project rows in either search mode, by the legacy comparator). @@ -2602,7 +3501,20 @@ export function SessionList(props: { () => { const inProgressIds = new Set(Object.values(runningSessions).flat().map(session => session.id)) const grouped = groupSessionsByDirectory( - topLevelSessions.filter(session => !session.globalPinned && !inProgressIds.has(session.id)), + // `inProgressIds` already reflects every exclusion + // `bucketRunningGroups` itself applies (pinned, + // globalPinned, `effectivePinInProgressMode`) — re-deriving + // those here would duplicate that logic and risk drifting + // from it. Blocked sessions are excluded separately: they + // never enter `runningSessions` at all (floated to the + // Blocked section instead), so they are never in + // `inProgressIds` either, and would otherwise fall through + // into this catch-all group and render twice. + topLevelSessions.filter(session => ( + !session.globalPinned + && !inProgressIds.has(session.id) + && !blockedSectionIds.has(session.id) + )), // Search keeps its own contract: relevance first, then the stable // last-message order for ties, whatever the list view says. hasTextQuery ? undefined : listView @@ -2612,7 +3524,7 @@ export function SessionList(props: { } return grouped }, - [runningSessions, topLevelSessions, rowSearchScoreIndex, hasTextQuery, listView] + [runningSessions, topLevelSessions, blockedSectionIds, rowSearchScoreIndex, hasTextQuery, listView] ) // Directory groups whose rows all floated to the pinned sections still // render an action-only header so copy-path / new-session-in-directory @@ -2634,12 +3546,27 @@ export function SessionList(props: { [props.sessions] ) const actionOnlyGroups = useMemo(() => { - if (effectivePinInProgressMode === 'off') { + // Under the blocked lens the operator asked for blocked rows and + // nothing else; every directory would otherwise contribute a bare + // action-only header, which is exactly the noise the lens removes. + if (showBlockedOnly) { + return [] + } + // Otherwise also needed when the Blocked section (not the in-progress + // pin) is what emptied a directory, or the project's copy-path / + // new-session actions would vanish with its last row. + if (effectivePinInProgressMode === 'off' && blockedSectionIds.size === 0) { return [] } const visibleKeys = new Set(groups.map((group) => group.key)) return allDirectoryGroups.filter((group) => !visibleKeys.has(group.key)) - }, [groups, allDirectoryGroups, effectivePinInProgressMode]) + }, [groups, allDirectoryGroups, effectivePinInProgressMode, blockedSectionIds, showBlockedOnly]) + // Disambiguate colliding project basenames on the same machine (`work/hapi` + // vs `oss/hapi`) while keeping unique basenames compact (`hapi`). + const projectGroupTitles = useMemo( + () => disambiguateProjectGroupTitles([...groups, ...actionOnlyGroups]), + [groups, actionOnlyGroups] + ) // Save explicit folds only, never temporary search expansion or inferred liveness. const identity = api?.getReadStateScope?.() const foldKey = identity ? `hapi.closed-projects.v1:${identity}` : null @@ -2651,6 +3578,13 @@ export function SessionList(props: { const [memberListOverrides, setMemberListOverrides] = useState>( () => new Map() ) + // Leader rows are memoized; hand them one stable toggle that reads the + // current fold state through a ref. + const toggleMemberListRef = useRef<(leaderId: string, isOpen: boolean) => void>(() => {}) + const onToggleGroup = useCallback( + (leaderId: string, isOpen: boolean) => toggleMemberListRef.current(leaderId, isOpen), + [] + ) // Folds made while filtering last only as long as the filter. const [filterMemberListOverrides, setFilterMemberListOverrides] = useState>( () => new Map() @@ -2813,7 +3747,7 @@ export function SessionList(props: { return (
- + - + {t(titleKey)} - - ({count}) + + {count}
-
+
{bucketKeys.map((bucketKey) => { const bucket = RUNNING_BUCKETS.find((b) => b.key === bucketKey) const sessions = runningSessions[bucketKey] @@ -2881,6 +3815,7 @@ export function SessionList(props: { targetMessageQuery={contentSearchActive ? normalizedQuery : undefined} lastSeenVersion={lastSeenVersion} showStoppedTime={stoppedTimeShown} + {...getGroupRowProps(s)} /> {renderGroupMembers(s)} @@ -2909,7 +3844,7 @@ export function SessionList(props: { event.stopPropagation() onNew() }} - className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-[var(--app-hint)] opacity-70 transition-colors hover:bg-[var(--app-secondary-bg)] hover:text-[var(--app-link)] hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--app-link)]" + className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[var(--app-hint)] opacity-0 transition-opacity duration-150 group-hover/project:opacity-100 focus-visible:opacity-100 hover:bg-[var(--app-secondary-bg)] hover:text-[var(--app-link)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--app-link)]" title={t('sessions.group.new')} aria-label={t('sessions.group.new')} > @@ -2919,25 +3854,38 @@ export function SessionList(props: { } const renderActionOnlyGroupHeader = (group: SessionGroup) => { - // With multiple machines in the unfiltered view, disambiguate - // same-named directories by suffixing the machine label. - const groupTitle = showMachineFilterBar && activeMachineFilter === null - ? `${group.displayName} · ${resolveMachineLabel(group.machineId)}` - : group.displayName + const projectTitle = projectGroupTitles.get(group.key) ?? group.displayName + // With multiple machines in the unfiltered view, display a muted + // machine label beside the project title. + const machineLabel = showMachineFilterBar && activeMachineFilter === null + ? resolveMachineLabel(group.machineId) + : null + const fullDisplayName = machineLabel ? `${projectTitle} · ${machineLabel}` : projectTitle return ( -
+
- - {groupTitle} - - + +
+ + {projectTitle} + + {machineLabel ? ( + <> + + + {machineLabel} + + + ) : null} +
+ {renderNewSessionInGroupButton(group)}
@@ -2970,6 +3918,34 @@ export function SessionList(props: { } setMemberListOverrides(prev => new Map(prev).set(leaderId, !isOpen)) } + toggleMemberListRef.current = toggleMemberList + + /** What a group leader's row shows about its members, and the whole group for dissolving it. */ + const getGroupRowProps = (leader: SessionSummary): Pick => { + // Same blocked-exclusion as renderGroupMembers (#2730): a blocked + // member floats into the Blocked section on its own, so it must not + // also inflate the leader's own count/waiting/working summary here. + // `allMembers` stays unfiltered — dissolving the group still needs + // to know about every member, blocked or not. + const members = (groupMembersByLeader.get(leader.id) ?? []) + .filter((member) => !blockedSectionIds.has(member.id)) + const allMembers = allGroupMembersByLeader.get(leader.id) ?? [] + if (members.length === 0) { + // Every member is pinned elsewhere, filtered out, or blocked and + // floated to its own section. The leader still leads a group, so + // the count and the group action stay. + return allMembers.length === 0 ? {} : { + groupSummary: { memberCount: allMembers.length, waiting: 0, working: 0, unread: 0, open: null }, + groupMembers: allMembers, + } + } + const status = summarizeGroupMembers(members, isSessionUnread, api?.hubClock?.now()) + return { + groupSummary: { memberCount: members.length, ...status, open: isMemberListOpen(leader.id, members) }, + groupMembers: allMembers, + onToggleGroup, + } + } const renderGroupSessionItem = (s: SessionSummary, labels?: { projectLabel?: string; machineLabel?: string }) => ( ) /** The members of a session group, folded under their leader's row. */ const renderGroupMembers = (leader: SessionSummary) => { - const members = groupMembersByLeader.get(leader.id) ?? [] - const allMembers = allGroupMembersByLeader.get(leader.id) ?? [] - const dissolveButton = ( - - ) - if (members.length === 0) { - // Every member is pinned elsewhere or filtered out. The leader - // still leads a group, so the group action stays reachable. - return allMembers.length === 0 ? null : ( -
-
- - {t('sessions.members.count', { n: allMembers.length })} - - {dissolveButton} -
-
- ) - } + // A blocked member floats into the Blocked section on its own + // (#2730) — rendering it here too would double it on the screen. + // Filtered rather than left to the caller: every renderGroupMembers + // call site (Pinned, directory groups, Blocked itself) would + // otherwise need to know about blockedSectionIds too. The leader's + // own row (getGroupRowProps, below) applies the same filter to its + // count/toggle summary. + const members = (groupMembersByLeader.get(leader.id) ?? []) + .filter((member) => !blockedSectionIds.has(member.id)) + if (members.length === 0) return null const open = isMemberListOpen(leader.id, members) - const status = summarizeGroupMembers(members, isSessionUnread, api?.hubClock?.now()) const leaderProject = getSessionProjectPath(leader.metadata) ?? 'Other' const leaderMachineId = leader.metadata?.machineId ?? null + // The leader row carries the count and the toggle; members indent + // under its title so they read as nested. return ( -
-
- - {dissolveButton} -
+
{[...members].sort((a, b) => { @@ -3103,36 +4040,80 @@ export function SessionList(props: { const collapseCount = visibleGroupSessions.length - previousGroupSessions.length const canShowFewerSessions = previousLimit < currentLimit && collapseCount > 0 const expandCount = Math.min(sessionPreviewLimit, hiddenSessionCount) - // With multiple machines in the unfiltered view, disambiguate - // same-named directories by suffixing the machine label. - const groupTitle = showMachineFilterBar && activeMachineFilter === null - ? `${group.displayName} · ${resolveMachineLabel(group.machineId)}` - : group.displayName + const projectTitle = projectGroupTitles.get(group.key) ?? group.displayName + // With multiple machines in the unfiltered view, display a muted + // machine label beside the project title. + const machineLabel = showMachineFilterBar && activeMachineFilter === null + ? resolveMachineLabel(group.machineId) + : null + const fullDisplayName = machineLabel ? `${projectTitle} · ${machineLabel}` : projectTitle + + let totalSessionCount = 0 + let hasAttention = false + let hasUnread = false + for (const session of group.sessions) { + totalSessionCount += 1 + if (session.active && (session.pendingRequestsCount ?? 0) > 0) hasAttention = true + if (isSessionUnread(session)) hasUnread = true + const members = groupMembersByLeader.get(session.id) + if (members) { + for (const member of members) { + totalSessionCount += 1 + if (member.active && (member.pendingRequestsCount ?? 0) > 0) hasAttention = true + if (isSessionUnread(member)) hasUnread = true + } + } + } + return ( -
+
toggleGroup(group.key, isCollapsed)} expanded={!isCollapsed} onNewSession={getNewSessionInGroup(group)} > - - - {groupTitle} - - + + +
+ + {projectTitle} + + {machineLabel ? ( + <> + + + {machineLabel} + + + ) : null} +
+ {renderNewSessionInGroupButton(group)} - - ({group.sessions.length}) + {isCollapsed && hasAttention ? ( +
{/* Sessions. Spacing lives inside the panels so folded rows take no room. */} -
+
@@ -3272,6 +4253,20 @@ export function SessionList(props: { return } + // A globally-pinned blocker keyboard-unpinned here moves into Blocked + // (#1717 cold-review round 25) — a destination this effect did not + // know about, so it fell through to the generic fallback below, + // which treats the move as a removal: focus landed on some other + // control and the row stayed hidden behind a collapsed panel. + if (blockedSectionSessions.some((session) => session.id === target.sessionId)) { + if (blockedSectionCollapsed && !isFiltering) { + setBlockedSectionCollapsed(false) + return + } + if (!target.pending) quickUnpinFocusRef.current = null + return + } + const targetGroup = groups.find((group) => group.sessions.some((session) => session.id === revealId) ) @@ -3319,6 +4314,7 @@ export function SessionList(props: { quickUnpinFocusRef.current = null }, [ globalPinnedSessions, runningSessions, groups, runningSectionCollapsed, + blockedSectionSessions, blockedSectionCollapsed, collapseOverrides, filterCollapseOverrides, sessionVisibleCounts, isFiltering, ephemeralFilter, selectedSessionId, folderSelectedId, sessionPreviewLimit, rowPreviewIsUnread, rowHasWaitingMember, sessionGroupLayout, memberListOverrides, filterMemberListOverrides, savedOpenMemberLists, @@ -3423,10 +4419,13 @@ export function SessionList(props: { const parsedGap = Number.parseFloat(getComputedStyle(root).columnGap) const morePx = moreNode && moreNode.offsetWidth > 0 ? moreNode.offsetWidth : TOOLBAR_MORE_PX const gapPx = Number.isFinite(parsedGap) && parsedGap > 0 ? parsedGap : TOOLBAR_GAP_PX + const blockedPx = blockedControlsRef.current?.offsetWidth ?? 0 setToolbarChrome((previous) => ( - previous.morePx === morePx && previous.gapPx === gapPx + previous.morePx === morePx + && previous.gapPx === gapPx + && previous.blockedPx === blockedPx ? previous - : { morePx, gapPx } + : { morePx, gapPx, blockedPx } )) // Reserve padding + gap + More so search cannot eat the trailing controls (#2040). const row = headerRowRef.current @@ -3539,6 +4538,296 @@ export function SessionList(props: { } }, []) + // #1717 off-viewport travel. Because the Blocked section keeps every + // blocked row mounted at the top of the list, "make the row reachable" + // only ever means expanding that section and dropping narrowing filters — + // no directory-group expansion or preview-cap raising required. + const jumpToNextBlocked = (viaKeyboard: boolean) => { + if (blockedSessions.length === 0) return + blockedJumpViaKeyboardRef.current = viaKeyboard + const renderedIds = new Set(machineFilteredSessions.map((session) => session.id)) + // Pick the target BEFORE deciding to clear anything. Testing "is any + // blocker hidden" threw away the operator's saved status/unread + // preferences even when the row we are about to travel to is already + // on screen — a filter they set is not ours to discard speculatively. + const cursor = blockedJumpCursorRef.current % blockedSessions.length + blockedJumpCursorRef.current = cursor + 1 + const blockedIds = blockedSessions.map((session) => session.id) + const blockedIdSet = new Set(blockedIds) + const visited = blockedJumpVisitedRef.current + // Drop visited ids that stopped being blocked, so a cleared blocker + // does not permanently shrink the pool later jumps can still reach. + for (const id of visited) { + if (!blockedIdSet.has(id)) visited.delete(id) + } + // A full lap: every counted blocker has already been visited this + // cycle. Start a fresh one instead of starving the directional and + // fallback picks of anything unvisited to choose. + if (visited.size >= blockedIds.length) { + visited.clear() + } + // The same snapshot the arrow is drawn from, so the click cannot + // disagree with it — including blockers whose section has collapsed + // and whose rows have left the DOM entirely. + const { above, below } = measureOffscreenBlockers() + // Cursor order, rotated to start where the last fallback left off, so + // a direction-exhausted or filter-hidden blocker is still reached by + // repeated clicks rather than being skipped forever. + const fallbackOrder = [...blockedIds.slice(cursor), ...blockedIds.slice(0, cursor)] + const targetId = chooseBlockedJumpTarget({ + direction: blockedDirection, + above, + below, + visited, + fallbackOrder + }) + const target = blockedSessions.find((session) => session.id === targetId) + ?? blockedSessions[cursor]! + visited.add(target.id) + if (!renderedIds.has(target.id)) { + // Reveal the target through transient state only. Writing + // `listView` / `machineFilter` persists to local storage, so a + // navigation action silently destroyed preferences the operator + // had set — the pill's job is to take them to the row, not to + // reset their list. Only the ephemeral lenses and the live search + // box are dropped, and `revealBlockedSessionId` exempts this one + // row from the rest. + setSearchQuery('') + setShowActiveOnly(false) + setShowWorkingOnly(false) + setShowScratchlistOnly(false) + setRevealBlockedSessionId(target.id) + } + // A globally pinned blocked row lives in the Pinned section, not the + // Blocked one — expand both or the jump lands on a zero-height row + // inside a collapsed panel and appears to do nothing. + setBlockedSectionCollapsed(false) + setPinnedSectionCollapsed(false) + setPendingBlockedScrollId(target.id) + } + + useEffect(() => { + if (!pendingBlockedScrollId) return + const container = scrollContainerRef.current + const row = container?.querySelector( + `[data-session-id="${CSS.escape(pendingBlockedScrollId)}"]` + ) + if (!row) { + // Usually "not mounted yet": clearing a filter or expanding the + // section re-renders and this effect runs again with the row in + // place. If the session stopped being blocked meanwhile, drop the + // request so it cannot wedge later jumps. + if (!blockedSessions.some((session) => session.id === pendingBlockedScrollId)) { + setPendingBlockedScrollId(null) + } + return + } + row.scrollIntoView({ block: 'center', behavior: 'smooth' }) + if (blockedJumpViaKeyboardRef.current) { + row.focus({ preventScroll: true }) + blockedJumpViaKeyboardRef.current = false + } + setFlashBlockedSessionId(pendingBlockedScrollId) + setPendingBlockedScrollId(null) + // The exemption is NOT dropped here. Releasing it the moment the + // smooth scroll starts unmounts the row mid-travel, so the operator + // arrives at nothing. It is released when the flash ends, which is + // long enough to see and act on the row. + }, [pendingBlockedScrollId, blockedSessions, blockedSectionSessions, blockedSectionCollapsed, machineFilteredSessions]) + + useEffect(() => { + if (!flashBlockedSessionId) return + const timer = setTimeout(() => { + // Releasing the exemption while a keyboard-focused control is + // still inside the revealed row unmounts it out from under the + // operator's next keystroke (#1717 cold-review round 27) — hand + // off to the dedicated focus-hold effect below instead of + // releasing directly. That effect runs on its OWN dependency + // (`focusHoldSessionId`), not on `flashBlockedSessionId` — doing + // the handoff here, in THIS effect, and tearing the listener + // down again the moment `flashBlockedSessionId` clears (which + // this very callback is about to do) would undo the handoff on + // the same render it happened. + // Not `row?.contains(document.activeElement)`: the row's action + // menu renders as a SIBLING of the row button, not a descendant + // (it needs `position: fixed` to escape the row's own overflow + // clipping), so opening it moves focus to an element the row + // never contained in the first place. Matching on the shared + // `data-session-id` from the focused element UPWARD catches + // both the row and its own open menu, whichever one focus is + // actually in (#1717 cold-review round 36). + const activeSessionId = document.activeElement instanceof Element + ? document.activeElement.closest('[data-session-id]')?.getAttribute('data-session-id') + : null + if (activeSessionId === flashBlockedSessionId) { + focusHeldAfterFlashRef.current = true + setFocusHoldSessionId(flashBlockedSessionId) + setFlashBlockedSessionId(null) + return + } + setFlashBlockedSessionId(null) + // Only drop the exemption if no dialog is open against that row. + // Expiring it underneath an open Mark-unblocked dialog unmounted + // the row mid-entry and took the dialog with it. The effect above + // releases it once that dialog closes. + if (blockedDialogSessionId === null) { + setRevealBlockedSessionId(null) + } + }, 2000) + return () => clearTimeout(timer) + }, [flashBlockedSessionId, blockedDialogSessionId]) + + useEffect(() => { + if (!focusHoldSessionId) return + const container = scrollContainerRef.current + const row = container?.querySelector( + `[data-session-id="${CSS.escape(focusHoldSessionId)}"]` + ) + if (!row) { + focusHeldAfterFlashRef.current = false + setFocusHoldSessionId(null) + return + } + const release = () => { + focusHeldAfterFlashRef.current = false + setFocusHoldSessionId(null) + if (blockedDialogSessionId === null) { + setRevealBlockedSessionId(null) + } + } + // Listening on `row` itself would miss every focus change inside + // the row's own action menu: the menu is a SIBLING of the row + // button in the DOM, not a descendant, so a `focusout` originating + // inside it never bubbles through `row` at all — it never reaches + // a listener attached there, regardless of containment logic + // (#1717 cold-review round 36). Listening on the scroll container + // sees every focus change in the list; matching the new target's + // own `data-session-id` is what scopes the check back down to + // this one row and its own menu, whichever one focus is moving + // into or out of. + const handleFocusOut = (event: FocusEvent) => { + const nextSessionId = event.relatedTarget instanceof Element + ? event.relatedTarget.closest('[data-session-id]')?.getAttribute('data-session-id') + : null + if (nextSessionId === focusHoldSessionId) return + release() + } + container?.addEventListener('focusout', handleFocusOut) + return () => container?.removeEventListener('focusout', handleFocusOut) + }, [focusHoldSessionId, blockedDialogSessionId]) + + // Direction hint for the pill: which way the operator would have to scroll + // to reach blocked rows that are not currently on screen. + // Built once, from state plus live rects, so the arrow and the jump target + // can never disagree about which blockers are off-screen (#1717). + const measureOffscreenBlockers = useCallback(() => { + const container = scrollContainerRef.current + if (!container) return { above: [] as string[], below: [] as string[] } + const bounds = container.getBoundingClientRect() + const mounted = Array.from( + container.querySelectorAll('[data-session-blocked]') + ).flatMap((row) => { + const id = row.getAttribute('data-session-id') + if (!id) return [] + const rect = row.getBoundingClientRect() + const panel = row.closest('.collapsible-panel') + return [{ + id, + top: rect.top, + bottom: rect.bottom, + height: rect.height, + // A collapse is a transition: during it the rows are still + // mounted at full size, so a height check would read them as + // visible. Afterwards they are gone entirely, which is why the + // section lists below exist. + collapsed: panel !== null && !panel.hasAttribute('data-open') + }] + }) + const headerRect = (testid: string) => container + .querySelector(`[data-testid="${testid}"]`) + ?.getBoundingClientRect() ?? null + return collectOffscreenBlockers({ + bounds, + mounted, + collapsedSections: [ + { + ids: blockedSectionCollapsed + ? blockedSectionSessions.map((session) => session.id) + : [], + headerRect: headerRect('blocked-section') + }, + { + // `isFiltering` forces Pinned open, matching its own + // `aria-expanded`, so it is only truly collapsed without one. + ids: pinnedSectionCollapsed && !isFiltering ? pinnedBlockedIds : [], + headerRect: headerRect('pinned-section') + } + ] + }) + }, [blockedSectionCollapsed, blockedSectionSessions, pinnedSectionCollapsed, pinnedBlockedIds, isFiltering]) + useEffect(() => { + const container = scrollContainerRef.current + if (!container || blockedCount === 0) { + // Functional + bail-out. A fresh `{above:0,below:0}` here would be a + // new identity every run, and this effect's deps churn on each + // render (the `machineLabelsById = {}` prop default cascades + // through the filter memos) — so an unconditional set becomes an + // infinite render loop. + setBlockedOffscreen((previous) => ( + previous.above === 0 && previous.below === 0 + ? previous + : { above: 0, below: 0 } + )) + return + } + let frame = 0 + const measure = () => { + frame = 0 + const { above, below } = measureOffscreenBlockers() + // Bail when nothing moved: this runs every scroll frame, and a + // fresh object each time would re-render every row in the list. + setBlockedOffscreen((previous) => ( + previous.above === above.length && previous.below === below.length + ? previous + : { above: above.length, below: below.length } + )) + } + const schedule = () => { + if (!frame) frame = requestAnimationFrame(measure) + } + schedule() + container.addEventListener('scroll', schedule, { passive: true }) + window.addEventListener('resize', schedule) + // Collapsing a section with the viewport stationary fires neither + // event, and the measurement taken on the click still sees the rows + // mounted — `CollapsiblePanel` removes them only after its 250ms + // transition. The arrow could therefore keep pointing at rows that no + // longer exist until some unrelated update happened to remeasure. + // Observing the content box catches the transition settling, whatever + // its duration, and covers Pinned and Blocked alike. + const observer = typeof ResizeObserver === 'undefined' + ? null + : new ResizeObserver(schedule) + if (observer) { + observer.observe(container) + for (const child of Array.from(container.children)) observer.observe(child) + } + return () => { + if (frame) cancelAnimationFrame(frame) + observer?.disconnect() + container.removeEventListener('scroll', schedule) + window.removeEventListener('resize', schedule) + } + }, [measureOffscreenBlockers, machineFilteredSessions]) + + const blockedDirection: BlockedJumpDirection = blockedOffscreen.above > 0 && blockedOffscreen.below > 0 + ? 'both' + : blockedOffscreen.above > 0 + ? 'up' + : blockedOffscreen.below > 0 + ? 'down' + : 'none' + return (
{deleteTarget && setDeleteTarget(null)} />} @@ -3551,7 +4840,28 @@ export function SessionList(props: {
controls -> list + // left the bar expanded and the normal toolbar hidden with + // focus already gone from both. This is their common + // ancestor, and with the search expanded it holds exactly + // those two. `SessionListSearch` keeps its own handler for + // the standalone usage that has no row around it. + onBlur={(event) => { + if (!searchExpanded) return + const related = event.relatedTarget as Element | null + if (related?.closest('[data-fue-callout]')) return + if (event.currentTarget.contains(related as Node | null)) return + setSearchExpanded(false) + }} > {showSearch ? ( 0 ? searchMaxPx : 0} /> ) : null} + {/* The actions row unmounts while the search field is + expanded, and it carries the blocked controls — so an + operator typing a query that hides the blocked rows lost + both the off-screen cue and the jump control until they + left the field, and an arrival pulse could expire unseen. + A compact cluster keeps both reachable. No + `blockedControlsRef` here: that measurement feeds the + shed budget of the row that is not currently rendered. */} + {showSearch && searchExpanded && (blockedCount > 0 || showBlockedOnly) ? ( +
+ {blockedCount > 0 ? ( + + ) : null} + setShowBlockedOnly(!showBlockedOnly)} + /> +
+ ) : null} {!(showSearch && searchExpanded) ? (
0 + ? toolbarChrome.blockedPx + toolbarChrome.gapPx + : 0 // Prefer the flex allocation. It tracks the row, not the // icons already on it. If they all fit, More is empty. const allocated = headerActionsRef.current?.clientWidth ?? 0 @@ -3599,7 +4946,7 @@ export function SessionList(props: { ? headerRowWidth : 0 const budget = gutter > 0 - ? gutter + ? Math.max(0, gutter - blockedAndGap) : toolbarActionBudget(0, searchQuery.length > 0) const slotWidth = (id: string, fallback: number) => { const measured = toolbarSlotWidths[id] ?? 0 @@ -3619,6 +4966,7 @@ export function SessionList(props: { setShowScratchlistOnly(false) setShowActiveOnly(false) setShowWorkingOnly(false) + setShowBlockedOnly(false) setCustomStart('') setCustomEnd('') setMachineFilter(null) @@ -3629,6 +4977,8 @@ export function SessionList(props: { onActiveChange={setShowActiveOnly} workingOnly={showWorkingOnly} onWorkingChange={setShowWorkingOnly} + blockedOnly={showBlockedOnly} + onBlockedChange={setShowBlockedOnly} customStart={customStart} customEnd={customEnd} sessionActivityDates={sessionActivityDates} @@ -3720,6 +5070,25 @@ export function SessionList(props: { ))}
+ {/* One measured box so `blockedPx` can be subtracted from + the shed budget below. These controls live in the + actions row but outside `definedSlots`, so without + reserving their width the shedder keeps icons inline + that no longer fit and the row overflows (#2039). */} + {blockedCount > 0 ? ( +
+ +
+ ) : null} {visible.map((slot) => ( {slot.node} @@ -3777,6 +5146,9 @@ export function SessionList(props: { ) : null}
+ + + {props.sessions.length === 0 && !props.isLoading ? ( ) : null} - {props.sessions.length > 0 && !contentSearchLoading && !contentSearchError && !contentSearchHasIncompleteResults && !isScratchlistStatusLoading && !scratchlistStatusError && (isFiltering || activeMachineFilter !== null || listView.status !== 'all' || listView.unreadOnly) && groups.length === 0 && runningSessionTotal === 0 && globalPinnedSessions.length === 0 ? ( + {props.sessions.length > 0 && !contentSearchLoading && !contentSearchError && !contentSearchHasIncompleteResults && !isScratchlistStatusLoading && !scratchlistStatusError && (isFiltering || activeMachineFilter !== null || listView.status !== 'all' || listView.unreadOnly || showBlockedOnly) && groups.length === 0 && runningSessionTotal === 0 && globalPinnedSessions.length === 0 && blockedSectionSessions.length === 0 ? (
{contentSearchActive ? contentSearchReady @@ -3844,9 +5216,9 @@ export function SessionList(props: { ) : null} {globalPinnedSessions.length > 0 ? ( -
+
- - - - {t('sessions.pinnedSection')} - - + + + + {t('sessions.pinnedSection')} -
-
+
{globalPinnedSessions.map((s) => ( + {renderGroupMembers(s)} + + ))} +
+ +
+ ) : null} + + {blockedSectionSessions.length > 0 ? ( +
+
setBlockedSectionCollapsed((value) => !value)} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + setBlockedSectionCollapsed((value) => !value) + } + }} + title={t('sessions.blockedSection')} + > + + + + + {t('sessions.blockedSection')} + + +
+ {/* CollapsiblePanel unmounts its children once the close + transition settles. The raw panel markup kept the row + buttons mounted and focusable, so a keyboard user tabbing + out of a collapsed header landed on invisible rows — one + dead tab stop per blocker. */} + +
+ {blockedSectionSessions.map((s) => ( + + {renderGroupMembers(s)} @@ -3918,6 +5362,17 @@ export function SessionList(props: { {groups.map(renderDirectoryGroup)} {actionOnlyGroups.map(renderActionOnlyGroupHeader)} + {unblockTarget ? ( + + ) : null} + + +
diff --git a/web/src/components/SessionList.unread-visibility.test.tsx b/web/src/components/SessionList.unread-visibility.test.tsx index eeb34a65694..31a896eb529 100644 --- a/web/src/components/SessionList.unread-visibility.test.tsx +++ b/web/src/components/SessionList.unread-visibility.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ReactNode } from 'react' @@ -124,6 +124,38 @@ describe('SessionList unread visibility', () => { ]) expect(screen.queryByRole('button', { name: /Read row/ })).toBeNull() + expect(screen.queryByTestId('project-group-unread-dot')).toBeNull() + expect(screen.queryByTestId('project-group-attention-dot')).toBeNull() + }) + + it('shows an unread or attention indicator dot on collapsed project headers only', () => { + seedReads({ read: 1000, unread: 1000 }) + renderSessionList([ + makeSession({ id: 'unread', updatedAt: 2000, metadata: { path: '/work/unread-proj', name: 'Unread row' } }), + makeSession({ + id: 'pending', + active: true, + pendingRequestsCount: 1, + pendingRequestKinds: ['permission'], + updatedAt: 2000, + metadata: { path: '/work/pending-proj', name: 'Pending row' } + }) + ]) + + const unreadHeader = screen.getByTitle('/work/unread-proj') + expect(unreadHeader).toHaveAttribute('aria-expanded', 'false') + expect(unreadHeader.querySelector('[data-testid="project-group-unread-dot"]')).not.toBeNull() + fireEvent.click(unreadHeader) + expect(unreadHeader.querySelector('[data-testid="project-group-unread-dot"]')).toBeNull() + + // A lone session with a pending permission request is blocked (#1717) + // and floats out of its directory group into the Blocked section on + // its own, so the project header behind it has nothing left to + // expand or flag — the attention signal already lives in Blocked. + const pendingHeader = screen.getByTitle('/work/pending-proj') + expect(pendingHeader).not.toHaveAttribute('aria-expanded') + expect(pendingHeader.querySelector('[data-testid="project-group-attention-dot"]')).toBeNull() + expect(within(screen.getByTestId('blocked-section')).getByRole('button', { name: /Pending row/ })).toBeInTheDocument() }) }) diff --git a/web/src/components/SessionListViewMenu.tsx b/web/src/components/SessionListViewMenu.tsx index b2a5cc7c2b2..26e426925c0 100644 --- a/web/src/components/SessionListViewMenu.tsx +++ b/web/src/components/SessionListViewMenu.tsx @@ -102,6 +102,8 @@ export function SessionListViewMenu(props: { onActiveChange?: (value: boolean) => void workingOnly?: boolean onWorkingChange?: (value: boolean) => void + blockedOnly?: boolean + onBlockedChange?: (value: boolean) => void customStart?: string customEnd?: string sessionActivityDates?: ReadonlySet @@ -122,7 +124,7 @@ export function SessionListViewMenu(props: { const [anchor, setAnchor] = useState(null) const [menuLeft, setMenuLeft] = useState(null) const customized = !isDefaultSessionListView(props.view) - || Boolean(props.scratchlistOnly || props.activeOnly || props.workingOnly || props.customStart || props.customEnd || props.machineFilter) + || Boolean(props.scratchlistOnly || props.activeOnly || props.workingOnly || props.blockedOnly || props.customStart || props.customEnd || props.machineFilter) const closeDatePicker = useCallback(() => { setDatePickerOpen(false) dateFilterButtonRef.current?.focus() @@ -329,6 +331,14 @@ export function SessionListViewMenu(props: { onSelect={() => props.onScratchlistChange?.(!props.scratchlistOnly)} /> ) : null} + {props.onBlockedChange ? ( + props.onBlockedChange?.(!props.blockedOnly)} + /> + ) : null}
{props.machines && props.onMachineChange ? (
diff --git a/web/src/components/SessionRowSummary.tsx b/web/src/components/SessionRowSummary.tsx index f1ee1aa0196..8c4201d38bd 100644 --- a/web/src/components/SessionRowSummary.tsx +++ b/web/src/components/SessionRowSummary.tsx @@ -5,7 +5,13 @@ import { AgentFlavorIcon } from '@/components/AgentFlavorIcon' import { InfoIcon, LoaderIcon, ScheduleIcon, StoppedBadgeIcon } from '@/components/icons' import { HoverTooltip, SESSION_ROW_TOOLTIP_FOCUS_CLASS, useSessionRowTooltipIds } from '@/components/HoverTooltip' import { getAttentionLabel, SessionAttentionIndicator, SessionRequestIcon } from '@/components/SessionAttentionIndicator' -import { classifySessionAttention, sessionIsUnread } from '@/lib/sessionAttention' +import { + classifySessionAttention, + getSessionBlockedLabelKey, + getSessionBlockedState, + sessionBlockedIsError, + sessionIsUnread +} from '@/lib/sessionAttention' import { getSessionLastSeenAt, getSessionManualUnreadAt } from '@/lib/sessionLastSeen' import { formatRelativeTime } from '@/lib/relativeTime' import { getStoppedSessionTime } from '@/lib/sessionListOrder' @@ -180,6 +186,11 @@ export function SessionRowSummary(props: { // Unread rows hand the agent icon to the attention tooltip as the "unread" // symbol, so it is no longer the presence badge and must not pulse. const plainUnreadTarget = attention?.kind === 'unread' && nestedTooltips && !attentionTooltipIdProp + // Blocked rides a different visual channel to the attention dot (chip + + // row rail), so a session can be both blocked and awaiting a permission + // without either signal having to win. + const blocked = getSessionBlockedState(s, { now: Date.now() }) + const blockedLabel = blocked ? t(getSessionBlockedLabelKey(blocked)) : null const urgentAttention = attention !== null && (attention.kind === 'permission' || attention.kind === 'input') const modelErrorActive = hasUrgentModelError(s.metadata) @@ -292,6 +303,22 @@ export function SessionRowSummary(props: { > {sessionName}
+ {blocked && blockedLabel ? ( + + {blockedLabel} + + ) : null} {/* Model error outranks activity/unread: the turn looked finished but failed, so this must not be collapsed into the combined indicator below. */} @@ -366,7 +393,9 @@ export function SessionRowSummary(props: { {todoProgress.completed}/{todoProgress.total} ) : null} - {!attention && s.active && s.pendingRequestsCount > 0 ? ( + {/* The blocked chip already names the reason; repeating + "pending N" here just crowds the title out of a narrow row. */} + {!attention && !blocked && s.active && s.pendingRequestsCount > 0 ? ( {t('session.item.pending')} {s.pendingRequestsCount} diff --git a/web/src/components/UnblockReasonDialog.test.tsx b/web/src/components/UnblockReasonDialog.test.tsx new file mode 100644 index 00000000000..96c5f8d1cad --- /dev/null +++ b/web/src/components/UnblockReasonDialog.test.tsx @@ -0,0 +1,82 @@ +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { I18nProvider } from '@/lib/i18n-context' +import { UnblockReasonDialog } from './UnblockReasonDialog' + +afterEach(cleanup) + +function renderDialog(overrides: { + onConfirm: (reason: string) => Promise + isPending?: boolean +}) { + return render( + + + + ) +} + +describe('UnblockReasonDialog (#1717)', () => { + it('submits one dismissal when the keyboard shortcut is pressed twice', async () => { + // The Confirm button disables itself while the mutation runs, but + // Ctrl/Cmd+Enter in the textarea reaches the submit handler directly. + // A second press mid-flight sent a second dismissal and appended a + // duplicate `operator_unblock` ledger event for one operator decision. + let release: (() => void) | undefined + const onConfirm = vi.fn(() => new Promise((resolve) => { release = resolve })) + renderDialog({ onConfirm }) + + const textarea = screen.getByRole('textbox') + fireEvent.change(textarea, { target: { value: 'handled out of band' } }) + + fireEvent.keyDown(textarea, { key: 'Enter', ctrlKey: true }) + fireEvent.keyDown(textarea, { key: 'Enter', ctrlKey: true }) + fireEvent.keyDown(textarea, { key: 'Enter', metaKey: true }) + + expect(onConfirm).toHaveBeenCalledTimes(1) + release?.() + }) + + it('still submits on a single shortcut press', () => { + // Positive control: the guard must not swallow the first activation. + const onConfirm = vi.fn(() => Promise.resolve()) + renderDialog({ onConfirm }) + + const textarea = screen.getByRole('textbox') + fireEvent.change(textarea, { target: { value: 'not actually blocked' } }) + fireEvent.keyDown(textarea, { key: 'Enter', ctrlKey: true }) + + expect(onConfirm).toHaveBeenCalledTimes(1) + expect(onConfirm).toHaveBeenCalledWith('not actually blocked') + }) + + it('refuses an empty reason without calling the mutation', () => { + const onConfirm = vi.fn(() => Promise.resolve()) + renderDialog({ onConfirm }) + + fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', ctrlKey: true }) + + expect(onConfirm).not.toHaveBeenCalled() + }) + + it('ignores the shortcut while a dismissal is already pending', () => { + // `isPending` arrives from the caller's mutation state, so it covers + // the window after a re-render as well as the synchronous latch. + const onConfirm = vi.fn(() => Promise.resolve()) + renderDialog({ onConfirm, isPending: true }) + + const textarea = screen.getByRole('textbox') + fireEvent.change(textarea, { target: { value: 'handled out of band' } }) + fireEvent.keyDown(textarea, { key: 'Enter', ctrlKey: true }) + + expect(onConfirm).not.toHaveBeenCalled() + }) +}) diff --git a/web/src/components/UnblockReasonDialog.tsx b/web/src/components/UnblockReasonDialog.tsx new file mode 100644 index 00000000000..84f64fe5836 --- /dev/null +++ b/web/src/components/UnblockReasonDialog.tsx @@ -0,0 +1,216 @@ +import { useEffect, useRef, useState } from 'react' +import { BLOCKED_ACK_REASON_MAX_CHARS } from '@hapi/protocol' +import { useTranslation } from '@/lib/use-translation' +import { cn } from '@/lib/utils' + +/** + * Presets for the common dismissals (#1717). + * + * The reason is mandatory, and mandatory free-text at fleet scale would either + * get skipped or get filled with "x". One tap writes a real, machine-comparable + * rationale into the ledger; the free-text box stays for the cases that + * deserve one. + */ +const PRESET_KEYS = [ + 'sessions.unblock.preset.handled', + 'sessions.unblock.preset.notBlocked', + 'sessions.unblock.preset.abandoned', + 'sessions.unblock.preset.superseded', +] as const + +export function UnblockReasonDialog(props: { + isOpen: boolean + sessionTitle: string + blockedLabel: string | null + blockedNote: string | null + isPending?: boolean + onClose: () => void + onConfirm: (reason: string) => Promise + /** Where keyboard focus returns on Escape / Cancel / confirm. Passed in + * because reading `document.activeElement` here races the action menu + * closing and the textarea's own autoFocus — cleanup then tried to focus + * the textarea as it unmounted, leaving the user with no focus at all. */ + returnFocusTo?: () => HTMLElement | null +}) { + const { t } = useTranslation() + const [reason, setReason] = useState('') + const [error, setError] = useState(null) + const inputRef = useRef(null) + const dialogRef = useRef(null) + // Synchronous in-flight latch; see `submit`. + const inFlightRef = useRef(false) + // Restore focus to the caller-named target, so dismissing returns the + // keyboard user to the session row rather than the top of the document. + // Deliberately NOT keyed on the callback identity. SessionItem passes a + // fresh closure every render, so including it re-ran cleanup whenever the + // mutation went pending — focusing the row while the dialog was still + // open, which put keyboard input behind the focus trap. + const returnFocusRef = useRef(props.returnFocusTo) + returnFocusRef.current = props.returnFocusTo + useEffect(() => { + if (!props.isOpen) return + return () => returnFocusRef.current?.()?.focus?.() + }, [props.isOpen]) + + useEffect(() => { + if (props.isOpen) { + setReason('') + setError(null) + } + }, [props.isOpen]) + + if (!props.isOpen) return null + + const trimmed = reason.trim() + + const submit = async () => { + // One guard for BOTH activations. The Confirm button disables itself + // while the mutation runs, but Ctrl/Cmd+Enter in the textarea reaches + // this directly, so a second press mid-flight sent a second dismissal + // and appended a duplicate `operator_unblock` for one decision. + // `inFlightRef`, not `props.isPending`: that arrives via a re-render, + // which is too late for two keystrokes in the same tick. + if (inFlightRef.current || props.isPending) return + if (trimmed.length === 0) { + setError(t('sessions.unblock.reasonRequired')) + inputRef.current?.focus() + return + } + inFlightRef.current = true + try { + await props.onConfirm(trimmed.slice(0, BLOCKED_ACK_REASON_MAX_CHARS)) + props.onClose() + } catch (err) { + setError(err instanceof Error ? err.message : t('dialog.error.default')) + } finally { + // Released on failure so the operator can retry; on success the + // dialog has already closed. + inFlightRef.current = false + } + } + + return ( +
+
event.stopPropagation()} + // `aria-modal` promises the background is inert, but nothing + // enforced it: tabbing past Confirm reached the session + // controls underneath, which stayed actionable. Trap the ring + // and honour Escape so the promise is real. + onKeyDown={(event) => { + if (event.key === 'Escape') { + event.stopPropagation() + props.onClose() + return + } + if (event.key !== 'Tab') return + const focusables = dialogRef.current?.querySelectorAll( + 'button:not([disabled]), textarea:not([disabled]), input:not([disabled]), [href], [tabindex]:not([tabindex="-1"])' + ) + if (!focusables || focusables.length === 0) return + const first = focusables[0]! + const last = focusables[focusables.length - 1]! + const active = document.activeElement + if (!event.shiftKey && active === last) { + event.preventDefault() + first.focus() + } else if (event.shiftKey && active === first) { + event.preventDefault() + last.focus() + } + }} + > +
+ {t('sessions.unblock.title')} +
+
+ {props.sessionTitle} +
+ + {props.blockedLabel ? ( +
+ {props.blockedLabel} + {props.blockedNote ? {props.blockedNote} : null} +
+ ) : null} + +

+ {t('sessions.unblock.description')} +

+ +
+ {PRESET_KEYS.map((key) => { + const label = t(key) + const selected = trimmed === label + return ( + + ) + })} +
+ +