From 6c69e2f315d717cc5bc7b4b70119e7353915037f Mon Sep 17 00:00:00 2001 From: IanMStevenson Date: Tue, 15 Sep 2026 02:01:05 +0100 Subject: [PATCH 01/34] fix(cli,hub): finalize canceled permission requests and surface stale answers (#1854) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(cli,hub): finalize canceled permission requests and surface stale answers When Claude Code sends control_cancel_request for a pending AskUserQuestion, the abort handler only removed the local pendingRequests entry and rejected the promise — it never finalized the request in agentState the way the session-level cancelPendingRequests path already does. A late answer to the now-stale widget would still pass the hub's requests[id] check, forward via RPC, land on a CLI that had already forgotten the request, and get silently absorbed with no error anywhere. Two changes, needed together: - permissionHandler.ts's abort handler now calls finalizeRequest with status: 'canceled', so cancellation is reflected in agentState the same way a session-level cancel already is. Once synced to the hub, the existing requests[requestId] check in permissions.ts naturally rejects a late answer with 404 before it ever reaches the CLI. - For the narrower race where an answer's RPC reaches the CLI before that sync lands, handleMissingPendingResponse now throws instead of only logging. RpcHandlerManager.handleRequest already turns a thrown error into a `{ error }` RPC response; RpcGateway.approvePermission/ denyPermission now check for that and throw a typed PermissionRequestNotFoundError, which the hub route turns into a 409 instead of silently returning { ok: true }. Fixes #1735 Co-Authored-By: Claude Sonnet 5 * fix(cli,hub): match the specific not-found message instead of any RPC error approvePermission/denyPermission treated any error on the Permission RPC method as "request not found", reasoning only in a code comment that nothing else on that path currently throws. Share the exact message via a new PERMISSION_REQUEST_NOT_FOUND_MESSAGE constant in shared/rpcMethods.ts, imported by both sides, so a future unrelated throw in handlePermissionResponse surfaces as itself instead of being relabeled as a stale request. Co-Authored-By: Claude Sonnet 5 --------- Co-authored-by: Ian Stevenson Co-authored-by: Claude Sonnet 5 --- .../claude/utils/permissionHandler.test.ts | 59 ++++++++- cli/src/claude/utils/permissionHandler.ts | 21 ++- hub/src/sync/rpcGateway.test.ts | 53 +++++++- hub/src/sync/rpcGateway.ts | 34 ++++- hub/src/web/routes/permissions.test.ts | 123 ++++++++++++++++++ hub/src/web/routes/permissions.ts | 19 ++- shared/src/rpcMethods.ts | 10 ++ 7 files changed, 309 insertions(+), 10 deletions(-) create mode 100644 hub/src/web/routes/permissions.test.ts diff --git a/cli/src/claude/utils/permissionHandler.test.ts b/cli/src/claude/utils/permissionHandler.test.ts index cc55b58b..c5954f0c 100644 --- a/cli/src/claude/utils/permissionHandler.test.ts +++ b/cli/src/claude/utils/permissionHandler.test.ts @@ -2,17 +2,24 @@ import { describe, expect, it, vi } from 'vitest'; import { PermissionHandler } from './permissionHandler'; import { PLAN_FAKE_REJECT, PLAN_FAKE_RESTART } from '../sdk/prompts'; import type { Session } from '../session'; +import type { AgentState } from '@/api/types'; function createFakeSession() { const queueItems: { message: string; mode: unknown }[] = []; let permissionMode: string | undefined; + let agentState: AgentState = { requests: {}, completedRequests: {} } as AgentState; + let rpcHandler: ((response: { id: string }) => Promise) | undefined; const session = { client: { rpcHandlerManager: { - registerHandler: vi.fn(), + registerHandler: vi.fn((_method: string, handler: any) => { + rpcHandler = handler; + }), }, - updateAgentState: vi.fn(), + updateAgentState: vi.fn((fn: (s: AgentState) => AgentState) => { + agentState = fn(agentState); + }), }, queue: { unshift: vi.fn((message: string, mode: unknown) => { @@ -25,7 +32,12 @@ function createFakeSession() { getPermissionMode: vi.fn(() => permissionMode), } as unknown as Session; - return { session, queueItems }; + return { + session, + queueItems, + getAgentState: () => agentState, + deliverRpcResponse: (r: { id: string }) => rpcHandler!(r), + }; } describe('PermissionHandler — YOLO plan mode', () => { @@ -141,3 +153,44 @@ describe('PermissionHandler — YOLO plan mode', () => { expect(result.behavior).toBe('allow'); }); }); + +// tiann/hapi#1735: canceling a pending AskUserQuestion (e.g. Claude sending a +// control_cancel_request) must finalize the request in agentState, and a +// late answer for an untracked request must surface an error rather than +// being silently dropped. +describe('PermissionHandler — canceled request finalization', () => { + it('finalizes an aborted request as canceled in agentState, and rejects a late answer instead of dropping it', async () => { + const { session, getAgentState, deliverRpcResponse } = createFakeSession(); + const handler = new PermissionHandler(session); + + handler.onMessage({ + type: 'assistant', + message: { role: 'assistant', content: [{ type: 'tool_use', id: 'tc-1', name: 'AskUserQuestion', input: { questions: [] } }] }, + } as any); + + const controller = new AbortController(); + const resultPromise = handler.handleToolCall( + 'AskUserQuestion', + { questions: [] }, + { permissionMode: 'default' } as any, + { signal: controller.signal } + ); + + expect(Object.keys(getAgentState().requests ?? {})).toEqual(['tc-1']); + + // Claude Code sends control_cancel_request for this tool call + controller.abort(); + await expect(resultPromise).rejects.toThrow('Permission request aborted'); + + // Fixed: the cancellation is now reflected in agentState, matching + // the session-level cancelPendingRequests path. + expect(getAgentState().requests?.['tc-1']).toBeUndefined(); + expect(getAgentState().completedRequests?.['tc-1']).toMatchObject({ status: 'canceled' }); + + // Operator answers the now-stale widget anyway; the RPC handler must + // reject rather than silently succeed. + await expect(deliverRpcResponse({ id: 'tc-1' } as any)).rejects.toThrow( + 'Permission request not found or already resolved' + ); + }); +}); diff --git a/cli/src/claude/utils/permissionHandler.ts b/cli/src/claude/utils/permissionHandler.ts index a6ccca17..f5d3a377 100644 --- a/cli/src/claude/utils/permissionHandler.ts +++ b/cli/src/claude/utils/permissionHandler.ts @@ -17,6 +17,7 @@ import { EnhancedMode, PermissionMode } from "../loop"; import { getToolDescriptor } from "./getToolDescriptor"; import { delay } from "@/utils/time"; import { isObject } from "@hapi/protocol"; +import { PERMISSION_REQUEST_NOT_FOUND_MESSAGE } from "@hapi/protocol/rpcMethods"; import { BasePermissionHandler, type PendingPermissionRequest, @@ -319,6 +320,16 @@ export class PermissionHandler extends BasePermissionHandler { this.pendingRequests.delete(id); + // Mirrors cancelPendingRequests' session-level cancel path: without + // this, a per-request abort (e.g. Claude sending a + // control_cancel_request) leaves the request live in agentState, so + // a later answer still passes the hub's requests[id] check and + // reaches handleMissingPendingResponse below instead of being + // rejected up front (hapi#1735). + this.finalizeRequest(id, { + status: 'canceled', + reason: 'Permission request aborted' + }); reject(new Error('Permission request aborted')); }; signal.addEventListener('abort', abortHandler, { once: true }); @@ -467,7 +478,15 @@ export class PermissionHandler extends BasePermissionHandler { expect((error as RpcTargetMissingError).code).toBe('socket-disconnected') }) }) + +// tiann/hapi#1735: a stale/canceled permission request answer must surface as +// a real error, not resolve as if it had been accepted. +describe('RpcGateway permission RPC error surfacing (tiann/hapi#1735)', () => { + function createGatewayWithResponse(errorMessage: string) { + const socket = { + timeout() { + return { + async emitWithAck() { + return JSON.stringify({ error: errorMessage }) + } + } + } + } + const io = { + of() { + return { sockets: { get() { return socket } } } + } + } as unknown as Server + const rpcRegistry = { + getSocketIdForMethod() { return 'socket-1' } + } as unknown as RpcRegistry + return new RpcGateway(io, rpcRegistry) + } + + it('throws PermissionRequestNotFoundError when the CLI reports no pending request for approve', async () => { + const gateway = createGatewayWithResponse(PERMISSION_REQUEST_NOT_FOUND_MESSAGE) + const error = await gateway.approvePermission('session-1', 'request-1').catch((e: unknown) => e) + expect(error).toBeInstanceOf(PermissionRequestNotFoundError) + }) + + it('throws PermissionRequestNotFoundError when the CLI reports no pending request for deny', async () => { + const gateway = createGatewayWithResponse(PERMISSION_REQUEST_NOT_FOUND_MESSAGE) + const error = await gateway.denyPermission('session-1', 'request-1').catch((e: unknown) => e) + expect(error).toBeInstanceOf(PermissionRequestNotFoundError) + }) + + it('does not relabel an unrelated RPC error as PermissionRequestNotFoundError', async () => { + const gateway = createGatewayWithResponse('Some other failure unrelated to a missing request') + // Only the specific shared message is treated as "not found"; anything + // else on this RPC method currently resolves rather than being + // mislabeled — a narrower, orthogonal gap than what this PR fixes. + await expect(gateway.approvePermission('session-1', 'request-1')).resolves.toBeUndefined() + }) + + it('resolves normally when the CLI accepts the answer', async () => { + const { gateway } = createGateway() + await expect(gateway.approvePermission('session-1', 'request-1')).resolves.toBeUndefined() + }) +}) diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index 90346e13..fc4112ba 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -1,5 +1,5 @@ import type { AgentFlavor, CodexCollaborationMode, CopilotAgentMode, PermissionMode } from '@hapi/protocol/types' -import { RPC_METHODS } from '@hapi/protocol/rpcMethods' +import { PERMISSION_REQUEST_NOT_FOUND_MESSAGE, RPC_METHODS } from '@hapi/protocol/rpcMethods' import { ArchiveCodexSessionRpcResponseSchema, AgentAvailabilityResponseSchema, @@ -65,6 +65,28 @@ export class RpcTargetMissingError extends Error { } } +/** + * The CLI no longer has this permission request pending — most often because + * it was already answered, or canceled on the agent side (e.g. Claude Code + * sent a control_cancel_request for it) before this answer arrived. + */ +export class PermissionRequestNotFoundError extends Error { + constructor(requestId: string) { + super(`Permission request is no longer active: ${requestId}`) + this.name = 'PermissionRequestNotFoundError' + } +} + +// Matches on the specific shared message rather than treating any error on +// the Permission RPC method as "not found" — a future, unrelated throw in +// handlePermissionResponse's success path should surface as a genuine error, +// not get relabeled as a stale request. +function isPermissionRequestNotFoundResponse(response: unknown): boolean { + if (!response || typeof response !== 'object') return false + const error = (response as Record).error + return error === PERMISSION_REQUEST_NOT_FOUND_MESSAGE +} + export type RpcCommandResponse = CommandResponse export type FileSearchOptions = { query: string @@ -111,7 +133,7 @@ export class RpcGateway { decision?: 'approved' | 'approved_for_session' | 'denied' | 'abort', answers?: Record | Record ): Promise { - await this.sessionRpc(sessionId, RPC_METHODS.Permission, { + const response = await this.sessionRpc(sessionId, RPC_METHODS.Permission, { id: requestId, approved: true, mode, @@ -119,6 +141,9 @@ export class RpcGateway { decision, answers }) + if (isPermissionRequestNotFoundResponse(response)) { + throw new PermissionRequestNotFoundError(requestId) + } } async denyPermission( @@ -126,11 +151,14 @@ export class RpcGateway { requestId: string, decision?: 'approved' | 'approved_for_session' | 'denied' | 'abort' ): Promise { - await this.sessionRpc(sessionId, RPC_METHODS.Permission, { + const response = await this.sessionRpc(sessionId, RPC_METHODS.Permission, { id: requestId, approved: false, decision }) + if (isPermissionRequestNotFoundResponse(response)) { + throw new PermissionRequestNotFoundError(requestId) + } } async abortSession(sessionId: string): Promise { diff --git a/hub/src/web/routes/permissions.test.ts b/hub/src/web/routes/permissions.test.ts new file mode 100644 index 00000000..c39346ff --- /dev/null +++ b/hub/src/web/routes/permissions.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from 'bun:test' +import { Hono } from 'hono' +import type { Session, SyncEngine } from '../../sync/syncEngine' +import type { WebAppEnv } from '../middleware/auth' +import { PermissionRequestNotFoundError } from '../../sync/rpcGateway' +import { createPermissionsRoutes } from './permissions' + +function createSession(): Session { + return { + id: 'session-1', + namespace: 'default', + seq: 1, + createdAt: 1, + updatedAt: 1, + active: true, + activeAt: 1, + metadata: { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + metadataVersion: 1, + agentState: { + controlledByUser: false, + requests: { + 'request-1': { tool: 'AskUserQuestion', arguments: {}, createdAt: 1 } + }, + completedRequests: {} + }, + agentStateVersion: 1, + thinking: false, + thinkingAt: 1, + model: null, + modelReasoningEffort: null, + effort: null, + serviceTier: null, + permissionMode: 'default', + collaborationMode: 'default' + } as Session +} + +function createApp(opts?: { + approvePermission?: SyncEngine['approvePermission'] + denyPermission?: SyncEngine['denyPermission'] +}) { + const session = createSession() + const engine = { + resolveSessionAccess: () => ({ ok: true, sessionId: session.id, session }), + approvePermission: opts?.approvePermission ?? (async () => {}), + denyPermission: opts?.denyPermission ?? (async () => {}) + } as Partial + + const app = new Hono() + app.use('*', async (c, next) => { + c.set('namespace', 'default') + await next() + }) + app.route('/api', createPermissionsRoutes(() => engine as SyncEngine)) + return app +} + +// tiann/hapi#1735: a stale/canceled permission request must not silently +// accept an answer — the operator needs to see it failed. +describe('permissions routes (tiann/hapi#1735)', () => { + it('approves a pending request', async () => { + const app = createApp() + const res = await app.request('/api/sessions/session-1/permissions/request-1/approve', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ answers: { '0': ['Alpha'] } }) + }) + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ ok: true }) + }) + + it('returns 409 when the CLI no longer has the request pending on approve', async () => { + const app = createApp({ + approvePermission: async () => { throw new PermissionRequestNotFoundError('request-1') } + }) + const res = await app.request('/api/sessions/session-1/permissions/request-1/approve', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ answers: { '0': ['Alpha'] } }) + }) + expect(res.status).toBe(409) + expect(await res.json()).toEqual({ error: 'Permission request is no longer active: request-1' }) + }) + + it('returns 409 when the CLI no longer has the request pending on deny', async () => { + const app = createApp({ + denyPermission: async () => { throw new PermissionRequestNotFoundError('request-1') } + }) + const res = await app.request('/api/sessions/session-1/permissions/request-1/deny', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({}) + }) + expect(res.status).toBe(409) + expect(await res.json()).toEqual({ error: 'Permission request is no longer active: request-1' }) + }) + + it('404s for a request id the session has never heard of, without calling the engine', async () => { + let called = false + const app = createApp({ approvePermission: async () => { called = true } }) + const res = await app.request('/api/sessions/session-1/permissions/unknown-request/approve', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({}) + }) + expect(res.status).toBe(404) + expect(called).toBe(false) + }) + + it('lets an unrelated engine error propagate instead of being swallowed as a 409', async () => { + const app = createApp({ + approvePermission: async () => { throw new Error('boom') } + }) + const res = await app.request('/api/sessions/session-1/permissions/request-1/approve', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({}) + }) + // Hono's default error handling turns an unhandled throw into a 500, + // not a 409 — the route only special-cases PermissionRequestNotFoundError. + expect(res.status).toBe(500) + }) +}) diff --git a/hub/src/web/routes/permissions.ts b/hub/src/web/routes/permissions.ts index 3173ae84..a4bb2d7e 100644 --- a/hub/src/web/routes/permissions.ts +++ b/hub/src/web/routes/permissions.ts @@ -2,6 +2,7 @@ import { isPermissionModeAllowedForFlavor } from '@hapi/protocol' import { PermissionModeSchema } from '@hapi/protocol/schemas' import { Hono } from 'hono' import { z } from 'zod' +import { PermissionRequestNotFoundError } from '../../sync/rpcGateway' import type { SyncEngine } from '../../sync/syncEngine' import type { WebAppEnv } from '../middleware/auth' import { requireSessionFromParam, requireSyncEngine } from './guards' @@ -64,7 +65,14 @@ export function createPermissionsRoutes(getSyncEngine: () => SyncEngine | null): const allowTools = parsed.data.allowTools const decision = parsed.data.decision const answers = parsed.data.answers - await engine.approvePermission(sessionId, requestId, mode, allowTools, decision, answers) + try { + await engine.approvePermission(sessionId, requestId, mode, allowTools, decision, answers) + } catch (error) { + if (error instanceof PermissionRequestNotFoundError) { + return c.json({ error: error.message }, 409) + } + throw error + } return c.json({ ok: true }) }) @@ -93,7 +101,14 @@ export function createPermissionsRoutes(getSyncEngine: () => SyncEngine | null): return c.json({ error: 'Invalid body' }, 400) } - await engine.denyPermission(sessionId, requestId, parsed.data.decision) + try { + await engine.denyPermission(sessionId, requestId, parsed.data.decision) + } catch (error) { + if (error instanceof PermissionRequestNotFoundError) { + return c.json({ error: error.message }, 409) + } + throw error + } return c.json({ ok: true }) }) diff --git a/shared/src/rpcMethods.ts b/shared/src/rpcMethods.ts index 325a1586..1ad52370 100644 --- a/shared/src/rpcMethods.ts +++ b/shared/src/rpcMethods.ts @@ -55,4 +55,14 @@ export const RPC_METHODS = { export const RPC_TARGET_MISSING_ERROR_CODE = 'rpc_target_missing' as const +/** + * Thrown by a permission handler's handleMissingPendingResponse when a + * Permission RPC response arrives for a request the CLI no longer has + * pending (already answered, or canceled on the agent side). Shared so the + * hub can match on the specific message rather than treating any error on + * this RPC method as "not found" — see RpcGateway.approvePermission/ + * denyPermission. + */ +export const PERMISSION_REQUEST_NOT_FOUND_MESSAGE = 'Permission request not found or already resolved' as const + export type RpcMethod = typeof RPC_METHODS[keyof typeof RPC_METHODS] From facb66ee0385fe35dc7244586ced14214cbccbf5 Mon Sep 17 00:00:00 2001 From: weishu Date: Tue, 15 Sep 2026 09:07:47 +0800 Subject: [PATCH 02/34] Release version 0.30.7 --- android/app/build.gradle.kts | 2 +- bun.lock | 22 +++++++++++----------- cli/package.json | 12 ++++++------ ios/Hapi.xcodeproj/project.pbxproj | 8 ++++---- shared/src/buildInfo.ts | 2 +- 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 3f21e3c1..a7292fb5 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -80,7 +80,7 @@ android { value.toInt().also { require(it > 0) { "hapiVersionCode must be positive" } } }.orElse(1).get() // Tracks the hapi CLI/hub release train. - versionName = providers.gradleProperty("hapiVersionName").orElse("0.30.6").get() + versionName = providers.gradleProperty("hapiVersionName").orElse("0.30.7").get() testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } diff --git a/bun.lock b/bun.lock index 21dfdd1c..ddfadeab 100644 --- a/bun.lock +++ b/bun.lock @@ -13,7 +13,7 @@ }, "cli": { "name": "@twsxtd/hapi", - "version": "0.30.6", + "version": "0.30.7", "bin": { "hapi": "bin/hapi.cjs", }, @@ -48,11 +48,11 @@ "vitest": "^4.0.16", }, "optionalDependencies": { - "@twsxtd/hapi-darwin-arm64": "0.30.6", - "@twsxtd/hapi-darwin-x64": "0.30.6", - "@twsxtd/hapi-linux-arm64": "0.30.6", - "@twsxtd/hapi-linux-x64": "0.30.6", - "@twsxtd/hapi-win32-x64": "0.30.6", + "@twsxtd/hapi-darwin-arm64": "0.30.7", + "@twsxtd/hapi-darwin-x64": "0.30.7", + "@twsxtd/hapi-linux-arm64": "0.30.7", + "@twsxtd/hapi-linux-x64": "0.30.7", + "@twsxtd/hapi-win32-x64": "0.30.7", }, }, "docs": { @@ -1111,15 +1111,15 @@ "@twsxtd/hapi": ["@twsxtd/hapi@workspace:cli"], - "@twsxtd/hapi-darwin-arm64": ["@twsxtd/hapi-darwin-arm64@0.30.6", "", { "os": "darwin", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-aiaLjk1fh4qNwtM7STQcWquikZcM0zWL1XQXK7pqXEFB09py+GZt4TEv5MxJhsFbk+Y6OxzhaWvowre832kdJw=="], + "@twsxtd/hapi-darwin-arm64": ["@twsxtd/hapi-darwin-arm64@0.30.7", "", { "os": "darwin", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-liXzQiIdNrEobPqlVRmbdIcN8r7W9e/7Vcc5gO34keJwzr6PZ4JZO4BM2PnNuw57WD2EeXb4aBR5PSOFhYi6Xw=="], - "@twsxtd/hapi-darwin-x64": ["@twsxtd/hapi-darwin-x64@0.30.6", "", { "os": "darwin", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-9DqQMShZRCQ59ypes7zIbBo1EhxtNiMxJYS9Sg1bu5PIkIsxGY8FRDTwN8uFqV14ZQm8FrfQiISonGrBwvt5Bg=="], + "@twsxtd/hapi-darwin-x64": ["@twsxtd/hapi-darwin-x64@0.30.7", "", { "os": "darwin", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-GbakM5JycgyINRfsBfHwvUIqA/faq63Kzu28ARcFxXqyet4hrS8P0Xawrsbmawq6RibK3sI74kX5cRlFmtXpZw=="], - "@twsxtd/hapi-linux-arm64": ["@twsxtd/hapi-linux-arm64@0.30.6", "", { "os": "linux", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-rOr7G57dG4zFGp3hrzGU2RZx+6a7Qi2UPcFoWNU+8h080u+Qp12+AGK7LEpFMgJbHemc0qU0BWXzc+RDuxolAA=="], + "@twsxtd/hapi-linux-arm64": ["@twsxtd/hapi-linux-arm64@0.30.7", "", { "os": "linux", "cpu": "arm64", "bin": { "hapi": "bin/hapi" } }, "sha512-v3OQ7ZrsLLwcCGIBd9lCCp+5vNoR0u+g+oWUV2iIAWvi2nmGF6zHvYT0Bl4+G9rjk29wdR8XemrItSfQrc3kbg=="], - "@twsxtd/hapi-linux-x64": ["@twsxtd/hapi-linux-x64@0.30.6", "", { "os": "linux", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-gEVZSdU9WjP4V9Uk2Va9JAG6iMQF3Lfe+y9BjUSGmqueqOTeEOZA8N/nFc+zQ16iECBG5PK5RYFuosWmZv1YrA=="], + "@twsxtd/hapi-linux-x64": ["@twsxtd/hapi-linux-x64@0.30.7", "", { "os": "linux", "cpu": "x64", "bin": { "hapi": "bin/hapi" } }, "sha512-/e712GKRzzeVD2SMO+ApIxd1/CkIHyKZRRzkEK1WWWvcie45Onres8z58V3liEA/JxbHUxaKaOPW7N0xQBVq1Q=="], - "@twsxtd/hapi-win32-x64": ["@twsxtd/hapi-win32-x64@0.30.6", "", { "os": "win32", "cpu": "x64", "bin": { "hapi": "bin/hapi.exe" } }, "sha512-chrreln6teaYCHgytSLXRlx3wt8x1p9ORstlxx0IZLl+8bPZ7C8sP5iCQc/N/ufZsZ9+jvU28ijpdN1FlY9fLg=="], + "@twsxtd/hapi-win32-x64": ["@twsxtd/hapi-win32-x64@0.30.7", "", { "os": "win32", "cpu": "x64", "bin": { "hapi": "bin/hapi.exe" } }, "sha512-oO43ncEFZVEUIUxQjzwTNdr70ae1pc8TEYBBa+lGhIOpU5NQNWu+Fc0tKqwvIcRKhXYqsHHPaVLqp+gg5uHxeQ=="], "@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="], diff --git a/cli/package.json b/cli/package.json index 1776870a..e7f9a084 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@twsxtd/hapi", - "version": "0.30.6", + "version": "0.30.7", "description": "App for agentic coding - access coding agent anywhere", "author": "Kirill Dubovitskiy & weishu", "license": "AGPL-3.0-only", @@ -26,11 +26,11 @@ } }, "optionalDependencies": { - "@twsxtd/hapi-darwin-arm64": "0.30.6", - "@twsxtd/hapi-darwin-x64": "0.30.6", - "@twsxtd/hapi-linux-arm64": "0.30.6", - "@twsxtd/hapi-linux-x64": "0.30.6", - "@twsxtd/hapi-win32-x64": "0.30.6" + "@twsxtd/hapi-darwin-arm64": "0.30.7", + "@twsxtd/hapi-darwin-x64": "0.30.7", + "@twsxtd/hapi-linux-arm64": "0.30.7", + "@twsxtd/hapi-linux-x64": "0.30.7", + "@twsxtd/hapi-win32-x64": "0.30.7" }, "scripts": { "postinstall": "node -e \"try{require('fs').chmodSync(require('path').join(__dirname,'bin','hapi.cjs'),0o755)}catch(e){}\"", diff --git a/ios/Hapi.xcodeproj/project.pbxproj b/ios/Hapi.xcodeproj/project.pbxproj index 9057ea05..489c1dd2 100644 --- a/ios/Hapi.xcodeproj/project.pbxproj +++ b/ios/Hapi.xcodeproj/project.pbxproj @@ -407,7 +407,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 0.30.6; + MARKETING_VERSION = 0.30.7; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = NO; @@ -438,7 +438,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 0.30.6; + MARKETING_VERSION = 0.30.7; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = NO; @@ -462,7 +462,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.30.6; + MARKETING_VERSION = 0.30.7; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app.HapiNotificationService; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; @@ -487,7 +487,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.30.6; + MARKETING_VERSION = 0.30.7; PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app.HapiNotificationService; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; diff --git a/shared/src/buildInfo.ts b/shared/src/buildInfo.ts index 0423bcdb..2eaf2c38 100644 --- a/shared/src/buildInfo.ts +++ b/shared/src/buildInfo.ts @@ -1 +1 @@ -export const APP_VERSION = '0.30.6' +export const APP_VERSION = '0.30.7' From 08dfce67c3888de6df72294ec9a09a2a6be8d2d1 Mon Sep 17 00:00:00 2001 From: Aqi77su <15936726968@163.com> Date: Tue, 15 Sep 2026 13:07:46 +0800 Subject: [PATCH 03/34] fix(grok): preserve ACP text deltas (#1860) Grok ACP emits true agent_message_chunk deltas. Default overlap dedupe treats a later "0" after "300" as an already-buffered suffix and drops it, so the hub stores 300 instead of 3000. Set textChunkMode: 'delta' on createGrokBackend, matching OpenCode. Co-authored-by: Aqi77su <304702613+Aqi77su@users.noreply.github.com> --- .../backends/acp/AcpMessageHandler.test.ts | 37 +++++++++++++++++++ cli/src/grok/utils/grokBackend.test.ts | 35 +++++++++++++++++- cli/src/grok/utils/grokBackend.ts | 7 +++- 3 files changed, 77 insertions(+), 2 deletions(-) diff --git a/cli/src/agent/backends/acp/AcpMessageHandler.test.ts b/cli/src/agent/backends/acp/AcpMessageHandler.test.ts index 5d65e267..cc47e19c 100644 --- a/cli/src/agent/backends/acp/AcpMessageHandler.test.ts +++ b/cli/src/agent/backends/acp/AcpMessageHandler.test.ts @@ -397,6 +397,43 @@ describe('AcpMessageHandler', () => { expect(messages).toEqual([{ type: 'text', text: '|-----|-----|-----|\n' }]); }); + it('drops extra zeros after 300 under default dedupe', () => { + // Grok streams "3000" as "300" then "0". Default overlap-dedupe sees + // bufferedText.endsWith("0") after "300" and skips the extra zero. + const messages: AgentMessage[] = []; + const handler = new AcpMessageHandler((message) => messages.push(message)); + + for (const text of ['3 \n', '30 \n', '300', '0 \n', '300', '00']) { + handler.handleUpdate({ + sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk, + content: { type: 'text', text } + }); + } + + handler.flushText(); + + expect(messages).toEqual([{ type: 'text', text: '3 \n30 \n300 \n300' }]); + }); + + it('preserves extra zeros after 300 in delta mode', () => { + const messages: AgentMessage[] = []; + const handler = new AcpMessageHandler( + (message) => messages.push(message), + { textChunkMode: 'delta' } + ); + + for (const text of ['3 \n', '30 \n', '300', '0 \n', '300', '00']) { + handler.handleUpdate({ + sessionUpdate: ACP_SESSION_UPDATE_TYPES.agentMessageChunk, + content: { type: 'text', text } + }); + } + + handler.flushText(); + + expect(messages).toEqual([{ type: 'text', text: '3 \n30 \n3000 \n30000' }]); + }); + it('keeps existing tool name when update only has kind fallback', () => { const messages: AgentMessage[] = []; const handler = new AcpMessageHandler((message) => messages.push(message)); diff --git a/cli/src/grok/utils/grokBackend.test.ts b/cli/src/grok/utils/grokBackend.test.ts index 68a911b7..a5b1090a 100644 --- a/cli/src/grok/utils/grokBackend.test.ts +++ b/cli/src/grok/utils/grokBackend.test.ts @@ -1,6 +1,20 @@ -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const constructorCalls: Array> = [] + +vi.mock('@/agent/backends/acp', () => ({ + AcpSdkBackend: vi.fn().mockImplementation(function ( + this: unknown, + opts: Record + ) { + constructorCalls.push(opts) + return { __opts: opts } + }) +})) + import { buildGrokAgentArgs, + createGrokBackend, formatGrokError, isGrokBuildAuxiliaryQuotaError } from './grokBackend' @@ -53,6 +67,25 @@ describe('buildGrokAgentArgs', () => { }) }) +describe('createGrokBackend', () => { + beforeEach(() => { + constructorCalls.length = 0 + }) + + it('concatenates ACP text chunks as deltas instead of overlap-deduping them', () => { + createGrokBackend({ cwd: '/tmp/project', model: 'grok-4.6' }) + expect(constructorCalls).toHaveLength(1) + expect(constructorCalls[0]?.textChunkMode).toBe('delta') + expect(constructorCalls[0]?.flavor).toBe('grok') + expect(constructorCalls[0]?.args).toEqual([ + '--cwd', '/tmp/project', + 'agent', + '--model', 'grok-4.6', + 'stdio' + ]) + }) +}) + describe('formatGrokError', () => { it('turns ACP auth failures into an actionable login hint', () => { expect(formatGrokError(new Error('Authentication required: no auth method id provided'))) diff --git a/cli/src/grok/utils/grokBackend.ts b/cli/src/grok/utils/grokBackend.ts index f12eba02..2bbf02f2 100644 --- a/cli/src/grok/utils/grokBackend.ts +++ b/cli/src/grok/utils/grokBackend.ts @@ -45,7 +45,12 @@ export function createGrokBackend(opts: { return new AcpSdkBackend({ command: getAgentLaunchCommand('grok'), args: buildGrokAgentArgs(opts), - env: filterEnv(process.env) + env: filterEnv(process.env), + // Grok ACP emits true agent_message_chunk deltas. Default overlap + // dedupe treats a later "0" after "300" as an already-buffered suffix + // and drops it, so the hub stores 300 instead of 3000. + textChunkMode: 'delta', + flavor: 'grok' }) } From c70d2282dbd355efb2792e9e3a0f007c30b74326 Mon Sep 17 00:00:00 2001 From: Ananovo Date: Wed, 16 Sep 2026 07:23:30 +0800 Subject: [PATCH 04/34] test(ios): stabilize QuestionCard viewport assertions (#1865) --- .../QuestionCardPresentationTests.swift | 51 ++++++++++++++----- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/ios/HapiTests/QuestionCardPresentationTests.swift b/ios/HapiTests/QuestionCardPresentationTests.swift index da418c79..60f425d5 100644 --- a/ios/HapiTests/QuestionCardPresentationTests.swift +++ b/ios/HapiTests/QuestionCardPresentationTests.swift @@ -24,7 +24,6 @@ final class QuestionCardPresentationTests: XCTestCase { let presentation = ChatPresentationState() let interactor: ChatInteractor @ObservationIgnored var height: CGFloat = 0 - @ObservationIgnored var appeared = 0 init(tool: ChatToolCall) { self.tool = tool let url = URL(string: "http://127.0.0.1:1")! @@ -53,7 +52,7 @@ final class QuestionCardPresentationTests: XCTestCase { .environment(\.chatPresentationState, driver.presentation) .background(GeometryReader { geometry in Color.clear - .onAppear { driver.height = geometry.size.height; driver.appeared += 1 } + .onAppear { driver.height = geometry.size.height } .onChange(of: geometry.size.height) { _, height in driver.height = height } }) .hapiReadingColumn() @@ -212,38 +211,47 @@ final class QuestionCardPresentationTests: XCTestCase { let collection = try XCTUnwrap(findCollection(host.view)) try await settle { collection.numberOfItems(inSection: 0) == 40 } func browse(_ index: Int) async throws { + let indexPath = IndexPath(item: index, section: 0) collection.delegate?.scrollViewWillBeginDragging?(collection) - collection.scrollToItem(at: IndexPath(item: index, section: 0), at: .top, animated: false) - try await settle { collection.cellForItem(at: IndexPath(item: index, section: 0)) != nil } + collection.scrollToItem(at: indexPath, at: .top, animated: false) + try await settle { + rowIntersectsViewport(index, in: collection) + && collection.cellForItem(at: indexPath) != nil + } } try await browse(10) - let cell = try XCTUnwrap(collection.cellForItem(at: IndexPath(item: 10, section: 0))) - let offset = cell.frame.minY - collection.contentOffset.y + let offset = try XCTUnwrap(rowOffset(10, in: collection)) let form = QuestionAnswerForm(tool: driver.tool) driver.draft.select(0, at: 0, in: form) driver.draft.select(1, at: 1, in: form) driver.draft.toggleText(at: 1, in: form) driver.draft.setText("A multiline draft\nthat must survive recycling", at: 1, in: form) try await Task.sleep(for: .milliseconds(300)) - XCTAssertEqual(cell.frame.minY - collection.contentOffset.y, offset, accuracy: 1) + let offsetAfterEdit = try XCTUnwrap(rowOffset(10, in: collection)) + XCTAssertEqual(offsetAfterEdit, offset, accuracy: 1) let draft = driver.draft - let appearances = driver.appeared + // UIHostingConfiguration may keep SwiftUI roots alive while UIKit + // removes a cell from the viewport, so onAppear is not a reliable + // recycling signal. Assert the actual row geometry instead. try await browse(32) + try await settle { !rowIntersectsViewport(10, in: collection) } + XCTAssertFalse(rowIntersectsViewport(10, in: collection)) try await browse(10) + try await settle { rowIntersectsViewport(10, in: collection) } + XCTAssertTrue(rowIntersectsViewport(10, in: collection)) XCTAssertEqual(driver.draft, draft) - XCTAssertGreaterThan(driver.appeared, appearances, "The card must actually leave and reenter the viewport") XCTAssertEqual(driver.draft.page, 1, "Restoring the selected step must not advance it") driver.draft.previous(in: form) driver.draft.setText("Retained note", at: 0, in: form) - let anchor = try XCTUnwrap(collection.cellForItem(at: IndexPath(item: 10, section: 0))) - let anchorOffset = anchor.frame.minY - collection.contentOffset.y + let anchorOffset = try XCTUnwrap(rowOffset(10, in: collection)) let expandedHeight = driver.height driver.tool.permission = ToolPermission(id: "reply", status: .approved, answers: .object([ "a": .object(["answers": .array([.string("A")])]), "b": .object(["answers": .array([.string("D")])]), ])) try await settle { driver.height < expandedHeight } - XCTAssertEqual(anchor.frame.minY - collection.contentOffset.y, anchorOffset, accuracy: 1) + let anchorOffsetAfterCollapse = try XCTUnwrap(rowOffset(10, in: collection)) + XCTAssertEqual(anchorOffsetAfterCollapse, anchorOffset, accuracy: 1) } private func host(_ view: V, width: CGFloat) throws -> (UIWindow, UIHostingController) { @@ -267,6 +275,25 @@ final class QuestionCardPresentationTests: XCTestCase { return view.subviews.lazy.compactMap(findScroll).first } + private func rowIntersectsViewport(_ index: Int, in collection: UICollectionView) -> Bool { + collection.layoutIfNeeded() + guard let frame = collection.layoutAttributesForItem(at: IndexPath(item: index, section: 0))?.frame else { + return false + } + let top = collection.contentOffset.y + collection.adjustedContentInset.top + let bottom = collection.contentOffset.y + collection.bounds.height - collection.adjustedContentInset.bottom + return frame.maxY > top && frame.minY < bottom + } + + private func rowOffset(_ index: Int, in collection: UICollectionView) -> CGFloat? { + collection.layoutIfNeeded() + guard let frame = collection.layoutAttributesForItem(at: IndexPath(item: index, section: 0))?.frame else { + return nil + } + let top = collection.contentOffset.y + collection.adjustedContentInset.top + return frame.minY - top + } + private func settle(_ condition: () -> Bool) async throws { for _ in 0..<100 { try await Task.sleep(for: .milliseconds(30)) From 88b037df10d5bc22042b431947c82e7857860ec8 Mon Sep 17 00:00:00 2001 From: Ananovo Date: Wed, 16 Sep 2026 07:23:58 +0800 Subject: [PATCH 05/34] docs(guide): document HAPI Markdown math delimiters (#1862) --- docs/guide/agents.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/guide/agents.md b/docs/guide/agents.md index 79fccd3d..79b81b68 100644 --- a/docs/guide/agents.md +++ b/docs/guide/agents.md @@ -54,6 +54,20 @@ hapi resume # Resume a specific HAPI session `hapi resume` reopens the conversation on this machine, including active sessions you were using from your phone. Gemini and fresh-session-only DSH cannot be resumed. Pi and Antigravity resume with input still controlled from HAPI rather than the terminal. +### Mathematical formulas in HAPI Markdown + +HAPI renders LaTeX-style mathematics through KaTeX. When generating or revising Markdown intended for display in HAPI, follow these rules exactly: + +- Use `\( ... \)` for inline mathematics. +- Use `\[ ... \]` for standalone display mathematics. +- Do not use single-dollar delimiters such as `$x^2$`. Single-dollar math is disabled to prevent currency values such as `$200` from being misinterpreted as formulas. +- `$$ ... $$` remains supported for compatibility, but `\[ ... \]` is preferred for display mathematics. +- Do not put formulas inside inline code, fenced code blocks, or other code content. +- Use only LaTeX commands supported by KaTeX. TikZ is not supported. +- Do not use bare `[ ... ]` as math delimiters. + +Before sending a response, check every mathematical expression for the correct delimiters. Rewrite any mathematical `$...$` expression as `\(...\)` or `\[...\]`; preserve ordinary currency text such as `$200` as plain text. + ## Cursor Agent HAPI supports [Cursor Agent CLI](https://cursor.com/docs/cli/using) for running Cursor's AI coding agent with remote control via web and phone. From b11358f333fe7c7fc562081c0fa5cbb6e3441df7 Mon Sep 17 00:00:00 2001 From: Ananovo Date: Wed, 16 Sep 2026 07:25:01 +0800 Subject: [PATCH 06/34] test(ios): assert Scratchlist preview visibility after focus (#1861) --- .../Scratchlist/ScratchlistDrawerView.swift | 23 ++++++++ .../ScratchlistPresentationTests.swift | 54 +++++++++++++++++-- 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/ios/Hapi/Features/Scratchlist/ScratchlistDrawerView.swift b/ios/Hapi/Features/Scratchlist/ScratchlistDrawerView.swift index 9b1ffc95..5435e1a9 100644 --- a/ios/Hapi/Features/Scratchlist/ScratchlistDrawerView.swift +++ b/ios/Hapi/Features/Scratchlist/ScratchlistDrawerView.swift @@ -2,6 +2,22 @@ import HapiClient import HapiProtocol import HapiUI import SwiftUI +import UIKit + +private struct ScratchlistAccessibilityProbe: UIViewRepresentable { + let identifier: String + + func makeUIView(context: Context) -> UIView { + let view = UIView(frame: .zero) + view.accessibilityIdentifier = identifier + view.isAccessibilityElement = false + return view + } + + func updateUIView(_ view: UIView, context: Context) { + view.accessibilityIdentifier = identifier + } +} /// One recent draft while browsing; just a header while typing. struct ScratchlistDrawerView: View { @@ -32,6 +48,13 @@ struct ScratchlistDrawerView: View { onDelete: { model.deleteEntry(entry.entryId) }, compact: true) .padding(.bottom, 8) .accessibilityIdentifier("scratchlist.recent") + // Keep a concrete UIKit node for presentation tests. The + // probe follows the same condition as the visible preview. + .background { + ScratchlistAccessibilityProbe(identifier: "scratchlist.recent") + .frame(width: 1, height: 1) + .allowsHitTesting(false) + } } Divider() } diff --git a/ios/HapiTests/ScratchlistPresentationTests.swift b/ios/HapiTests/ScratchlistPresentationTests.swift index 7db4e908..daf79427 100644 --- a/ios/HapiTests/ScratchlistPresentationTests.swift +++ b/ios/HapiTests/ScratchlistPresentationTests.swift @@ -12,6 +12,36 @@ private struct ScratchlistOfflineHTTP: HTTPPerforming { @MainActor final class ScratchlistPresentationTests: XCTestCase { + private func hasAccessibilityIdentifier(_ identifier: String, in view: UIView) -> Bool { + if view.accessibilityIdentifier == identifier { return true } + if let elements = view.accessibilityElements { + for element in elements { + if let identifiable = element as? UIAccessibilityIdentification, + identifiable.accessibilityIdentifier == identifier { + return true + } + } + } + let elementCount = view.accessibilityElementCount() + if elementCount != NSNotFound { + for index in 0.. ChatInteractor { let url = URL(string: "https://scratchlist.invalid")! let http = ScratchlistOfflineHTTP() @@ -156,8 +186,17 @@ final class ScratchlistPresentationTests: XCTestCase { window.makeKeyAndVisible() defer { window.endEditing(true); window.isHidden = true } try await Task.sleep(for: .milliseconds(250)) - let proposal = CGSize(width: 390, height: 2000) - let browsingHeight = host.sizeThatFits(in: proposal).height + window.layoutIfNeeded() + host.view.layoutIfNeeded() + var hasPreview = hasAccessibilityIdentifier("scratchlist.recent", in: window) + for _ in 0..<50 { + if hasPreview { break } + try await Task.sleep(for: .milliseconds(10)) + window.layoutIfNeeded() + host.view.layoutIfNeeded() + hasPreview = hasAccessibilityIdentifier("scratchlist.recent", in: window) + } + XCTAssertTrue(hasPreview, "The recent Scratchlist preview should be visible before focusing the composer") interactor.focusComposer() func hasFirstResponder(_ view: UIView) -> Bool { view.isFirstResponder || view.subviews.contains(where: hasFirstResponder) @@ -167,8 +206,15 @@ final class ScratchlistPresentationTests: XCTestCase { try await Task.sleep(for: .milliseconds(10)) } XCTAssertTrue(hasFirstResponder(window)) - try await Task.sleep(for: .milliseconds(250)) - XCTAssertLessThan(host.sizeThatFits(in: proposal).height, browsingHeight - 40) + hasPreview = hasAccessibilityIdentifier("scratchlist.recent", in: window) + for _ in 0..<50 { + if !hasPreview { break } + try await Task.sleep(for: .milliseconds(10)) + window.layoutIfNeeded() + host.view.layoutIfNeeded() + hasPreview = hasAccessibilityIdentifier("scratchlist.recent", in: window) + } + XCTAssertFalse(hasPreview, "The recent Scratchlist preview should disappear after focusing the composer") XCTAssertEqual(interactor.composerText, "补充一条回归测试") XCTAssertEqual(interactor.composerDestination, .scratchlist) XCTAssertEqual(interactor.scratchlistCount, 3) From d14683a4b27d4fb6d4b3f7da27691d00bc6d6116 Mon Sep 17 00:00:00 2001 From: admin <33443359+miuiadmin@users.noreply.github.com> Date: Wed, 16 Sep 2026 07:25:52 +0800 Subject: [PATCH 07/34] perf(hub): cache prepared statements and memoize per-socket session access (#1851) --- hub/src/socket/handlers/cli/index.test.ts | 345 ++++++++++++++++++ hub/src/socket/handlers/cli/index.ts | 74 +++- .../socket/handlers/cli/sessionHandlers.ts | 21 +- hub/src/store/messages.ts | 121 +++--- hub/src/store/sessionInvalidation.ts | 17 + hub/src/store/sessions.ts | 44 ++- hub/src/store/statementCache.test.ts | 62 ++++ hub/src/store/statementCache.ts | 39 ++ 8 files changed, 635 insertions(+), 88 deletions(-) create mode 100644 hub/src/socket/handlers/cli/index.test.ts create mode 100644 hub/src/store/sessionInvalidation.ts create mode 100644 hub/src/store/statementCache.test.ts create mode 100644 hub/src/store/statementCache.ts diff --git a/hub/src/socket/handlers/cli/index.test.ts b/hub/src/socket/handlers/cli/index.test.ts new file mode 100644 index 00000000..866ffccf --- /dev/null +++ b/hub/src/socket/handlers/cli/index.test.ts @@ -0,0 +1,345 @@ +import { describe, expect, it, mock } from 'bun:test' +import { Store } from '../../../store' +import type { CliSocketWithData } from '../../socketTypes' +import { registerCliHandlers } from './index' + +class FakeCliSocket { + readonly handlers = new Map void) => void>() + readonly emitted: Array<{ event: string; data: unknown }> = [] + readonly rooms: string[] = [] + data: { namespace?: string } = {} + handshake = { auth: {} as Record } + + on(event: string, handler: (data: unknown, ack?: (response: unknown) => void) => void): this { + this.handlers.set(event, handler) + return this + } + + join(room: string): this { + this.rooms.push(room) + return this + } + + emit(event: string, data: unknown): this { + this.emitted.push({ event, data }) + return this + } + + to(): { emit: (event: string, data: unknown) => void } { + return { emit: () => {} } + } + + trigger(event: string, data: unknown, ack?: (response: unknown) => void): void { + this.handlers.get(event)?.(data, ack) + } +} + +const anyRegistry = new Proxy({}, { get: () => () => {} }) as never +const fakeIo = { of: () => ({ to: () => ({ emit: () => {} }) }) } as never + +describe('cli handler session-access memo', () => { + it('serves repeated events for one session from the per-socket cache', () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('memo-burst', null, null, 'default') + + let byNamespaceCalls = 0 + const original = store.sessions.getSessionByNamespace.bind(store.sessions) + store.sessions.getSessionByNamespace = ((sessionId: string, namespace: string) => { + byNamespaceCalls += 1 + return original(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + const alive = mock() + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store, + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry, + onSessionAlive: alive + }) + + // Burst of events against the same session: one store read, many events. + for (let i = 0; i < 5; i += 1) { + socket.trigger('session-alive', { sid: session.id, time: Date.now() }) + } + expect(alive).toHaveBeenCalledTimes(5) + expect(byNamespaceCalls).toBe(1) + + // A different session id misses the cache. + socket.trigger('session-alive', { sid: 'other-session', time: Date.now() }) + expect(byNamespaceCalls).toBe(2) + store.close() + }) + + it('does not cache denials — every denied event re-resolves', () => { + const store = new Store(':memory:') + let plainCalls = 0 + const original = store.sessions.getSession.bind(store.sessions) + store.sessions.getSession = ((sessionId: string) => { + plainCalls += 1 + return original(sessionId) + }) as typeof store.sessions.getSession + + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store, + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry + }) + + socket.trigger('session-alive', { sid: 'missing', time: Date.now() }) + socket.trigger('session-alive', { sid: 'missing', time: Date.now() }) + expect(plainCalls).toBe(2) + expect(socket.emitted.filter(({ event }) => event === 'error')).toHaveLength(2) + store.close() + }) + + it('expires the memo after the TTL window', async () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('memo-ttl', null, null, 'default') + + let byNamespaceCalls = 0 + const original = store.sessions.getSessionByNamespace.bind(store.sessions) + store.sessions.getSessionByNamespace = ((sessionId: string, namespace: string) => { + byNamespaceCalls += 1 + return original(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store, + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry + }) + + socket.trigger('session-alive', { sid: session.id, time: Date.now() }) + expect(byNamespaceCalls).toBe(1) + + await new Promise((resolve) => setTimeout(resolve, 1100)) + socket.trigger('session-alive', { sid: session.id, time: Date.now() }) + expect(byNamespaceCalls).toBe(2) + store.close() + }) + + it('keeps per-session entries under interleaved multi-session traffic (A-B-A)', () => { + const store = new Store(':memory:') + const a = store.sessions.getOrCreateSession('memo-inter-a', null, null, 'default') + const b = store.sessions.getOrCreateSession('memo-inter-b', null, null, 'default') + + let byNamespaceCalls = 0 + const original = store.sessions.getSessionByNamespace.bind(store.sessions) + store.sessions.getSessionByNamespace = ((sessionId: string, namespace: string) => { + byNamespaceCalls += 1 + return original(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + const alive = mock() + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store, + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry, + onSessionAlive: alive + }) + + // A-B-A interleave within the TTL: a single-slot memo thrashes to a + // miss on every event here (one runner socket multiplexes concurrent + // sessions); the per-session map must resolve each session once. + socket.trigger('session-alive', { sid: a.id, time: Date.now() }) + socket.trigger('session-alive', { sid: b.id, time: Date.now() }) + socket.trigger('session-alive', { sid: a.id, time: Date.now() }) + socket.trigger('session-alive', { sid: b.id, time: Date.now() }) + socket.trigger('session-alive', { sid: a.id, time: Date.now() }) + expect(byNamespaceCalls).toBe(2) + expect(alive).toHaveBeenCalledTimes(5) + store.close() + }) + + it('bounds the cache across many sessions (oldest evicted first)', () => { + const store = new Store(':memory:') + const ids: string[] = [] + for (let i = 0; i < 70; i += 1) { + ids.push(store.sessions.getOrCreateSession(`memo-many-${i}`, null, null, 'default').id) + } + + let byNamespaceCalls = 0 + const original = store.sessions.getSessionByNamespace.bind(store.sessions) + store.sessions.getSessionByNamespace = ((sessionId: string, namespace: string) => { + byNamespaceCalls += 1 + return original(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store, + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry + }) + + for (const id of ids) { + socket.trigger('session-alive', { sid: id, time: Date.now() }) + } + const afterFirstPass = byNamespaceCalls + + // The newest entry is still cached. + socket.trigger('session-alive', { sid: ids[69], time: Date.now() }) + expect(byNamespaceCalls).toBe(afterFirstPass) + + // The oldest entries were evicted once the cache exceeded its cap. + socket.trigger('session-alive', { sid: ids[0], time: Date.now() }) + expect(byNamespaceCalls).toBe(afterFirstPass + 1) + store.close() + }) + + it('update-metadata resolves the session fresh so hub-owned fields survive a warm memo', () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('memo-meta', null, null, 'default') + + let byNamespaceCalls = 0 + const original = store.sessions.getSessionByNamespace.bind(store.sessions) + store.sessions.getSessionByNamespace = ((sessionId: string, namespace: string) => { + byNamespaceCalls += 1 + return original(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store, + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry + }) + + // Warm the memo with a metadata-less snapshot of the session. + socket.trigger('session-alive', { sid: session.id, time: Date.now() }) + expect(byNamespaceCalls).toBe(1) + + // A hub-side write lands the hub-owned key AFTER the memo was warmed. + const hubWrite = store.sessions.updateSessionMetadata( + session.id, + { supersededBySessionId: 'successor' }, + session.metadataVersion, + 'default' + ) + expect(hubWrite.result).toBe('success') + const live = store.sessions.getSession(session.id) + expect(live).not.toBeNull() + + // The client's metadata write omits the hub-owned key. A stale memo + // base (metadata: null) would strip it from the merged row; a fresh + // resolve preserves it from the live row. + let ack: unknown + socket.trigger('update-metadata', { + sid: session.id, + metadata: { title: 'renamed' }, + expectedVersion: live!.metadataVersion + }, (response: unknown) => { ack = response }) + + // The write path bypassed the memo (fresh resolve). + expect(byNamespaceCalls).toBe(2) + expect((ack as { result: string }).result).toBe('success') + + const stored = store.sessions.getSession(session.id) + const metadata = stored!.metadata as Record + expect(metadata.title).toBe('renamed') + expect(metadata.supersededBySessionId).toBe('successor') + store.close() + }) + + it('drops the memo as soon as the session is deleted (deletion epoch)', () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('memo-del', null, null, 'default') + + let byNamespaceCalls = 0 + const original = store.sessions.getSessionByNamespace.bind(store.sessions) + store.sessions.getSessionByNamespace = ((sessionId: string, namespace: string) => { + byNamespaceCalls += 1 + return original(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store, + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry + }) + + // Warm the memo. + socket.trigger('session-alive', { sid: session.id, time: Date.now() }) + expect(byNamespaceCalls).toBe(1) + + // Hub-side delete (webapp API, session merge — every path funnels + // through the store's deleteSession). + expect(store.sessions.deleteSession(session.id, 'default')).toBe(true) + + // Well inside the TTL, the next event must not be served from the + // memo: the deletion bumped the epoch, forcing a fresh resolve that + // denies instead of authorizing events against the deleted row. + socket.trigger('session-alive', { sid: session.id, time: Date.now() }) + expect(byNamespaceCalls).toBe(2) + expect(socket.emitted.filter(({ event }) => event === 'error')).toHaveLength(1) + store.close() + }) + + it('native-queue-message reads live capabilities, not a memo snapshot', () => { + const store = new Store(':memory:') + const session = store.sessions.getOrCreateSession('memo-queue', null, null, 'default') + + let byNamespaceCalls = 0 + const original = store.sessions.getSessionByNamespace.bind(store.sessions) + store.sessions.getSessionByNamespace = ((sessionId: string, namespace: string) => { + byNamespaceCalls += 1 + return original(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + const socket = new FakeCliSocket() + socket.data = { namespace: 'default' } + const onWebappEvent = mock() + registerCliHandlers(socket as unknown as CliSocketWithData, { + io: fakeIo, + store, + rpcRegistry: anyRegistry, + terminalRegistry: anyRegistry, + onWebappEvent + }) + + // Warm the memo while the session has no capabilities. + socket.trigger('session-alive', { sid: session.id, time: Date.now() }) + expect(byNamespaceCalls).toBe(1) + + // Capabilities land via a metadata write (hub side, e.g. a merge + // copying capabilities onto the session). + const write = store.sessions.updateSessionMetadata( + session.id, + { capabilities: { concurrentClients: true } }, + session.metadataVersion, + 'default' + ) + expect(write.result).toBe('success') + + // Within the TTL a memo snapshot would still see capabilities as + // absent and silently drop the queued entry; the fresh read + // processes it. + socket.trigger('native-queue-message', { sid: session.id, localId: 'q1', text: 'queued hello' }) + expect(byNamespaceCalls).toBe(2) + + const received = onWebappEvent.mock.calls + .map(([event]) => event as { type: string }) + .find((event) => event.type === 'message-received') + expect(received).toBeDefined() + store.close() + }) +}) diff --git a/hub/src/socket/handlers/cli/index.ts b/hub/src/socket/handlers/cli/index.ts index f39b510c..72e7cf47 100644 --- a/hub/src/socket/handlers/cli/index.ts +++ b/hub/src/socket/handlers/cli/index.ts @@ -9,6 +9,7 @@ import { registerMachineHandlers } from './machineHandlers' import { registerRpcHandlers } from './rpcHandlers' import { registerSessionHandlers } from './sessionHandlers' import { cleanupTerminalHandlers, registerTerminalHandlers } from './terminalHandlers' +import { sessionDeletionEpoch } from '../../../store/sessionInvalidation' type SessionAlivePayload = { sid: string @@ -53,23 +54,84 @@ export type CliHandlersDeps = { onMessagesConsumed?: (sessionId: string) => void } +// resolveSessionAccess runs on EVERY cli socket event (message stream deltas, +// keep-alives, consumed acks, terminal output) as the authorization gate. A +// streaming CLI emits dozens of events per second against the same session, +// and each uncached resolution costs a fresh prepared SELECT + metadata JSON +// parse — the dominant hub CPU cost under sustained event traffic (profiled: +// ~40% of a saturated event loop). Positive resolutions for a given session +// are memoized per-socket for this window. Denials stay uncached so clients +// see a fresh outcome on every event while a rename/namespace switch settles. +// The cache is keyed by session id, not a single slot: one runner socket +// multiplexes MANY concurrent sessions (agents driving parallel sessions on +// the same machine), and their events interleave. A single-slot memo thrashes +// to a miss on every event under that interleaving — profiled as seconds-long +// event-loop saturation while message floods alternate session ids — so the +// memo must survive A-B-A event sequences. Bounded by MAX_SESSIONS with +// expired-first then oldest-first eviction (Map preserves insertion order). +// The cached fields callers consume are effectively immutable for a session id +// (namespace) or tolerant of ≤1s staleness (metadata), so the bounded window +// cannot change an access decision that would otherwise differ. +// +// Deletion is the one mutation the TTL window cannot absorb: a memoized grant +// would keep authorizing events (and FK-failing writes) against a row that no +// longer exists. deleteSession bumps a process-wide monotonic epoch; entries +// stamp the epoch they were filled under, and a mismatch forces one +// re-resolve on the next event — an integer compare on the hit path, no DB +// read. Bumps are rare, so the amortized cost is negligible. +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, onWebappEvent, onBackgroundTaskDelta, onSessionActivity, onSweepImmediateQueued, onMessagesConsumed } = deps const terminalNamespace = io.of('/terminal') const namespace = typeof socket.data.namespace === 'string' ? socket.data.namespace : null - const resolveSessionAccess = (sessionId: string): AccessResult => { + const sessionAccessCache = new Map; expiresAt: number; epoch: number }>() + + const resolveSessionAccess = (sessionId: string, opts?: { fresh?: boolean }): AccessResult => { if (!namespace) { return { ok: false, reason: 'namespace-missing' } } + const now = Date.now() + // `fresh` bypasses the memo read. Callers that use the resolved + // session as a write base (e.g. preserving hub-owned metadata keys) + // must merge against the live row, not a ≤TTL-stale snapshot — a + // stale base would drop a concurrently-set hub-owned key or + // resurrect a concurrently-cleared one. A fresh read still + // write-throughs the cache. + if (!opts?.fresh) { + const cached = sessionAccessCache.get(sessionId) + if (cached && cached.expiresAt > now && cached.epoch === sessionDeletionEpoch()) { + return cached.access + } + } const session = store.sessions.getSessionByNamespace(sessionId, namespace) + let access: AccessResult if (session) { - return { ok: true, value: session } + access = { ok: true, value: session } + sessionAccessCache.set(sessionId, { access, expiresAt: now + SESSION_ACCESS_CACHE_TTL_MS, epoch: sessionDeletionEpoch() }) + if (sessionAccessCache.size > SESSION_ACCESS_CACHE_MAX_SESSIONS) { + for (const [key, entry] of sessionAccessCache) { + if (entry.expiresAt <= now) { + sessionAccessCache.delete(key) + } + } + while (sessionAccessCache.size > SESSION_ACCESS_CACHE_MAX_SESSIONS) { + const oldest = sessionAccessCache.keys().next().value + if (oldest === undefined) break + sessionAccessCache.delete(oldest) + } + } + } else { + sessionAccessCache.delete(sessionId) + if (store.sessions.getSession(sessionId)) { + access = { ok: false, reason: 'access-denied' } + } else { + access = { ok: false, reason: 'not-found' } + } } - if (store.sessions.getSession(sessionId)) { - return { ok: false, reason: 'access-denied' } - } - return { ok: false, reason: 'not-found' } + return access } const resolveMachineAccess = (machineId: string): AccessResult => { diff --git a/hub/src/socket/handlers/cli/sessionHandlers.ts b/hub/src/socket/handlers/cli/sessionHandlers.ts index b15e5f34..1fcb7ab7 100644 --- a/hub/src/socket/handlers/cli/sessionHandlers.ts +++ b/hub/src/socket/handlers/cli/sessionHandlers.ts @@ -39,7 +39,7 @@ type SessionReadyPayload = { time: number } -type ResolveSessionAccess = (sessionId: string) => AccessResult +type ResolveSessionAccess = (sessionId: string, opts?: { fresh?: boolean }) => AccessResult type EmitAccessError = (scope: 'session' | 'machine', id: string, reason: AccessErrorReason) => void @@ -107,7 +107,12 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session const parsed = z.object({ sid: z.string(), localId: z.string().min(1), text: z.string().nullable() }).safeParse(data) if (!parsed.success) return const { sid, localId, text } = parsed.data - const access = resolveSessionAccess(sid) + // Fresh resolve: the capabilities gate below decides whether the + // queue ledger is written, and capabilities can change via metadata + // writes (e.g. a merge copying capabilities onto this session) — a + // memo snapshot could silently drop or wrongly accept the entry. + // Queued input is human-paced, not a stream hot path. + const access = resolveSessionAccess(sid, { fresh: true }) if (!access.ok) { emitAccessError('session', sid, access.reason); return } const metadata = access.value.metadata as Metadata | null if (!metadata?.capabilities?.concurrentClients) return @@ -259,7 +264,11 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session } const { sid, metadata, expectedVersion } = parsed.data - const sessionAccess = resolveSessionAccess(sid) + // Fresh resolve: preserveHubOwnedMetadata below merges against + // sessionAccess.value.metadata, so the base must be the live row. + // A memo-stale base would drop a concurrently-set hub-owned key or + // resurrect a concurrently-cleared one in this very write. + const sessionAccess = resolveSessionAccess(sid, { fresh: true }) if (!sessionAccess.ok) { cb({ result: 'error', reason: sessionAccess.reason }) return @@ -506,7 +515,11 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session if (!data || typeof data.sid !== 'string' || typeof data.time !== 'number') { return } - const sessionAccess = resolveSessionAccess(data.sid) + // Fresh resolve: the shared-Codex capability gate below decides + // whether the queue ledger is swept, and capabilities can change via + // metadata writes. Session end fires once per session — not a hot + // path — so read the live row rather than a memo snapshot. + const sessionAccess = resolveSessionAccess(data.sid, { fresh: true }) if (!sessionAccess.ok) { emitAccessError('session', data.sid, sessionAccess.reason) return diff --git a/hub/src/store/messages.ts b/hub/src/store/messages.ts index eb8ae62b..56bc0944 100644 --- a/hub/src/store/messages.ts +++ b/hub/src/store/messages.ts @@ -1,4 +1,5 @@ import type { Database } from 'bun:sqlite' +import { prepareCached } from './statementCache' import { randomUUID } from 'node:crypto' import { isDeepStrictEqual } from 'node:util' import { z } from 'zod' @@ -42,7 +43,7 @@ export function addImportedMessage( localId: string, createdAt: number ): { message: StoredMessage; inserted: boolean } { - const existing = db.prepare( + const existing = prepareCached(db, 'SELECT * FROM messages WHERE session_id = ? AND local_id = ? LIMIT 1' ).get(sessionId, localId) as DbMessageRow | undefined if (existing) { @@ -56,11 +57,11 @@ export function addImportedMessage( const stampedAt = Number.isFinite(createdAt) ? Math.min(createdAt, now) : now return db.transaction(() => { const previousHead = getNewestMessagePosition(db, sessionId) - const msgSeqRow = db.prepare( + const msgSeqRow = prepareCached(db, 'SELECT COALESCE(MAX(seq), 0) + 1 AS nextSeq FROM messages WHERE session_id = ?' ).get(sessionId) as { nextSeq: number } const id = randomUUID() - db.prepare(` + prepareCached(db, ` INSERT INTO messages ( id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at ) VALUES ( @@ -76,7 +77,7 @@ export function addImportedMessage( invoked_at: stampedAt }) if (previousHead && stampedAt < previousHead.at) bumpMessageEpoch(db, sessionId) - const row = db.prepare('SELECT * FROM messages WHERE id = ?').get(id) as DbMessageRow | undefined + const row = prepareCached(db, 'SELECT * FROM messages WHERE id = ?').get(id) as DbMessageRow | undefined if (!row) throw new Error('Failed to create imported message') return { message: toStoredMessage(row), inserted: true } })() @@ -127,7 +128,7 @@ export function addMessage( } if (localId) { - const existing = db.prepare( + const existing = prepareCached(db, 'SELECT * FROM messages WHERE session_id = ? AND local_id = ? LIMIT 1' ).get(sessionId, localId) as DbMessageRow | undefined if (existing) { @@ -135,7 +136,7 @@ export function addMessage( } } - const msgSeqRow = db.prepare( + const msgSeqRow = prepareCached(db, 'SELECT COALESCE(MAX(seq), 0) + 1 AS nextSeq FROM messages WHERE session_id = ?' ).get(sessionId) as { nextSeq: number } const msgSeq = msgSeqRow.nextSeq @@ -153,7 +154,7 @@ export function addMessage( return db.transaction(() => { const previousHead = getNewestMessagePosition(db, sessionId) - db.prepare(` + prepareCached(db, ` INSERT INTO messages ( id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at ) VALUES ( @@ -172,7 +173,7 @@ export function addMessage( const positionAt = invokedAt ?? stampedAt if (previousHead && positionAt < previousHead.at) bumpMessageEpoch(db, sessionId) - const row = db.prepare('SELECT * FROM messages WHERE id = ?').get(id) as DbMessageRow | undefined + const row = prepareCached(db, 'SELECT * FROM messages WHERE id = ?').get(id) as DbMessageRow | undefined if (!row) throw new Error('Failed to create message') return toStoredMessage(row) })() @@ -188,7 +189,7 @@ export function syncNativeQueuedMessage(db: Database, sessionId: string, localId const prior = z.object({ role: z.literal('user'), content: z.object({ type: z.literal('text') }).passthrough() }).passthrough().safeParse(message.content) const content = prior.success ? { ...prior.data, content: { ...prior.data.content, text } } : initial const encoded = encodeMessageContent(truncateOversizedMessageContent(content)) - db.prepare('UPDATE messages SET content = ? WHERE session_id = ? AND local_id = ? AND invoked_at IS NULL') + prepareCached(db, 'UPDATE messages SET content = ? WHERE session_id = ? AND local_id = ? AND invoked_at IS NULL') .run(encoded, sessionId, localId) return { ...message, content } })() @@ -204,7 +205,7 @@ export function copyMessageToSession( let localId = message.localId if (localId) { - const collision = db.prepare( + const collision = prepareCached(db, 'SELECT 1 FROM messages WHERE session_id = ? AND local_id = ? LIMIT 1' ).get(sessionId, localId) as { 1: number } | undefined if (collision) { @@ -220,7 +221,7 @@ export function copyMessageToSession( const invokedAt = localId ? message.invokedAt : (message.invokedAt ?? createdAt) const id = randomUUID() - db.prepare(` + prepareCached(db, ` INSERT INTO messages ( id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at, delivery_state ) VALUES ( @@ -240,7 +241,7 @@ export function copyMessageToSession( delivery_state: message.deliveryState ?? 'queued' }) - const row = db.prepare('SELECT * FROM messages WHERE id = ?').get(id) as DbMessageRow | undefined + const row = prepareCached(db, 'SELECT * FROM messages WHERE id = ?').get(id) as DbMessageRow | undefined if (!row) { throw new Error('Failed to copy message into target session') } @@ -265,14 +266,14 @@ export function copyMessagesToSession( return db.transaction(() => { let nextSeq = getMaxSeq(db, sessionId) + 1 - const insert = db.prepare(` + const insert = prepareCached(db, ` INSERT INTO messages ( id, session_id, content, created_at, 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 ) `) - const collisionCheck = db.prepare( + const collisionCheck = prepareCached(db, 'SELECT 1 FROM messages WHERE session_id = ? AND local_id = ? LIMIT 1' ) @@ -315,7 +316,7 @@ export function getMessages( ): StoredMessage[] { const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.min(200, limit)) : 200 - const rows = db.prepare( + const rows = prepareCached(db, 'SELECT * FROM messages WHERE session_id = ? ORDER BY seq DESC LIMIT ?' ).all(sessionId, safeLimit) as DbMessageRow[] @@ -326,7 +327,7 @@ export function getAllMessages( db: Database, sessionId: string ): StoredMessage[] { - const rows = db.prepare( + const rows = prepareCached(db, 'SELECT * FROM messages WHERE session_id = ? ORDER BY seq ASC' ).all(sessionId) as DbMessageRow[] @@ -338,7 +339,7 @@ export function getMessagesAfterSeq( sessionId: string, afterSeq: number ): StoredMessage[] { - const rows = db.prepare( + const rows = prepareCached(db, 'SELECT * FROM messages WHERE session_id = ? AND seq > ? ORDER BY seq ASC' ).all(sessionId, afterSeq) as DbMessageRow[] @@ -351,7 +352,7 @@ export function getMessageSeqById( sessionId: string, messageId: string ): number | null { - const row = db.prepare( + const row = prepareCached(db, 'SELECT seq FROM messages WHERE id = ? AND session_id = ?' ).get(messageId, sessionId) as { seq: number } | undefined return row ? row.seq : null @@ -364,7 +365,7 @@ export function getFirstMessages( ): StoredMessage[] { const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.min(200, limit)) : 50 - const rows = db.prepare( + const rows = prepareCached(db, 'SELECT * FROM messages WHERE session_id = ? ORDER BY seq ASC LIMIT ?' ).all(sessionId, safeLimit) as DbMessageRow[] @@ -389,7 +390,7 @@ export function getDeliverableMessagesAfter( const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.min(200, limit)) : 200 const safeAfterSeq = Number.isFinite(afterSeq) ? afterSeq : 0 - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT * FROM messages WHERE session_id = ? AND seq > ? @@ -425,7 +426,7 @@ export function deleteLiveReasoningSnapshots( streamId: string, keepMessageId?: string ): number { - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT id, content FROM messages WHERE session_id = ? ORDER BY seq DESC @@ -439,7 +440,7 @@ export function deleteLiveReasoningSnapshots( if (staleIds.length === 0) return 0 const placeholders = staleIds.map(() => '?').join(', ') - const result = db.prepare( + const result = prepareCached(db, `DELETE FROM messages WHERE session_id = ? AND id IN (${placeholders})` ).run(sessionId, ...staleIds) return Number(result.changes) @@ -457,7 +458,7 @@ export function getMessagesByPosition( const beforeClause = before ? 'AND (COALESCE(invoked_at, created_at) < @beforeAt OR (COALESCE(invoked_at, created_at) = @beforeAt AND seq < @beforeSeq))' : '' - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT *, COALESCE(invoked_at, created_at) AS position_at FROM messages WHERE session_id = @sessionId @@ -491,7 +492,7 @@ export function getMessagesAfterPosition( OR (COALESCE(invoked_at, created_at) = @untilAt AND seq <= @untilSeq) )` : '' - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT *, COALESCE(invoked_at, created_at) AS position_at FROM messages WHERE session_id = @sessionId @@ -514,7 +515,7 @@ export function getMessagesAfterPosition( } export function getNewestMessagePosition(db: Database, sessionId: string): MessagePosition | null { - const row = db.prepare(` + const row = prepareCached(db, ` SELECT COALESCE(invoked_at, created_at) AS position_at, seq FROM messages WHERE session_id = ? @@ -525,14 +526,14 @@ export function getNewestMessagePosition(db: Database, sessionId: string): Messa } export function getMessageEpoch(db: Database, sessionId: string): number { - const row = db.prepare( + const row = prepareCached(db, 'SELECT epoch FROM message_epochs WHERE session_id = ?' ).get(sessionId) as { epoch: number } | undefined return row?.epoch ?? 0 } export function bumpMessageEpoch(db: Database, sessionId: string): number { - db.prepare(` + prepareCached(db, ` INSERT INTO message_epochs (session_id, epoch) VALUES (?, 1) ON CONFLICT(session_id) DO UPDATE SET epoch = epoch + 1 @@ -549,7 +550,7 @@ export function getUninvokedLocalMessages( options?: { deliverableOnly?: boolean } ): StoredMessage[] { const deliverableClause = options?.deliverableOnly ? " AND delivery_state = 'queued'" : '' - const rows = db.prepare( + const rows = prepareCached(db, `SELECT * FROM messages WHERE session_id = ? AND invoked_at IS NULL AND local_id IS NOT NULL${deliverableClause} ORDER BY seq ASC` ).all(sessionId) as DbMessageRow[] return rows.map(toStoredMessage) @@ -570,7 +571,7 @@ export function getLocalMessageStates( return [] } const placeholders = localIds.map(() => '?').join(', ') - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT local_id, invoked_at, delivery_state FROM messages WHERE session_id = ? AND local_id IN (${placeholders}) @@ -596,7 +597,7 @@ export function getMatureScheduledMessages( db: Database, beforeTime: number ): StoredMessage[] { - const rows = db.prepare( + const rows = prepareCached(db, "SELECT * FROM messages WHERE scheduled_at IS NOT NULL AND scheduled_at <= ? AND invoked_at IS NULL AND delivery_state = 'queued' ORDER BY scheduled_at ASC" ).all(beforeTime) as DbMessageRow[] return rows.map(toStoredMessage) @@ -619,7 +620,7 @@ export function getImmediateQueuedLocalMessages( db: Database, sessionId: string ): StoredMessage[] { - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT * FROM messages WHERE session_id = ? AND invoked_at IS NULL @@ -640,7 +641,7 @@ export function getImmediateQueuedLocalMessages( * tiann/hapi#872. */ export function countMessages(db: Database, sessionId: string): number { - const row = db.prepare( + const row = prepareCached(db, 'SELECT COUNT(*) AS count FROM messages WHERE session_id = ?' ).get(sessionId) as { count: number } | undefined return row?.count ?? 0 @@ -652,7 +653,7 @@ export function countFutureScheduledLocalMessages( sessionId: string, now: number ): number { - const row = db.prepare(` + const row = prepareCached(db, ` SELECT COUNT(*) AS count FROM messages WHERE session_id = ? @@ -677,7 +678,7 @@ export function countFutureScheduledBySessionIds( } const placeholders = sessionIds.map(() => '?').join(',') - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT session_id, COUNT(*) AS count FROM messages WHERE session_id IN (${placeholders}) @@ -707,7 +708,7 @@ export function minFutureScheduledAtBySessionIds( } const placeholders = sessionIds.map(() => '?').join(',') - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT session_id, MIN(scheduled_at) AS next_at FROM messages WHERE session_id IN (${placeholders}) @@ -726,7 +727,7 @@ export function minFutureScheduledAtBySessionIds( } export function getMaxSeq(db: Database, sessionId: string): number { - const row = db.prepare( + const row = prepareCached(db, 'SELECT COALESCE(MAX(seq), 0) AS maxSeq FROM messages WHERE session_id = ?' ).get(sessionId) as { maxSeq: number } | undefined return row?.maxSeq ?? 0 @@ -760,7 +761,7 @@ export function cancelQueuedMessage( // Note: local_id = ? evaluates to NULL (no match) when local_id IS NULL, // which is safe — messages without a localId are inserted with invoked_at set // and are never queued, so they cannot reach this code path anyway. - const row = db.prepare(` + const row = prepareCached(db, ` SELECT * FROM messages WHERE session_id = ? AND (id = ? OR local_id = ?) LIMIT 1 @@ -778,7 +779,7 @@ export function cancelQueuedMessage( return { status: 'invoked' as const, message: toStoredMessage(row) } } - const deleted = db.prepare(` + const deleted = prepareCached(db, ` DELETE FROM messages WHERE session_id = ? AND (id = ? OR local_id = ?) AND invoked_at IS NULL `).run(sessionId, messageId, messageId) @@ -812,7 +813,7 @@ export function lookupQueuedMessage( sessionId: string, messageId: string ): LookupQueuedMessageResult { - const row = db.prepare(` + const row = prepareCached(db, ` SELECT * FROM messages WHERE session_id = ? AND (id = ? OR local_id = ?) LIMIT 1 @@ -848,7 +849,7 @@ export function claimIndeterminateMessage( messageId: string ): StoredMessage | null { return db.transaction(() => { - const claimed = db.prepare(` + const claimed = prepareCached(db, ` UPDATE messages SET delivery_state = 'dispatching' WHERE session_id = ? @@ -857,7 +858,7 @@ export function claimIndeterminateMessage( AND delivery_state = 'indeterminate' `).run(sessionId, messageId, messageId) if (claimed.changes === 0) return null - const updated = db.prepare(` + const updated = prepareCached(db, ` SELECT * FROM messages WHERE session_id = ? AND (id = ? OR local_id = ?) AND invoked_at IS NULL @@ -874,7 +875,7 @@ export function deleteQueuedMessageById( messageId: string ): boolean { return db.transaction(() => { - const deleted = db.prepare(` + const deleted = prepareCached(db, ` DELETE FROM messages WHERE session_id = ? AND (id = ? OR local_id = ?) AND invoked_at IS NULL `).run(sessionId, messageId, messageId) @@ -899,7 +900,7 @@ export function markMessagesInvoked( ): number { if (localIds.length === 0) return 0 const placeholders = localIds.map(() => '?').join(', ') - return db.prepare( + return prepareCached(db, `UPDATE messages SET invoked_at = ?, delivery_state = 'queued' WHERE session_id = ? @@ -922,7 +923,7 @@ export function setMessagesDeliveryState( : state === 'dispatching' ? "'queued', 'indeterminate'" : "'queued', 'dispatching'" - return db.prepare( + return prepareCached(db, `UPDATE messages SET delivery_state = ? WHERE session_id = ? @@ -948,7 +949,7 @@ export function markUninvokedImmediateMessages( sessionId: string, invokedAt: number ): string[] { - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT local_id FROM messages WHERE session_id = ? AND local_id IS NOT NULL @@ -959,7 +960,7 @@ export function markUninvokedImmediateMessages( `).all(sessionId) as Array<{ local_id: string }> if (rows.length === 0) return [] - db.prepare(` + prepareCached(db, ` UPDATE messages SET invoked_at = ? WHERE session_id = ? @@ -983,7 +984,7 @@ export function moveUninvokedScheduledMessages( ): number { if (fromSessionId === toSessionId) return 0 - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT id FROM messages WHERE session_id = ? AND scheduled_at IS NOT NULL @@ -995,7 +996,7 @@ export function moveUninvokedScheduledMessages( try { db.exec('BEGIN') let nextSeq = getMaxSeq(db, toSessionId) - const update = db.prepare('UPDATE messages SET session_id = ?, seq = ? WHERE id = ?') + const update = prepareCached(db, 'UPDATE messages SET session_id = ?, seq = ? WHERE id = ?') for (const row of rows) { nextSeq += 1 update.run(toSessionId, nextSeq, row.id) @@ -1019,7 +1020,7 @@ export function moveUninvokedScheduledMessages( export function moveUninvokedMessages(db: Database, fromSessionId: string, toSessionId: string): number { if (fromSessionId === toSessionId) return 0 return db.transaction(() => { - const discarded = db.prepare(` + const discarded = prepareCached(db, ` DELETE FROM messages WHERE session_id = ? AND invoked_at IS NULL @@ -1030,7 +1031,7 @@ export function moveUninvokedMessages(db: Database, fromSessionId: string, toSes AND target.local_id = messages.local_id ) `).run(fromSessionId, toSessionId).changes - const rows = db.prepare(` + const rows = prepareCached(db, ` SELECT id, session_id FROM messages WHERE session_id IN (?, ?) AND invoked_at IS NULL -- created_at is millisecond-granularity; rowid is the durable @@ -1042,12 +1043,12 @@ export function moveUninvokedMessages(db: Database, fromSessionId: string, toSes `).all(fromSessionId, toSessionId) as Array<{ id: string; session_id: string }> const moved = rows.filter((row) => row.session_id === fromSessionId).length if (discarded === 0 && moved === 0) return 0 - const invokedMax = db.prepare(` + const invokedMax = prepareCached(db, ` SELECT COALESCE(MAX(seq), 0) AS maxSeq FROM messages WHERE session_id = ? AND invoked_at IS NOT NULL `).get(toSessionId) as { maxSeq: number } let nextSeq = invokedMax.maxSeq - const update = db.prepare('UPDATE messages SET session_id = ?, seq = ? WHERE id = ?') + const update = prepareCached(db, 'UPDATE messages SET session_id = ?, seq = ? WHERE id = ?') for (const row of rows) update.run(toSessionId, ++nextSeq, row.id) bumpMessageEpoch(db, fromSessionId) bumpMessageEpoch(db, toSessionId) @@ -1071,12 +1072,12 @@ export function mergeSessionMessages( db.exec('BEGIN') if (newMaxSeq > 0 && oldMaxSeq > 0) { - db.prepare( + prepareCached(db, 'UPDATE messages SET seq = seq + ? WHERE session_id = ?' ).run(oldMaxSeq, toSessionId) } - const collisions = db.prepare(` + const collisions = prepareCached(db, ` SELECT local_id FROM messages WHERE session_id = ? AND local_id IS NOT NULL INTERSECT @@ -1091,7 +1092,7 @@ 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. - db.prepare( + prepareCached(db, `UPDATE messages SET local_id = NULL, invoked_at = COALESCE(invoked_at, created_at) @@ -1099,7 +1100,7 @@ export function mergeSessionMessages( ).run(fromSessionId, ...localIds) } - const result = db.prepare( + const result = prepareCached(db, 'UPDATE messages SET session_id = ? WHERE session_id = ?' ).run(toSessionId, fromSessionId) @@ -1133,7 +1134,7 @@ export function truncateMessagesFromLocalId( }> = [] ): { deleted: number; inserted: number; epoch: number } { return db.transaction(() => { - const target = db.prepare(` + const target = prepareCached(db, ` SELECT id, seq, COALESCE(invoked_at, created_at) AS position_at FROM messages WHERE session_id = ? AND local_id = ? @@ -1144,7 +1145,7 @@ export function truncateMessagesFromLocalId( throw new Error(`Message not found for localId: ${localId}`) } - const deleted = db.prepare(` + const deleted = prepareCached(db, ` DELETE FROM messages WHERE session_id = ? AND ( @@ -1156,14 +1157,14 @@ export function truncateMessagesFromLocalId( let inserted = 0 for (const message of replacement) { const now = Date.now() - const msgSeqRow = db.prepare( + const msgSeqRow = prepareCached(db, 'SELECT COALESCE(MAX(seq), 0) + 1 AS nextSeq FROM messages WHERE session_id = ?' ).get(sessionId) as { nextSeq: number } const id = randomUUID() const createdAt = message.createdAt ?? now const invokedAt = message.invokedAt === undefined ? createdAt : message.invokedAt const rowLocalId = message.localId ?? null - db.prepare(` + prepareCached(db, ` INSERT INTO messages (id, session_id, content, created_at, seq, local_id, invoked_at, scheduled_at) VALUES (?, ?, ?, ?, ?, ?, ?, NULL) `).run( diff --git a/hub/src/store/sessionInvalidation.ts b/hub/src/store/sessionInvalidation.ts new file mode 100644 index 00000000..cf3b6606 --- /dev/null +++ b/hub/src/store/sessionInvalidation.ts @@ -0,0 +1,17 @@ +// Process-wide monotonic epoch bumped whenever a session row is deleted. +// +// Per-socket session-access memos (socket/handlers/cli) stamp the epoch they +// were filled under and re-resolve on mismatch, so a deletion takes effect on +// the very next event instead of after the memo TTL — inside that window a +// stale grant would keep authorizing events (and FK-failing writes) against a +// row that no longer exists. Reading the epoch is a single integer compare; +// bumps are rare (user-initiated deletes, session merges). +let epoch = 0 + +export function bumpSessionDeletionEpoch(): void { + epoch += 1 +} + +export function sessionDeletionEpoch(): number { + return epoch +} diff --git a/hub/src/store/sessions.ts b/hub/src/store/sessions.ts index c0d23236..8d2ad418 100644 --- a/hub/src/store/sessions.ts +++ b/hub/src/store/sessions.ts @@ -1,4 +1,6 @@ import type { Database } from 'bun:sqlite' +import { prepareCached } from './statementCache' +import { bumpSessionDeletionEpoch } from './sessionInvalidation' import { randomUUID } from 'node:crypto' import type { StoredSession, VersionedUpdateResult } from './types' @@ -197,7 +199,7 @@ export function getOrCreateSession( modelReasoningEffort?: string, requestedId?: string ): StoredSession { - const existing = db.prepare( + const existing = prepareCached(db, 'SELECT * FROM sessions WHERE tag = ? AND namespace = ? ORDER BY created_at DESC LIMIT 1' ).get(tag, namespace) as DbSessionRow | undefined @@ -224,7 +226,7 @@ export function getOrCreateSession( const metadataJson = JSON.stringify(metadata) const agentStateJson = agentState === null || agentState === undefined ? null : JSON.stringify(agentState) - db.prepare(` + prepareCached(db, ` INSERT INTO sessions ( id, tag, namespace, machine_id, created_at, updated_at, metadata, metadata_version, @@ -287,7 +289,7 @@ export function updateSessionMetadata( try { return db.transaction((): VersionedUpdateResult => { - const priorRow = db.prepare( + const priorRow = prepareCached(db, 'SELECT metadata FROM sessions WHERE id = ? AND namespace = ?' ).get(id, namespace) as { metadata: string | null } | undefined @@ -358,7 +360,7 @@ export function setSessionTodos( ): boolean { try { const json = todos === null || todos === undefined ? null : JSON.stringify(todos) - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET todos = @todos, todos_updated_at = @todos_updated_at, @@ -402,7 +404,7 @@ export function replaceSessionTodos( try { const json = todos === null || todos === undefined ? null : JSON.stringify(todos) const now = Date.now() - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET todos = @todos, todos_updated_at = CASE @@ -434,7 +436,7 @@ export function setSessionTeamState( ): boolean { try { const json = teamState === null || teamState === undefined ? null : JSON.stringify(teamState) - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET team_state = @team_state, team_state_updated_at = @team_state_updated_at, @@ -468,7 +470,7 @@ export function setSessionModel( const touchUpdatedAt = options?.touchUpdatedAt === true try { - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET model = @model, updated_at = CASE WHEN @touch_updated_at = 1 THEN @updated_at ELSE updated_at END, @@ -501,7 +503,7 @@ export function setSessionModelReasoningEffort( const touchUpdatedAt = options?.touchUpdatedAt === true try { - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET model_reasoning_effort = @model_reasoning_effort, updated_at = CASE WHEN @touch_updated_at = 1 THEN @updated_at ELSE updated_at END, @@ -534,7 +536,7 @@ export function setSessionServiceTier( const touchUpdatedAt = options?.touchUpdatedAt === true try { - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET service_tier = @service_tier, updated_at = CASE WHEN @touch_updated_at = 1 THEN @updated_at ELSE updated_at END, @@ -567,7 +569,7 @@ export function setSessionEffort( const touchUpdatedAt = options?.touchUpdatedAt === true try { - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET effort = @effort, updated_at = CASE WHEN @touch_updated_at = 1 THEN @updated_at ELSE updated_at END, @@ -597,7 +599,7 @@ export function setSessionActive( namespace: string ): boolean { try { - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET active = @active, active_at = CASE @@ -626,7 +628,7 @@ export type SessionPinMode = 'none' | 'project' | 'global' export function setSessionPinMode(db: Database, id: string, mode: SessionPinMode, namespace: string): boolean { const pinned = mode === 'project' ? 1 : 0 const globalPinned = mode === 'global' ? 1 : 0 - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET pinned = @pinned, global_pinned = @global_pinned @@ -649,7 +651,7 @@ export function touchSessionUpdatedAt( namespace: string ): boolean { try { - const result = db.prepare(` + const result = prepareCached(db, ` UPDATE sessions SET updated_at = @updated_at, seq = seq + 1 @@ -669,32 +671,38 @@ export function touchSessionUpdatedAt( } export function getSession(db: Database, id: string): StoredSession | null { - const row = db.prepare('SELECT * FROM sessions WHERE id = ?').get(id) as DbSessionRow | undefined + const row = prepareCached(db, 'SELECT * FROM sessions WHERE id = ?').get(id) as DbSessionRow | undefined return row ? toStoredSession(row) : null } export function getSessionByNamespace(db: Database, id: string, namespace: string): StoredSession | null { - const row = db.prepare( + const row = prepareCached(db, 'SELECT * FROM sessions WHERE id = ? AND namespace = ?' ).get(id, namespace) as DbSessionRow | undefined return row ? toStoredSession(row) : null } export function getSessions(db: Database): StoredSession[] { - const rows = db.prepare('SELECT * FROM sessions ORDER BY updated_at DESC').all() as DbSessionRow[] + const rows = prepareCached(db, 'SELECT * FROM sessions ORDER BY updated_at DESC').all() as DbSessionRow[] return rows.map(toStoredSession) } export function getSessionsByNamespace(db: Database, namespace: string): StoredSession[] { - const rows = db.prepare( + const rows = prepareCached(db, 'SELECT * FROM sessions WHERE namespace = ? ORDER BY updated_at DESC' ).all(namespace) as DbSessionRow[] return rows.map(toStoredSession) } export function deleteSession(db: Database, id: string, namespace: string): boolean { - const result = db.prepare( + const result = prepareCached(db, 'DELETE FROM sessions WHERE id = ? AND namespace = ?' ).run(id, namespace) + if (result.changes > 0) { + // Per-socket access memos stamp the epoch they were filled under; + // bumping makes their next event re-resolve instead of serving a + // grant for a row that no longer exists. + bumpSessionDeletionEpoch() + } return result.changes > 0 } diff --git a/hub/src/store/statementCache.test.ts b/hub/src/store/statementCache.test.ts new file mode 100644 index 00000000..4e1c46c3 --- /dev/null +++ b/hub/src/store/statementCache.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'bun:test' +import { Database } from 'bun:sqlite' +import { prepareCached } from './statementCache' + +describe('prepareCached', () => { + it('reuses one Statement instance per (db, sql) and keeps it bindable', () => { + const db = new Database(':memory:') + db.exec('CREATE TABLE t (id TEXT)') + + const first = prepareCached(db, 'SELECT COUNT(*) AS n FROM t WHERE id = ?') + const second = prepareCached(db, 'SELECT COUNT(*) AS n FROM t WHERE id = ?') + expect(second).toBe(first) + + expect((first.get('x') as { n: number }).n).toBe(0) + db.exec("INSERT INTO t VALUES ('x')") + expect((second.get('x') as { n: number }).n).toBe(1) + expect((prepareCached(db, 'SELECT COUNT(*) AS n FROM t WHERE id = ?').get('x') as { n: number }).n).toBe(1) + db.close() + }) + + it('caches per Database instance', () => { + const db1 = new Database(':memory:') + const db2 = new Database(':memory:') + for (const db of [db1, db2]) db.exec('CREATE TABLE t (id TEXT)') + + expect(prepareCached(db1, 'SELECT COUNT(*) FROM t')).not.toBe(prepareCached(db2, 'SELECT COUNT(*) FROM t')) + db1.close() + db2.close() + }) + + it('does not share statements across distinct sql on the same db', () => { + const db = new Database(':memory:') + db.exec('CREATE TABLE t (id TEXT)') + expect(prepareCached(db, 'SELECT COUNT(*) FROM t')).not.toBe(prepareCached(db, 'SELECT id FROM t')) + db.close() + }) + + it('bounds retention: beyond the cap statements are prepared per call', () => { + const db = new Database(':memory:') + db.exec('CREATE TABLE t (id TEXT)') + + // Warm an entry while the cache is below its cap. + const early = prepareCached(db, 'SELECT COUNT(*) AS n FROM t') + + // Flood past the retention bound with distinct constant SQL. + for (let i = 0; i < 600; i += 1) { + prepareCached(db, `SELECT ${i} AS n`) + } + + // Entries admitted before the cap stay cached (identity stable). + expect(prepareCached(db, 'SELECT COUNT(*) AS n FROM t')).toBe(early) + + // New statements beyond the cap are not retained: each call compiles + // its own statement, and both execute correctly. + const lateA = prepareCached(db, 'SELECT 4242 AS n') + const lateB = prepareCached(db, 'SELECT 4242 AS n') + expect(lateA).not.toBe(lateB) + expect((lateA.get() as { n: number }).n).toBe(4242) + expect((lateB.get() as { n: number }).n).toBe(4242) + db.close() + }) +}) diff --git a/hub/src/store/statementCache.ts b/hub/src/store/statementCache.ts new file mode 100644 index 00000000..a1e29145 --- /dev/null +++ b/hub/src/store/statementCache.ts @@ -0,0 +1,39 @@ +import type { Database, Statement } from 'bun:sqlite' + +// Prepared-statement cache keyed by Database instance, then SQL text. +// +// bun:sqlite compiles a fresh Statement on every `db.prepare()` call. The +// hub's per-socket-event paths (session access resolution, message ingest, +// consumed/steer acks) invoke the same handful of statements dozens of times +// per second per connected CLI, and SQL recompilation dominated the hub's CPU +// profile under sustained event traffic. Statements are re-bindable on every +// get/run/all call, so a cached statement is semantically identical to an +// inline prepare as long as callers fully drain each call before the next +// (true for every sync store helper; `Statement.iterate()` callers keep +// preparing inline because they `finalize()` their statement). +// +// Keyed weakly so a reopened/replaced Database drops its statements with it. +const statementsByDb = new WeakMap>() + +// Retention bound. Every current call site passes one of ~80 static SQL +// strings, so the cap is never reached in practice; it exists so a future +// caller passing variable-length SQL (e.g. interpolated IN lists) cannot +// accumulate compiled statements without limit. Beyond the cap the statement +// is prepared per call — uncached, still correct. +const MAX_CACHED_STATEMENTS = 512 + +export function prepareCached(db: Database, sql: string): Statement { + let bySql = statementsByDb.get(db) + if (!bySql) { + bySql = new Map() + statementsByDb.set(db, bySql) + } + let statement = bySql.get(sql) + if (!statement) { + statement = db.prepare(sql) + if (bySql.size < MAX_CACHED_STATEMENTS) { + bySql.set(sql, statement) + } + } + return statement +} From 7b6c575514164300cfa104d6600df033b6082c39 Mon Sep 17 00:00:00 2001 From: Ananovo Date: Wed, 16 Sep 2026 07:26:18 +0800 Subject: [PATCH 08/34] fix(web): refresh cached session tails with a small page (#1847) --- docs/api/client-contract/pagination.md | 8 +- e2e/history-load.spec.ts | 62 +++++++++ web/e2e-fixtures/history-load-fixture.tsx | 42 ++++++- web/src/lib/message-window-store.test.ts | 145 ++++++++++++++++++++-- web/src/lib/message-window-store.ts | 17 ++- 5 files changed, 257 insertions(+), 17 deletions(-) diff --git a/docs/api/client-contract/pagination.md b/docs/api/client-contract/pagination.md index f8f6e194..2f43046d 100644 --- a/docs/api/client-contract/pagination.md +++ b/docs/api/client-contract/pagination.md @@ -24,7 +24,7 @@ Query parameters (`MessagesQuerySchema`; all numbers coerced from strings): | Param | Type | Constraint | |---|---|---| -| `limit` | int | 1–200. **Default 50** when omitted (the web reference always sends 200). | +| `limit` | int | 1–200. **Default 50** when omitted; the web reference uses 200 for full latest/reset, after, and before pages, and 20 for the first latest-tail refresh on cached re-entry. | | `beforeSeq` + `beforeAt` | int + int | Page strictly older than this position. Pairwise required. | | `afterSeq` + `afterAt` | int + int | Page strictly newer than this position. Pairwise required. | | `untilSeq` + `untilAt` | int + int | Inclusive snapshot head for a catch-up loop. Pairwise required; **requires an `after` cursor**. | @@ -102,7 +102,8 @@ Run after connect, after an SSE `resume: 'gap'` handshake, on session open, and - For a genuinely cold window with no cursor and no pending structural reset, request `GET …/messages?limit=20` (latest) so the newest usable conversation content can paint quickly. - For a pending structural reset, request the normal full latest page with `limit=200`. - Replace/merge into the window, store `page.epoch`, `nextBefore*` (older-page cursor) and `snapshotHead*` (newest cursor). Done. -2. **Have cursor + epoch**: loop +2. **Cached re-entry with a usable cursor**: `GET …/messages?limit=20` (latest), replace the stale server window while preserving queued/concurrent rows, then expose `nextBefore*` for older-history loading. Done. +3. **Have cursor + epoch outside activation**: loop - `GET …/messages?afterSeq&afterAt&epoch[&untilSeq&untilAt]&limit=200`, where `after` starts at your newest cursor and `until` is the `snapshotHead*` captured from the **first** response of the loop (fixes the target so the loop terminates). - `page.reset` or `direction: 'latest'` ⇒ replace the window with this page; stop. - Otherwise merge the rows, advance `after = nextAfter*`, update the newest cursor to `max(current, nextAfter)`; stop when `hasMore` is false. @@ -120,6 +121,7 @@ Constants from the web reference (`web/src/lib/message-window-store.ts`): |---|---|---| | `INITIAL_PAGE_SIZE` | 20 | Request size for the cold latest page used to prioritize first paint. | | `PAGE_SIZE` | 200 | Request size for ordinary latest/reset, forward, and older-page fetches. | +| `CACHED_REENTRY_PAGE_SIZE` | 20 | First latest-tail page for a cached session re-entry. | | `VISIBLE_WINDOW_SIZE` | 400 | Max regular rows kept in **tail** mode (following live bottom). | | `HISTORY_WINDOW_SIZE` | 600 | Max regular rows kept in **history** mode (user scrolled back). | | `OLDER_LOAD_WINDOW_SIZE` | 800 | Temporary cap while an older page is being merged (prepend). | @@ -130,7 +132,7 @@ Rules: - **Tail mode** trims from the top (oldest dropped). Dropping rows ⇒ set `hasMore: true` and recompute the older-page cursor from the oldest kept row. - **History mode** trims from the bottom (newest dropped). Dropping newest rows means your window no longer reaches the tail ⇒ flag "latest reset required": on returning to tail mode, discard cursors and fetch a fresh latest page rather than trusting stale ones. - **Queued rows are never trimmed** (user messages with `invokedAt === null`, see below) — they are re-merged after every trim. -- Persist the window (messages + cursors + epoch) per session for instant cold-start rendering; a genuinely cold window requests a small latest page for first paint, while structural resets and re-activation with a persisted cursor use the ordinary full latest page and reconcile. Another client may have advanced the session by many pages. +- Persist the window (messages + cursors + epoch) per session for instant cold-start rendering; a genuinely cold window and cached re-activation request a small latest page for first paint, while structural resets request the ordinary full latest page and reconcile. Another client may have advanced the session by many pages; cached re-activation keeps the returned older cursor available for on-demand history loading. --- diff --git a/e2e/history-load.spec.ts b/e2e/history-load.spec.ts index 4b9793f2..a4d0939e 100644 --- a/e2e/history-load.spec.ts +++ b/e2e/history-load.spec.ts @@ -1,5 +1,67 @@ import { expect, test } from '@playwright/test' +test('cached re-entry keeps the cache visible while refreshing a small latest tail', async ({ page }) => { + await page.goto('/e2e-fixtures/history-load-fixture.html?cachedReentry=1&holdLatest=1') + const viewport = page.locator('.app-scroll-y') + await expect(viewport).toBeVisible() + + await expect.poll(async () => await page.evaluate(() => ({ + latestRequests: window.__probe.requests.filter((request) => request.direction === 'latest').length, + latestLimit: window.__probe.requests.find((request) => request.direction === 'latest')?.limit ?? null + }))).toEqual({ latestRequests: 1, latestLimit: 20 }) + + // The persisted snapshot must remain usable while the latest-tail request + // is held in flight; this is the user-visible cache-first contract. + await expect(page.getByText('Fixture message 1001', { exact: true })).toBeVisible() + expect(await page.evaluate(() => window.__probe.requests.filter((request) => request.direction === 'before').length)).toBe(0) + + await page.evaluate(() => window.__probe.releaseLatest()) + await expect(page.getByText('Fixture message 1200', { exact: true })).toBeVisible() + await expect(page.getByText('Fixture message 1001', { exact: true })).toHaveCount(0) + + // The small latest page still exposes its normal older cursor; scrolling + // to the top must load one full history page through the existing path. + await viewport.dispatchEvent('pointerdown', { button: 0, pointerType: 'mouse' }) + await page.evaluate(() => { + const element = document.querySelector('.app-scroll-y') as HTMLElement + element.scrollTop = 0 + element.dispatchEvent(new Event('scroll')) + }) + await viewport.dispatchEvent('pointerup', { button: 0, pointerType: 'mouse' }) + await expect.poll(async () => await page.evaluate(() => ({ + beforeRequests: window.__probe.requests.filter((request) => request.direction === 'before').length, + beforeLimit: window.__probe.requests.find((request) => request.direction === 'before')?.limit ?? null + }))).toEqual({ beforeRequests: 1, beforeLimit: 200 }) + await expect(page.getByText('Fixture message 1001', { exact: true })).toBeVisible() +}) + +test('cached re-entry resumes an upward history gesture after latest refresh completes', async ({ page }) => { + await page.goto('/e2e-fixtures/history-load-fixture.html?cachedReentry=1&holdLatest=1') + const viewport = page.locator('.app-scroll-y') + await expect(viewport).toBeVisible() + await expect.poll(async () => await page.evaluate(() => ({ + latestRequests: window.__probe.requests.filter((request) => request.direction === 'latest').length, + latestLimit: window.__probe.requests.find((request) => request.direction === 'latest')?.limit ?? null + }))).toEqual({ latestRequests: 1, latestLimit: 20 }) + + // The user starts browsing older history before the latest refresh returns. + await viewport.dispatchEvent('pointerdown', { button: 0, pointerType: 'mouse' }) + await page.evaluate(() => { + const element = document.querySelector('.app-scroll-y') as HTMLElement + element.scrollTop = 0 + element.dispatchEvent(new Event('scroll')) + }) + await viewport.dispatchEvent('pointerup', { button: 0, pointerType: 'mouse' }) + expect(await page.evaluate(() => window.__probe.requests.filter((request) => request.direction === 'before').length)).toBe(0) + + await page.evaluate(() => window.__probe.releaseLatest()) + await expect.poll(async () => await page.evaluate(() => ({ + beforeRequests: window.__probe.requests.filter((request) => request.direction === 'before').length, + beforeLimit: window.__probe.requests.find((request) => request.direction === 'before')?.limit ?? null + }))).toEqual({ beforeRequests: 1, beforeLimit: 200 }) + await expect(page.getByText('Fixture message 1000', { exact: true })).toBeVisible() +}) + // Regression: loading an older page prepends hundreds of messages at once. // assistant-ui's tap scheduler aborts a flush with more than 50 dirty // resources and drops the rest, so the thread never reflected the merged diff --git a/web/e2e-fixtures/history-load-fixture.tsx b/web/e2e-fixtures/history-load-fixture.tsx index 29379e3c..d91df9be 100644 --- a/web/e2e-fixtures/history-load-fixture.tsx +++ b/web/e2e-fixtures/history-load-fixture.tsx @@ -30,6 +30,7 @@ type Probe = { requests: { direction: string; beforeSeq: number | null; limit: number | undefined; at: number }[] loadMore: () => Promise refetch: () => Promise + releaseLatest: () => void windowState: () => { messageCount: number; oldestSeq: number | null; newestSeq: number | null } } @@ -39,10 +40,14 @@ declare global { } } +let releaseLatestResponse = () => {} +let latestResponseGate: Promise | null = null + window.__probe = { requests: [], loadMore: async () => {}, refetch: async () => {}, + releaseLatest: () => releaseLatestResponse(), windowState: () => { const state = getMessageWindowState(SESSION_ID) return { @@ -69,6 +74,10 @@ window.__probe = { // of returning the legacy full 200-row page used by this fixture by default. // - ?slowBefore=1 — delay older-page responses long enough for a normal tail // synchronization to invalidate an in-flight request. +// - ?cachedReentry=1 — hydrate one cached message before activation, so the +// latest-tail refresh path can be tested independently from a cold window. +// - ?holdLatest=1 — hold the latest response until `window.__probe.releaseLatest` +// is called, making the cached first paint observable. const fixtureParams = new URLSearchParams(window.location.search) const shortPages = fixtureParams.has('shortPages') const failBeforeCount = Number(fixtureParams.get('failBefore') ?? '0') @@ -76,6 +85,13 @@ const filteredOlder = fixtureParams.has('filteredOlder') const epochBump = fixtureParams.has('epochBump') const coldInitial = fixtureParams.has('coldInitial') const slowBefore = fixtureParams.has('slowBefore') +const cachedReentry = fixtureParams.has('cachedReentry') +const holdLatest = fixtureParams.has('holdLatest') +if (holdLatest) { + latestResponseGate = new Promise((resolve) => { + releaseLatestResponse = resolve + }) +} let beforeAttempts = 0 const allMessages: DecryptedMessage[] = Array.from({ length: TOTAL_MESSAGES }, (_, index) => { @@ -93,6 +109,24 @@ const allMessages: DecryptedMessage[] = Array.from({ length: TOTAL_MESSAGES }, ( } as DecryptedMessage }) +if (cachedReentry) { + const cachedMessages = allMessages.slice(-200) + const cachedOldest = cachedMessages[0] + const cachedNewest = cachedMessages.at(-1) + if (!cachedOldest || !cachedNewest) throw new Error('Expected cached fixture messages') + const oldestPosition = positionOf(cachedOldest) + const newestPosition = positionOf(cachedNewest) + sessionStorage.setItem(`hapi:message-window:v2:${SESSION_ID}`, JSON.stringify({ + messages: cachedMessages, + hasMore: true, + oldestPositionAt: oldestPosition.at, + oldestPositionSeq: oldestPosition.seq, + newestPositionAt: newestPosition.at, + newestPositionSeq: newestPosition.seq, + epoch: 1 + })) +} + function positionOf(message: DecryptedMessage): { at: number; seq: number } { return { at: message.invokedAt ?? message.createdAt, seq: message.seq ?? 0 } } @@ -117,6 +151,8 @@ function pageFrom(messages: DecryptedMessage[], overrides: Partial ({ sessionSummaryInChat: false }), + getMachines: async () => ({ machines: [] }), getMessages: async (_sessionId: string, query: { limit?: number beforeAt?: number | null @@ -128,7 +164,7 @@ const fakeApi = { let direction = 'latest' if (query.beforeSeq != null || query.beforeAt != null) direction = 'before' else if (query.afterSeq != null || query.afterAt != null) direction = 'after' - const limit = direction === 'latest' && !coldInitial ? 200 : requestedLimit + const limit = direction === 'latest' && !coldInitial && !cachedReentry ? 200 : requestedLimit window.__probe.requests.push({ direction, beforeSeq: query.beforeSeq ?? null, @@ -142,6 +178,10 @@ const fakeApi = { direction === 'before' && slowBefore ? 500 : 50 )) + if (direction === 'latest' && latestResponseGate) { + await latestResponseGate + } + if (direction === 'before') { beforeAttempts += 1 if (beforeAttempts <= failBeforeCount) { diff --git a/web/src/lib/message-window-store.test.ts b/web/src/lib/message-window-store.test.ts index fb2b721e..898d41f0 100644 --- a/web/src/lib/message-window-store.test.ts +++ b/web/src/lib/message-window-store.test.ts @@ -137,6 +137,7 @@ function makeAgentRunMessage(id: string, seq: number, at: number): DecryptedMess function latestResponse( messages: DecryptedMessage[], options: { + limit?: number epoch?: number hasMore?: boolean reset?: boolean @@ -154,7 +155,7 @@ function latestResponse( messages, page: { direction: 'latest', - limit: 200, + limit: options.limit ?? 200, epoch: options.epoch ?? 0, reset: options.reset ?? false, nextBeforeAt: options.nextBeforeAt ?? null, @@ -383,7 +384,7 @@ describe('message tail synchronization', () => { expect(getMessageWindowState(id).isSyncingTail).toBe(false) }) - it('renders a persisted window immediately, then requests the latest tail on re-entry', async () => { + it('renders a persisted window immediately, then requests a small latest tail on re-entry', async () => { const id = sessionId('reentry') const cached = makeAgentMessage({ id: 'cached', seq: 40, at: 40_000 }) sessionStorage.setItem(`hapi:message-window:v2:${id}`, JSON.stringify({ @@ -401,16 +402,24 @@ describe('message tail synchronization', () => { activateMessageWindow(id) expect(getMessageWindowState(id).viewMode).toBe('tail') + const response = deferred() + const getMessages = vi.fn(async () => await response.promise) + const syncing = syncTailMessages(createApi(getMessages), id) + + expect(getMessages).toHaveBeenCalledWith(id, { limit: 20 }) + expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual(['cached']) + expect(getMessageWindowState(id).isSyncingTail).toBe(true) + const latest = makeAgentMessage({ id: 'latest', seq: 2_040, at: 2_040_000 }) - const getMessages = vi.fn(async () => latestResponse([latest], { + response.resolve(latestResponse([latest], { + limit: 20, epoch: 3, hasMore: true, nextBeforeAt: 1_841_000, nextBeforeSeq: 1_841 })) - await syncTailMessages(createApi(getMessages), id) + await syncing - expect(getMessages).toHaveBeenCalledWith(id, { limit: 200 }) expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual(['latest']) expect(getMessageWindowState(id).hasMore).toBe(true) expect('pending' in getMessageWindowState(id)).toBe(false) @@ -441,7 +450,7 @@ describe('message tail synchronization', () => { const getMessages = vi.fn(async () => latestResponse([latest], { epoch: 3 })) await syncTailMessages(createApi(getMessages), id) - expect(getMessages).toHaveBeenCalledWith(id, { limit: 200 }) + expect(getMessages).toHaveBeenCalledWith(id, { limit: 20 }) expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual([ 'local-1', 'latest' @@ -452,6 +461,127 @@ describe('message tail synchronization', () => { })) }) + it('keeps the latest page cursor available for older history after re-entry', async () => { + const id = sessionId('reentry-older-history') + const cached = makeAgentMessage({ id: 'cached', seq: 40, at: 40_000 }) + sessionStorage.setItem(`hapi:message-window:v2:${id}`, JSON.stringify({ + messages: [cached], + hasMore: true, + oldestPositionAt: 40_000, + oldestPositionSeq: 40, + newestPositionAt: 40_000, + newestPositionSeq: 40, + epoch: 3 + })) + + activateMessageWindow(id) + const latest = [ + makeAgentMessage({ id: 'latest-1', seq: 2_039, at: 2_039_000 }), + makeAgentMessage({ id: 'latest-2', seq: 2_040, at: 2_040_000 }) + ] + const older = makeAgentMessage({ id: 'older', seq: 2_038, at: 2_038_000 }) + const getMessages = vi.fn() + .mockResolvedValueOnce(latestResponse(latest, { + limit: 20, + epoch: 3, + hasMore: true, + nextBeforeAt: 2_039_000, + nextBeforeSeq: 2_039 + })) + .mockResolvedValueOnce(beforeResponse([older], { + epoch: 3, + hasMore: false, + nextBeforeAt: 2_038_000, + nextBeforeSeq: 2_038 + })) + const api = createApi(getMessages) + + await syncTailMessages(api, id) + await fetchOlderMessages(api, id) + + expect(getMessages.mock.calls[0]?.[1]).toEqual({ limit: 20 }) + expect(getMessages.mock.calls[1]?.[1]).toEqual({ + beforeAt: 2_039_000, + beforeSeq: 2_039, + limit: 200 + }) + expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual([ + 'older', + 'latest-1', + 'latest-2' + ]) + }) + + it('keeps cached messages visible when the re-entry refresh fails', async () => { + const id = sessionId('reentry-refresh-failure') + const cached = makeAgentMessage({ id: 'cached', seq: 40, at: 40_000 }) + sessionStorage.setItem(`hapi:message-window:v2:${id}`, JSON.stringify({ + messages: [cached], + hasMore: true, + oldestPositionAt: 40_000, + oldestPositionSeq: 40, + newestPositionAt: 40_000, + newestPositionSeq: 40, + epoch: 3 + })) + + activateMessageWindow(id) + const getMessages = vi.fn(async () => { + throw new Error('latest tail unavailable') + }) + + await syncTailMessages(createApi(getMessages), id) + + expect(getMessages).toHaveBeenCalledWith(id, { limit: 20 }) + expect(getMessageWindowState(id)).toMatchObject({ + messages: [cached], + isSyncingTail: false, + warning: 'latest tail unavailable' + }) + }) + + it('preserves live and optimistic rows that arrive during a re-entry refresh', async () => { + const id = sessionId('reentry-concurrent-rows') + const cached = makeAgentMessage({ id: 'cached', seq: 40, at: 40_000 }) + sessionStorage.setItem(`hapi:message-window:v2:${id}`, JSON.stringify({ + messages: [cached], + hasMore: true, + oldestPositionAt: 40_000, + oldestPositionSeq: 40, + newestPositionAt: 40_000, + newestPositionSeq: 40, + epoch: 3 + })) + + activateMessageWindow(id) + const response = deferred() + const getMessages = vi.fn(async () => await response.promise) + const syncing = syncTailMessages(createApi(getMessages), id) + await vi.waitFor(() => expect(getMessages).toHaveBeenCalledWith(id, { limit: 20 })) + + const optimistic = makeUserMessage({ + id: 'local-1', + localId: 'local-1', + createdAt: 41_000, + invokedAt: null, + status: 'sending' + }) + appendOptimisticMessage(id, optimistic) + const live = makeAgentMessage({ id: 'live', seq: 41, at: 41_000 }) + ingestIncomingMessages(id, [live]) + + response.resolve(latestResponse([ + makeAgentMessage({ id: 'latest', seq: 2_040, at: 2_040_000 }) + ], { limit: 20, epoch: 3 })) + await syncing + + expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual([ + 'live', + 'local-1', + 'latest' + ]) + }) + it('keeps incremental synchronization for non-activation refreshes', async () => { const id = sessionId('incremental-refresh') const cached = makeAgentMessage({ id: 'cached', seq: 40, at: 40_000 }) @@ -706,7 +836,7 @@ describe('message tail synchronization', () => { activateMessageWindow(id) const reentrySync = syncTailMessages(api, id) await vi.waitFor(() => expect(getMessages).toHaveBeenCalledTimes(2)) - expect(getMessages.mock.calls[1]?.[1]).toEqual({ limit: 200 }) + expect(getMessages.mock.calls[1]?.[1]).toEqual({ limit: 20 }) staleResponse.resolve(afterResponse([ makeAgentMessage({ id: 'stale-page', seq: 41, at: 41_000 }) ], { @@ -962,6 +1092,7 @@ describe('message tail synchronization', () => { await syncTailMessages(createApi(getMessages), id) expect(getMessages).toHaveBeenCalledTimes(1) + expect(getMessages).toHaveBeenCalledWith(id, { limit: INITIAL_PAGE_SIZE }) expect(getMessageWindowState(id).hasMore).toBe(true) }) }) diff --git a/web/src/lib/message-window-store.ts b/web/src/lib/message-window-store.ts index 912d4e11..3c677d40 100644 --- a/web/src/lib/message-window-store.ts +++ b/web/src/lib/message-window-store.ts @@ -44,6 +44,7 @@ export const INITIAL_PAGE_SIZE = 20 const AGENT_RUN_WINDOW_SIZE = 800 const OLDER_LOAD_WINDOW_SIZE = 800 const PAGE_SIZE = 200 +const CACHED_REENTRY_PAGE_SIZE = 20 type MessagePosition = { at: number @@ -694,13 +695,17 @@ async function runTailSync(api: ApiClient, sessionId: string): Promise { if (!canIncrement) { const requestBaseline = new Map(getState(sessionId).messages.map((message) => [message.id, message])) - // A cold window has no server cursor yet, so prioritize the latest - // usable messages for first paint. Structural resets and cached - // re-entry keep the full page so their authoritative replacement - // remains unchanged; user-driven older loads still use PAGE_SIZE. - const latestPageSize = initial.requiresLatestReset || initialCursor !== null + // Cold windows and cached re-entry prioritize the newest usable + // messages for first paint. Structural resets and cursor-backed + // non-activation synchronization use the full page so their + // authoritative replacement remains unchanged. + const latestPageSize = initial.requiresLatestReset ? PAGE_SIZE - : INITIAL_PAGE_SIZE + : preferLatestOnActivation + ? CACHED_REENTRY_PAGE_SIZE + : initialCursor === null + ? INITIAL_PAGE_SIZE + : PAGE_SIZE const response = await api.getMessages(sessionId, { limit: latestPageSize }) if (!isCurrentTailSync(sessionId, generation)) return updateState(sessionId, (previous) => { From 8f9d6bd7f8e4c2eb0dec824e0bdf974e86064e31 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Wed, 16 Sep 2026 01:11:54 +0100 Subject: [PATCH 09/34] fix(hub): keepalive-only sessions reconcile to an idle lifecycle (#1820) (#1821) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(hub): reconcile keepalive-only sessions to an idle lifecycle `sessionCache.expireInactive` only expires a session when `activeAt` goes stale, and `session-alive` refreshes `activeAt` every ~2s for as long as the CLI socket lives. A session whose agent has done nothing for days therefore stays `active: true` / `lifecycleState: running` forever — socket pinging was being read as agent health. Add the missing second signal. `active` keeps its meaning (the CLI is reachable); `metadata.lifecycleState` moves `running` -> `idle` once the hub has seen nothing but keepalives for `HAPI_SESSION_IDLE_TIMEOUT_MS` (default 12h, `0` disables), and back to `running` on the next real progress. `active` is deliberately not flipped: the socket really is up, and a false `active: false` would let `resumeSession` spawn a second agent against a live process and would unlock dedup-merge / delete on it — the #1705 class of bug. - `sessionCache.recordAgentProgress` tracks a progress clock that keepalives can never touch: messages in either direction, queued prompts, background tasks. Seeded from `updatedAt` so a hub restart re-derives it from disk. - `reconcileKeepaliveIdle` runs on the existing 5s inactivity tick. Sessions that are thinking, running background tasks or holding a pending permission request are never marked; `metadata.idleReconcileExempt` opts out entirely. - Only real progress clears `idle`, never `thinking` — Cursor ACP emits ambient idle/running churn (#1553) that would otherwise flap the lifecycle every tick. - `isLiveLifecycleState` replaces the `=== 'running'` literals so an `idle` row does not read as dead to the archive route or the Cursor migrator. - Web splits keepalive-only sessions into their own session-list bucket. Refs #1820. Distinct from #842 (`active=false` with a stale `running` badge); this is the inverse. via [HAPI](https://hapi.run) Co-Authored-By: HAPI * fix(hub): seed the idle clock from stored messages across hub restart PR review on #1821: a cold `SessionCache` had no observed progress and fell back to `updatedAt` alone. Assistant messages deliberately do not move `updatedAt`, so a session that was streaming output a minute before a hub restart read as hours idle and got marked on the very next tick — a false `idle` that persisted until the next progress event. Seed the clock once from `getNewestMessagePosition`, which is the durable record of that output. `updatedAt` stays a floor on top of the seed: todos / teamState / agentState writes bump it without routing through `recordAgentProgress`. Regression test recreates a SessionCache over the same store after recent assistant output and confirms keepalives no longer cause premature idle classification — and that the same session is still marked once the output itself goes stale. via [HAPI](https://hapi.run) Co-Authored-By: HAPI * test: cover the socket wake-up path and the idle session-list bucket Follow-up review on #1821 reported no findings but flagged two uncovered paths. Both have bad failure modes, so close them. - Hub: an assistant message arriving through `registerSessionHandlers` must wake an idle session. Assistant messages never bump `updatedAt`, so the `onAgentProgress` hook is the only thing that can clear the mark — a refactor dropping that wiring would silently false-idle every actively working session, and nothing would have caught it. - Web: extract the inline bucketing from the `runningSessions` useMemo into a pure `bucketRunningSessions`, matching how the rest of SessionList's logic is exported and tested. Covers idle vs quiet-but-ready separation, no double-bucketing, the transition back out of idle on thinking/background task/pending request, and the disconnected/pinned skips. No behaviour change. via [HAPI](https://hapi.run) Co-Authored-By: HAPI * test: cover the idle lifecycle at both isLiveLifecycleState call sites Third review round reported no findings but named the two guards this PR changed as uncovered. Both protect against reading a keepalive-idle row as a dead one: - Cursor migrator: an idle-marked row still has a live CLI behind it, so preflight must refuse it without `forceArchiveRunning`. A regression here would let the migrator transplant the ACP session directory out from under a running Cursor runner. - Archive route: once a keepalive-idle session finally loses its socket it must stay archivable, rather than being stranded behind a 409. Both tests were confirmed non-vacuous by reverting each guard to the `=== 'running'` literal; each then fails. No behaviour change. via [HAPI](https://hapi.run) Co-Authored-By: HAPI * test: stop the restart regression leaking its temp DB on failure The file-backed store's `rmSync` was a trailing call, so any failing assertion above it skipped cleanup and left a temp DB behind — one per failed run. Noticed while verifying the test was non-vacuous, which deliberately fails it. Wrap in try/finally. Verified: a forced failure now leaves zero `/tmp/hapi-1820-*` directories. Test-only. via [HAPI](https://hapi.run) Co-Authored-By: HAPI --------- Co-authored-by: HAPI --- docs/api/client-contract/sse.md | 23 ++ hub/README.md | 15 + hub/src/cursor/cursorLegacyMigrator.test.ts | 12 + hub/src/cursor/cursorLegacyMigrator.ts | 15 +- hub/src/socket/handlers/cli/index.ts | 4 +- .../socket/handlers/cli/sessionHandlers.ts | 9 +- hub/src/socket/server.ts | 2 + hub/src/startHub.ts | 1 + hub/src/sync/sessionCache.ts | 128 ++++++++ hub/src/sync/sessionIdle.test.ts | 282 ++++++++++++++++++ hub/src/sync/sessionIdle.ts | 94 ++++++ hub/src/sync/syncEngine.ts | 20 +- hub/src/web/routes/sessions.test.ts | 26 ++ hub/src/web/routes/sessions.ts | 6 +- shared/package.json | 1 + shared/src/index.ts | 1 + shared/src/schemas.ts | 7 + shared/src/sessionLifecycle.ts | 35 +++ web/src/components/SessionList.test.ts | 52 ++++ web/src/components/SessionList.tsx | 83 ++++-- web/src/lib/locales/en.ts | 1 + web/src/lib/locales/zh-CN.ts | 1 + 22 files changed, 774 insertions(+), 44 deletions(-) create mode 100644 hub/src/sync/sessionIdle.test.ts create mode 100644 hub/src/sync/sessionIdle.ts create mode 100644 shared/src/sessionLifecycle.ts diff --git a/docs/api/client-contract/sse.md b/docs/api/client-contract/sse.md index 3bb3a39a..3bcf2ce5 100644 --- a/docs/api/client-contract/sse.md +++ b/docs/api/client-contract/sse.md @@ -186,6 +186,29 @@ The CLI keep-alive makes the hub re-broadcast a patch roughly **every 10 s per a Reference list sort (web): `globalPinned` > `pinned` > `active` > `pendingRequestsCount` (among active) > `updatedAt` desc. +### `active` is transport liveness, not agent health + +Two different signals travel on a `Session` and clients routinely conflate them (tiann/hapi#1820): + +| Signal | Means | Refreshed by | +|---|---|---| +| `active` / `activeAt` | the CLI socket is connected and reachable | the `session-alive` keep-alive, every ~2 s | +| `metadata.lifecycleState` | what the agent behind that socket is actually doing | lifecycle transitions only | + +A session can keep `active: true` indefinitely on keep-alives alone, with no messages and no thinking, for days. That is a live socket in front of an idle agent, not a working session. + +`metadata.lifecycleState` is the health signal: + +- `running` — live working session (stamped by the CLI at session start) +- `idle` — the hub has seen nothing but keep-alives for `HAPI_SESSION_IDLE_TIMEOUT_MS` (default 12 h). Reversible and non-destructive: `active` stays `true`, and the next message, queued prompt or background task flips it back to `running` within one hub tick +- `archived` — session closed + +Client rules: + +- Treat both `running` and `idle` as "a CLI still owns this session". Comparing against the `'running'` literal makes an `idle` session read as a dead row. +- Surface `idle` distinctly from `active`-and-recently-working, so an operator can tell a busy fleet from a pile of keep-alive zombies (web: the `idle` bucket in `SessionList`). +- Sessions that are meant to sit quiet indefinitely can set `metadata.idleReconcileExempt: true` to opt out of reconciliation entirely. + --- ## Visibility diff --git a/hub/README.md b/hub/README.md index 1a591166..64d08a2b 100644 --- a/hub/README.md +++ b/hub/README.md @@ -55,6 +55,7 @@ Dictation and voice-assistant provider keys can also be added from **Settings - `FCM_SERVICE_ACCOUNT_PATH` - Service-account JSON for private Firebase builds; the app must use the same project. Invalid configured credentials disable Android push instead of switching projects. - `HAPI_IOS_PUSH` - `relay` (default), `apns`, or `off`. - `HAPI_PUSH_RELAY_URL` - Shared Android/iOS push relay (default: `https://push.hapi.run`; persisted as `iosPushRelayUrl`). Independent of the `--relay` network tunnel. +- `HAPI_SESSION_IDLE_TIMEOUT_MS` - Keep-alive-idle window in ms (default: 43200000 / 12 h; `0` disables). See "Session liveness" below. Official native apps register their encryption keys automatically; no push provider setup is needed on a fresh hub. See the [native companion push @@ -251,6 +252,20 @@ See `src/sync/syncEngine.ts` for the main session/message manager: - Git operations and file search. - Activity tracking and timeouts. +### Session liveness + +Two separate signals, deliberately (tiann/hapi#1820): + +- **`active` / `activeAt`** - transport. The CLI socket is connected; `session-alive` refreshes it every ~2 s. `sessionCache.expireInactive` drops `active` after 30 s of silence. +- **`metadata.lifecycleState`** - agent health. `running` -> `idle` -> `running`, plus `archived`. + +Keep-alives prove a socket, not an agent. A session can therefore heartbeat for days with no messages, no thinking and no background tasks - `active: true` forever, which `expireInactive` can never catch. `sessionCache.reconcileKeepaliveIdle` (same 5 s tick) closes that gap: after `HAPI_SESSION_IDLE_TIMEOUT_MS` with no agent progress it moves `lifecycleState` `running` -> `idle`. + +- `active` is left alone on purpose. The CLI really is reachable, and flipping it would let `resumeSession` spawn a second agent against a live process, and unlock dedup-merge / delete on it. +- Progress means a message in either direction, a queued prompt, or a background task - never a keep-alive. Sessions that are thinking, running background tasks or holding a pending permission request are never marked. +- `idle` reverts to `running` on the next progress, within one tick. +- `metadata.idleReconcileExempt: true` opts a session out entirely. + ## Storage See `src/store/index.ts` for SQLite persistence: diff --git a/hub/src/cursor/cursorLegacyMigrator.test.ts b/hub/src/cursor/cursorLegacyMigrator.test.ts index 57f8f5a8..a271bc8a 100644 --- a/hub/src/cursor/cursorLegacyMigrator.test.ts +++ b/hub/src/cursor/cursorLegacyMigrator.test.ts @@ -470,6 +470,18 @@ describe('CursorLegacyMigrator.migrateOne — refusals', () => { if (!out.ok) expect(out.reason).toBe('running_refused') }) + // tiann/hapi#1820: an idle-marked row still has a live CLI behind it. + // Reading 'idle' as a dead row would let the migrator transplant the ACP + // session directory out from under a running Cursor runner. + it('refuses sessions whose lifecycleState is "idle" without forceArchiveRunning', async () => { + const session = h.makeSession({ + metadata: { path: '/x', host: 'h', flavor: 'cursor', cursorSessionId: 'u', lifecycleState: 'idle' } + }) + const out = await makeMigrator(h, null).migrateOne(session, {}) + expect(out.ok).toBe(false) + if (!out.ok) expect(out.reason).toBe('running_refused') + }) + it('refuses sessions where session.active=true even without lifecycleState (Codex #34 P2)', async () => { const session = h.makeSession({ active: true, diff --git a/hub/src/cursor/cursorLegacyMigrator.ts b/hub/src/cursor/cursorLegacyMigrator.ts index 6ce40a3c..f744ca97 100644 --- a/hub/src/cursor/cursorLegacyMigrator.ts +++ b/hub/src/cursor/cursorLegacyMigrator.ts @@ -47,6 +47,7 @@ import { mkdtempSync, copyFileSync, writeFileSync, existsSync, mkdirSync, rmSync import { createHash } from 'node:crypto' import { Database } from 'bun:sqlite' +import { isLiveLifecycleState } from '@hapi/protocol' import type { CursorMigrateOutcome, CursorMigrateRefusalReason } from '@hapi/protocol/apiTypes' import type { Metadata } from '@hapi/protocol/schemas' import type { Session } from '@hapi/protocol/types' @@ -461,11 +462,11 @@ export function preflightSession(session: Session | undefined, now: () => number if (!CURSOR_SESSION_ID_RE.test(trimmed) || trimmed === '.' || trimmed === '..') { return refusal(sessionId, 'no_cursor_session_id', `cursorSessionId '${trimmed}' fails basename validation`, start, now) } - // Block both lifecycleState==='running' AND session.active (legacy rows - // may lack lifecycleState but still be active in the cache). Codex - // review #34 P2. + // Block both a live lifecycleState ('running' or the keepalive-idle + // 'idle' of tiann/hapi#1820) AND session.active (legacy rows may lack + // lifecycleState but still be active in the cache). Codex review #34 P2. const lifecycle = typeof metadata.lifecycleState === 'string' ? metadata.lifecycleState : undefined - const isActive = lifecycle === 'running' || session.active === true + const isActive = isLiveLifecycleState(lifecycle) || session.active === true if (isActive && !opts.forceArchiveRunning) { return refusal(sessionId, 'running_refused', 'session is active; archive first or pass forceArchiveRunning', start, now) } @@ -731,8 +732,8 @@ export class CursorLegacyMigrator { } catch (err) { return refusal(session.id, 'archive_failed', err instanceof Error ? err.message : String(err), start, this.deps.now) } - } else if (metadata.lifecycleState === 'running') { - log.info('[migrator] migrating stale lifecycle=running row without archive RPC (no live runner)', { sessionId: session.id }) + } else if (isLiveLifecycleState(metadata.lifecycleState)) { + log.info('[migrator] migrating stale live-lifecycle row without archive RPC (no live runner)', { sessionId: session.id, lifecycleState: metadata.lifecycleState }) } // If we just archived an active session, wait for the legacy @@ -929,7 +930,7 @@ export class CursorLegacyMigrator { tryRm(acpSessionDir) return refusal(session.id, 'session_resumed_during_migrate', `session became active during migration (active=true lifecycleState=${latest.lifecycleState ?? 'n/a'}); rolled back ACP placement`, start, this.deps.now) } - if (latest && !wasActive && latest.lifecycleState === 'running') { + if (latest && !wasActive && isLiveLifecycleState(latest.lifecycleState)) { // Lifecycle says running but active=false and we did NOT // archive this session ourselves. Something external lifted // it back to running between preflight and now (rare but diff --git a/hub/src/socket/handlers/cli/index.ts b/hub/src/socket/handlers/cli/index.ts index 72e7cf47..d9c95648 100644 --- a/hub/src/socket/handlers/cli/index.ts +++ b/hub/src/socket/handlers/cli/index.ts @@ -50,6 +50,7 @@ export type CliHandlersDeps = { onWebappEvent?: (event: SyncEvent) => void onBackgroundTaskDelta?: (sessionId: string, delta: { started: number; completed: number }) => void onSessionActivity?: (sessionId: string, updatedAt: number) => void + onAgentProgress?: (sessionId: string, at: number) => void onSweepImmediateQueued?: (sessionId: string, now: number) => void onMessagesConsumed?: (sessionId: string) => void } @@ -83,7 +84,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, onWebappEvent, onBackgroundTaskDelta, onSessionActivity, onSweepImmediateQueued, onMessagesConsumed } = deps + const { io, store, rpcRegistry, terminalRegistry, onSessionAlive, onSessionReady, onSessionEnd, onMachineAlive, onWebappEvent, onBackgroundTaskDelta, onSessionActivity, onAgentProgress, onSweepImmediateQueued, onMessagesConsumed } = deps const terminalNamespace = io.of('/terminal') const namespace = typeof socket.data.namespace === 'string' ? socket.data.namespace : null @@ -179,6 +180,7 @@ export function registerCliHandlers(socket: CliSocketWithData, deps: CliHandlers onWebappEvent, onBackgroundTaskDelta, onSessionActivity, + onAgentProgress, onSweepImmediateQueued, onMessagesConsumed }) diff --git a/hub/src/socket/handlers/cli/sessionHandlers.ts b/hub/src/socket/handlers/cli/sessionHandlers.ts index 1fcb7ab7..dd1c24a4 100644 --- a/hub/src/socket/handlers/cli/sessionHandlers.ts +++ b/hub/src/socket/handlers/cli/sessionHandlers.ts @@ -93,6 +93,8 @@ export type SessionHandlersDeps = { onWebappEvent?: (event: SyncEvent) => void onBackgroundTaskDelta?: (sessionId: string, delta: { started: number; completed: number }) => void onSessionActivity?: (sessionId: string, updatedAt: number) => void + /** tiann/hapi#1820: any message is agent progress, either direction. */ + onAgentProgress?: (sessionId: string, at: number) => void /** Delegates session-end immediate-queue sweep to the MessageService layer. */ onSweepImmediateQueued?: (sessionId: string, now: number) => void /** Drops the queued-thinking grace so synchronous CLI handlers (e.g. slash @@ -101,7 +103,7 @@ export type SessionHandlersDeps = { } export function registerSessionHandlers(socket: CliSocketWithData, deps: SessionHandlersDeps): void { - const { store, resolveSessionAccess, emitAccessError, onSessionAlive, onSessionReady, onSessionEnd, onWebappEvent, onBackgroundTaskDelta, onSessionActivity, onSweepImmediateQueued, onMessagesConsumed } = deps + const { store, resolveSessionAccess, emitAccessError, onSessionAlive, onSessionReady, onSessionEnd, onWebappEvent, onBackgroundTaskDelta, onSessionActivity, onAgentProgress, onSweepImmediateQueued, onMessagesConsumed } = 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) @@ -171,6 +173,11 @@ export function registerSessionHandlers(socket: CliSocketWithData, deps: Session store.messages.deleteLiveReasoningSnapshots(sid, reasoningStreamId, msg.id) } + // tiann/hapi#1820: every stored message proves the agent is doing + // something, so it refreshes the keepalive-idle clock. Only human + // turns additionally bump `updatedAt` (list ordering). + onAgentProgress?.(sid, msg.createdAt) + if (shouldRecordSessionActivity(content)) { onSessionActivity?.(sid, msg.createdAt) } diff --git a/hub/src/socket/server.ts b/hub/src/socket/server.ts index 5dc8ebc4..a394a649 100644 --- a/hub/src/socket/server.ts +++ b/hub/src/socket/server.ts @@ -44,6 +44,7 @@ export type SocketServerDeps = { onMachineAlive?: (payload: { machineId: string; time: number; health?: unknown }) => void onBackgroundTaskDelta?: (sessionId: string, delta: { started: number; completed: number }) => void onSessionActivity?: (sessionId: string, updatedAt: number) => void + onAgentProgress?: (sessionId: string, at: number) => void onSweepImmediateQueued?: (sessionId: string, now: number) => void onMessagesConsumed?: (sessionId: string) => void } @@ -132,6 +133,7 @@ export function createSocketServer(deps: SocketServerDeps): { onWebappEvent: deps.onWebappEvent, onBackgroundTaskDelta: deps.onBackgroundTaskDelta, onSessionActivity: deps.onSessionActivity, + onAgentProgress: deps.onAgentProgress, onSweepImmediateQueued: deps.onSweepImmediateQueued, onMessagesConsumed: deps.onMessagesConsumed })) diff --git a/hub/src/startHub.ts b/hub/src/startHub.ts index 2a78d092..984d7c7c 100644 --- a/hub/src/startHub.ts +++ b/hub/src/startHub.ts @@ -203,6 +203,7 @@ export async function startHub(options: StartHubOptions = {}): Promise syncEngine?.handleMachineAlive(payload), onBackgroundTaskDelta: (sessionId, delta) => syncEngine?.handleBackgroundTaskDelta(sessionId, delta), onSessionActivity: (sessionId, updatedAt) => syncEngine?.recordSessionActivity(sessionId, updatedAt), + onAgentProgress: (sessionId, at) => syncEngine?.recordAgentProgress(sessionId, at), onSweepImmediateQueued: (sessionId, now) => syncEngine?.sweepImmediateQueuedOnSessionEnd(sessionId, now), onMessagesConsumed: (sessionId) => syncEngine?.clearQueuedThinkingGrace(sessionId) }) diff --git a/hub/src/sync/sessionCache.ts b/hub/src/sync/sessionCache.ts index 7ae05e17..5a83f10c 100644 --- a/hub/src/sync/sessionCache.ts +++ b/hub/src/sync/sessionCache.ts @@ -1,3 +1,4 @@ +import { SESSION_LIFECYCLE_IDLE, SESSION_LIFECYCLE_RUNNING } from '@hapi/protocol' import { AgentStateSchema, MetadataSchema, SessionPatchSchema, TeamStateSchema } from '@hapi/protocol/schemas' import type { CodexCollaborationMode, CopilotAgentMode, PermissionMode, Session, SessionPatch } from '@hapi/protocol/types' import type { Store } from '../store' @@ -5,6 +6,7 @@ import { clampAliveTime } from './aliveTime' import { EventPublisher } from './eventPublisher' import { extractTodoWriteTodosFromMessageContent, TodosSchema } from './todos' import { extractBackgroundTaskDelta } from './backgroundTasks' +import { resolveSessionIdleTimeoutMs, shouldClearKeepaliveIdle, shouldMarkKeepaliveIdle } from './sessionIdle' const QUEUED_MESSAGE_THINKING_GRACE_MS = 15_000 // tiann/hapi#919: metadata writers (renameSession, clearSessionArchiveMetadata, @@ -22,6 +24,14 @@ export class SessionCache { private readonly deduplicatePending: Set = new Set() private readonly pendingThinkingUntilBySessionId: Map = new Map() private readonly runtimeConfigUpdatedAtBySessionId: Map>> = new Map() + /** + * Last time the hub saw real agent progress per session (tiann/hapi#1820). + * Deliberately NOT bumped by `session-alive`: keepalives are exactly the + * signal this clock has to be immune to. Seeded lazily from `updatedAt`, + * so a hub restart re-derives it from the last human turn on disk. + */ + private readonly agentProgressAtBySessionId: Map = new Map() + private readonly sessionIdleTimeoutMs: number = resolveSessionIdleTimeoutMs() constructor( private readonly store: Store, @@ -129,6 +139,7 @@ export class SessionCache { const existed = this.sessions.delete(sessionId) this.pendingThinkingUntilBySessionId.delete(sessionId) this.runtimeConfigUpdatedAtBySessionId.delete(sessionId) + this.agentProgressAtBySessionId.delete(sessionId) if (existed) { this.publisher.emit({ type: 'session-removed', sessionId }) } @@ -515,6 +526,7 @@ export class SessionCache { if (!wasThinking) session.activeTurnStartedAt = activeTurnStartedAt session.updatedAt = Math.max(session.updatedAt, nextTime) this.pendingThinkingUntilBySessionId.set(session.id, nextTime + QUEUED_MESSAGE_THINKING_GRACE_MS) + this.recordAgentProgress(session.id, nextTime) if (!wasThinking || session.updatedAt !== previousUpdatedAt) { this.lastBroadcastAtBySessionId.set(session.id, Date.now()) @@ -539,6 +551,7 @@ export class SessionCache { if (next === prev) return session.backgroundTaskCount = next + this.recordAgentProgress(sessionId) this.publisher.emit({ type: 'session-updated', sessionId, @@ -557,6 +570,7 @@ export class SessionCache { } const nextUpdatedAt = Math.max(stored.updatedAt, updatedAt) + this.recordAgentProgress(sessionId, nextUpdatedAt) const touched = this.store.sessions.touchSessionUpdatedAt(sessionId, nextUpdatedAt, stored.namespace) const session = this.sessions.get(sessionId) @@ -580,6 +594,112 @@ export class SessionCache { }) } + /** + * tiann/hapi#1820: record real agent progress (a message in either + * direction, a queued prompt, a background task starting). This is the + * clock `reconcileKeepaliveIdle` reads — `session-alive` must never reach + * it, otherwise a heartbeating-but-dead session looks healthy forever. + * + * Pure bookkeeping on purpose: the lifecycle write is left to the tick so + * this is safe to call from anywhere holding a cached Session reference + * (`refreshSession` replaces the cached object). + */ + recordAgentProgress(sessionId: string, at: number = Date.now()): void { + if (!Number.isFinite(at)) return + const previous = this.agentProgressAtBySessionId.get(sessionId) ?? 0 + if (at > previous) { + this.agentProgressAtBySessionId.set(sessionId, at) + } + } + + /** + * A cold cache (hub restart) has observed no progress of its own, so seed + * it once from disk. + * + * `updatedAt` alone is not enough: assistant messages deliberately do not + * move it, so a session that was streaming output a minute before the + * restart would read as hours idle and get marked on the very next tick. + * The newest stored message is the durable record of that output. + * + * `updatedAt` stays a floor on top of the seed, because todos / teamState + * / agentState writes bump it without routing through + * `recordAgentProgress`. + */ + private getAgentProgressAt(session: Session): number { + let observed = this.agentProgressAtBySessionId.get(session.id) + if (observed === undefined) { + observed = this.store.messages.getNewestMessagePosition(session.id)?.at ?? 0 + this.agentProgressAtBySessionId.set(session.id, observed) + } + return Math.max(observed, session.updatedAt) + } + + /** + * tiann/hapi#1820: reconcile `lifecycleState` for sessions that only the + * keepalive is keeping alive. Runs on the existing inactivity tick. + * + * `active` is deliberately left alone: the CLI socket really is up, and + * flipping `active` would make `resumeSession` spawn a second agent + * against a live process (and would unlock dedup-merge / delete on it). + * What changes is the honest agent-health signal, which operators, the + * session list and downstream tooling can act on. + * + * Returns the session ids newly marked `idle`. + */ + reconcileKeepaliveIdle(now: number = Date.now(), timeoutMs: number = this.sessionIdleTimeoutMs): string[] { + if (timeoutMs <= 0) return [] + + const marked: string[] = [] + // Snapshot: a lifecycle write refreshes the cached Session in place. + for (const session of Array.from(this.sessions.values())) { + const progressAt = this.getAgentProgressAt(session) + if (shouldClearKeepaliveIdle(session, progressAt, now, timeoutMs)) { + this.writeLifecycleState(session.id, SESSION_LIFECYCLE_RUNNING) + continue + } + if (!shouldMarkKeepaliveIdle(session, progressAt, now, timeoutMs)) { + continue + } + if (this.writeLifecycleState(session.id, SESSION_LIFECYCLE_IDLE)) { + marked.push(session.id) + } + } + return marked + } + + /** + * Swap `metadata.lifecycleState` between `running` and `idle`, retrying on + * version-mismatch like the other hub-side metadata writers. Best effort: + * a session whose CLI is concurrently rewriting metadata just gets + * reconciled on a later tick. + */ + private writeLifecycleState(sessionId: string, next: typeof SESSION_LIFECYCLE_RUNNING | typeof SESSION_LIFECYCLE_IDLE): boolean { + for (let attempt = 0; attempt < METADATA_RETRY_ATTEMPTS; attempt += 1) { + const session = this.sessions.get(sessionId) + const current = session?.metadata + if (!session || !current) return false + if (current.lifecycleState === next) return false + // Only the running <-> idle pair is ours; never step on `archived` + // or any CLI-authored state. + const expected = next === SESSION_LIFECYCLE_IDLE ? SESSION_LIFECYCLE_RUNNING : SESSION_LIFECYCLE_IDLE + if (current.lifecycleState !== expected) return false + + const result = this.store.sessions.updateSessionMetadata( + sessionId, + { ...current, lifecycleState: next, lifecycleStateSince: Date.now() }, + session.metadataVersion, + session.namespace, + { touchUpdatedAt: false } + ) + if (result.result === 'error') return false + // refreshSession re-reads the row and broadcasts the full session, + // so clients pick up the new lifecycleState without a second emit. + this.refreshSession(sessionId) + if (result.result === 'success') return true + } + return false + } + /** * tiann/hapi#893 (scratchlist v2): emit a `session-updated` SSE patch * carrying `scratchlistUpdatedAt` so other clients viewing the same @@ -1081,6 +1201,7 @@ export class SessionCache { this.lastBroadcastAtBySessionId.delete(sessionId) this.todoBackfillAttemptedSessionIds.delete(sessionId) this.pendingThinkingUntilBySessionId.delete(sessionId) + this.agentProgressAtBySessionId.delete(sessionId) void import('../scratchlistAttachments/storage').then(async ({ deleteScratchlistAttachmentFiles, @@ -1330,6 +1451,13 @@ export class SessionCache { } this.lastBroadcastAtBySessionId.delete(oldSessionId) this.todoBackfillAttemptedSessionIds.delete(oldSessionId) + // The merged history is the new row's progress too — carry the + // clock over so a resume-rotated id does not start out stale. + const oldProgressAt = this.agentProgressAtBySessionId.get(oldSessionId) + if (oldProgressAt !== undefined) { + this.recordAgentProgress(newSessionId, oldProgressAt) + } + this.agentProgressAtBySessionId.delete(oldSessionId) } else { this.refreshSession(oldSessionId) } diff --git a/hub/src/sync/sessionIdle.test.ts b/hub/src/sync/sessionIdle.test.ts new file mode 100644 index 00000000..6a1f872d --- /dev/null +++ b/hub/src/sync/sessionIdle.test.ts @@ -0,0 +1,282 @@ +import { describe, expect, it } 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 type { Session, SyncEvent } from '@hapi/protocol/types' +import { Store } from '../store' +import { registerSessionHandlers } from '../socket/handlers/cli/sessionHandlers' +import type { EventPublisher } from './eventPublisher' +import { SessionCache } from './sessionCache' +import { + DEFAULT_SESSION_IDLE_TIMEOUT_MS, + resolveSessionIdleTimeoutMs, + shouldClearKeepaliveIdle, + shouldMarkKeepaliveIdle, +} from './sessionIdle' + +const HOUR = 60 * 60 * 1000 +const NOW = 1_800_000_000_000 + +function createPublisher(events: SyncEvent[]): EventPublisher { + return { + emit: (event: SyncEvent) => { + events.push(event) + } + } as unknown as EventPublisher +} + +function session(overrides: Partial = {}): Session { + return { + id: 'sid', + namespace: 'default', + seq: 0, + createdAt: NOW - 100 * HOUR, + updatedAt: NOW - 100 * HOUR, + active: true, + activeAt: NOW, + metadata: { path: '/tmp/p', host: 'h', lifecycleState: 'running' }, + metadataVersion: 1, + agentState: null, + agentStateVersion: 1, + thinking: false, + thinkingAt: NOW, + ...overrides + } as Session +} + +describe('resolveSessionIdleTimeoutMs', () => { + it('defaults when unset or unparseable', () => { + expect(resolveSessionIdleTimeoutMs({})).toBe(DEFAULT_SESSION_IDLE_TIMEOUT_MS) + expect(resolveSessionIdleTimeoutMs({ HAPI_SESSION_IDLE_TIMEOUT_MS: ' ' })).toBe(DEFAULT_SESSION_IDLE_TIMEOUT_MS) + expect(resolveSessionIdleTimeoutMs({ HAPI_SESSION_IDLE_TIMEOUT_MS: 'soon' })).toBe(DEFAULT_SESSION_IDLE_TIMEOUT_MS) + expect(resolveSessionIdleTimeoutMs({ HAPI_SESSION_IDLE_TIMEOUT_MS: '-1' })).toBe(DEFAULT_SESSION_IDLE_TIMEOUT_MS) + }) + + it('honours an explicit window, and 0 disables', () => { + expect(resolveSessionIdleTimeoutMs({ HAPI_SESSION_IDLE_TIMEOUT_MS: '3600000' })).toBe(3_600_000) + expect(resolveSessionIdleTimeoutMs({ HAPI_SESSION_IDLE_TIMEOUT_MS: '0' })).toBe(0) + }) +}) + +describe('shouldMarkKeepaliveIdle', () => { + const window = 12 * HOUR + + it('marks a session whose only sign of life is the keepalive', () => { + expect(shouldMarkKeepaliveIdle(session(), NOW - 87 * HOUR, NOW, window)).toBe(true) + }) + + it('leaves a session inside the window alone', () => { + expect(shouldMarkKeepaliveIdle(session(), NOW - 2 * HOUR, NOW, window)).toBe(false) + }) + + it('is disabled by a zero window', () => { + expect(shouldMarkKeepaliveIdle(session(), NOW - 87 * HOUR, NOW, 0)).toBe(false) + }) + + it('never marks work the hub can see', () => { + const stale = NOW - 87 * HOUR + expect(shouldMarkKeepaliveIdle(session({ thinking: true }), stale, NOW, window)).toBe(false) + expect(shouldMarkKeepaliveIdle(session({ backgroundTaskCount: 1 }), stale, NOW, window)).toBe(false) + expect(shouldMarkKeepaliveIdle( + session({ agentState: { requests: { 'req-1': { tool: 'Bash', arguments: {} } } } as Session['agentState'] }), + stale, NOW, window + )).toBe(false) + }) + + it('honours the explicit escape hatch', () => { + const exempt = session({ metadata: { path: '/tmp/p', host: 'h', lifecycleState: 'running', idleReconcileExempt: true } }) + expect(shouldMarkKeepaliveIdle(exempt, NOW - 87 * HOUR, NOW, window)).toBe(false) + }) + + it('only touches live running rows', () => { + const stale = NOW - 87 * HOUR + expect(shouldMarkKeepaliveIdle(session({ active: false }), stale, NOW, window)).toBe(false) + expect(shouldMarkKeepaliveIdle( + session({ metadata: { path: '/tmp/p', host: 'h', lifecycleState: 'archived' } }), + stale, NOW, window + )).toBe(false) + expect(shouldMarkKeepaliveIdle( + session({ metadata: { path: '/tmp/p', host: 'h' } }), + stale, NOW, window + )).toBe(false) + }) +}) + +describe('shouldClearKeepaliveIdle', () => { + const window = 12 * HOUR + const idle = (overrides: Partial = {}) => session({ + metadata: { path: '/tmp/p', host: 'h', lifecycleState: 'idle' }, + ...overrides + }) + + it('wakes on fresh progress', () => { + expect(shouldClearKeepaliveIdle(idle(), NOW - 1 * HOUR, NOW, window)).toBe(true) + }) + + it('does not wake on ambient thinking churn (tiann/hapi#1553) — that would flap every tick', () => { + expect(shouldClearKeepaliveIdle(idle({ thinking: true }), NOW - 87 * HOUR, NOW, window)).toBe(false) + }) + + it('wakes when the escape hatch is set after the fact', () => { + const exempt = session({ metadata: { path: '/tmp/p', host: 'h', lifecycleState: 'idle', idleReconcileExempt: true } }) + expect(shouldClearKeepaliveIdle(exempt, NOW - 87 * HOUR, NOW, window)).toBe(true) + }) + + it('stays idle while nothing has happened', () => { + expect(shouldClearKeepaliveIdle(idle(), NOW - 87 * HOUR, NOW, window)).toBe(false) + }) + + it('ignores sessions that are not idle', () => { + expect(shouldClearKeepaliveIdle(session(), NOW - 1 * HOUR, NOW, window)).toBe(false) + }) +}) + +describe('SessionCache.reconcileKeepaliveIdle', () => { + const window = 12 * HOUR + + function setup() { + const events: SyncEvent[] = [] + const store = new Store(':memory:') + const cache = new SessionCache(store, createPublisher(events)) + const created = cache.getOrCreateSession( + 'tag-1', + { path: '/tmp/project', host: 'localhost', flavor: 'cursor', lifecycleState: 'running' }, + null, + 'default' + ) + // The row is stamped "now"; walk the clock forward instead of + // rewriting persisted timestamps, so `updatedAt` stays honest across + // the refreshSession that a lifecycle write performs. + return { store, cache, events, sessionId: created.id, later: Date.now() + 87 * HOUR } + } + + it('reconciles a keepalive-only session to idle without touching active', () => { + const { cache, sessionId, later } = setup() + + // 87h of keepalives, nothing else — exactly the #1820 sample. + cache.handleSessionAlive({ sid: sessionId, time: Date.now() }) + expect(cache.getSession(sessionId)!.active).toBe(true) + + expect(cache.reconcileKeepaliveIdle(later, window)).toEqual([sessionId]) + + const marked = cache.getSession(sessionId)! + expect(marked.metadata?.lifecycleState).toBe('idle') + // The CLI socket really is up; flipping `active` would arm the + // resume-respawn / dedup / delete paths against a live process. + expect(marked.active).toBe(true) + }) + + it('keepalives alone never wake it back up, but agent progress does', () => { + const { cache, sessionId, later } = setup() + cache.handleSessionAlive({ sid: sessionId, time: Date.now() }) + cache.reconcileKeepaliveIdle(later, window) + expect(cache.getSession(sessionId)!.metadata?.lifecycleState).toBe('idle') + + cache.handleSessionAlive({ sid: sessionId, time: Date.now() }) + cache.reconcileKeepaliveIdle(later, window) + expect(cache.getSession(sessionId)!.metadata?.lifecycleState).toBe('idle') + + cache.recordAgentProgress(sessionId, later) + cache.reconcileKeepaliveIdle(later, window) + expect(cache.getSession(sessionId)!.metadata?.lifecycleState).toBe('running') + }) + + it('survives a hub restart: recent assistant output is not read as idle', () => { + // Needs a file-backed store so the human-turn clock can be backdated + // directly; `touchSessionUpdatedAt` is forward-only by design. + const dir = mkdtempSync(join(tmpdir(), 'hapi-1820-')) + try { + const dbPath = join(dir, 'hapi.db') + const store = new Store(dbPath) + const cache = new SessionCache(store, createPublisher([])) + const sessionId = cache.getOrCreateSession( + 'tag-restart', + { path: '/tmp/project', host: 'localhost', flavor: 'cursor', lifecycleState: 'running' }, + null, + 'default' + ).id + + // Assistant output just now. This deliberately does NOT move + // `updatedAt` (sessionHandlers bumps that for human turns only), so + // the message row is the only durable record of it. + store.messages.addMessage( + sessionId, + { role: 'agent', content: { type: 'text', text: 'still working' } } + ) + // Last human turn was 80h ago. + const raw = new Database(dbPath) + raw.prepare('UPDATE sessions SET updated_at = ? WHERE id = ?') + .run(Date.now() - 80 * HOUR, sessionId) + raw.close() + + // Hub restart: fresh cache over the same store, empty progress map. + const restarted = new SessionCache(store, createPublisher([])) + restarted.reloadAll() + restarted.handleSessionAlive({ sid: sessionId, time: Date.now() }) + + // Seeded from the message, not from the 80h-old `updatedAt`. + expect(restarted.reconcileKeepaliveIdle(Date.now(), window)).toEqual([]) + expect(restarted.getSession(sessionId)!.metadata?.lifecycleState).toBe('running') + + // ...and once that output is itself stale, it does get marked. + expect(restarted.reconcileKeepaliveIdle(Date.now() + 13 * HOUR, window)).toEqual([sessionId]) + expect(restarted.getSession(sessionId)!.metadata?.lifecycleState).toBe('idle') + + } finally { + // finally, not a trailing call: a failing assertion above would + // otherwise leak the temp DB on every run. + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('an assistant message over the socket handler wakes an idle session', () => { + const { store, cache, sessionId, later } = setup() + cache.handleSessionAlive({ sid: sessionId, time: Date.now() }) + cache.reconcileKeepaliveIdle(later, window) + expect(cache.getSession(sessionId)!.metadata?.lifecycleState).toBe('idle') + + // Mirror startHub's wiring: the socket handler's onAgentProgress hook + // feeds the cache clock. A refactor dropping this would silently + // false-idle every actively working session. + const handlers = new Map void>() + const progress: Array<{ sessionId: string; at: number }> = [] + registerSessionHandlers({ + on: (event: string, handler: (payload: unknown) => void) => { + handlers.set(event, handler) + }, + to: () => ({ emit: () => {} }) + } as never, { + store, + resolveSessionAccess: (id: string) => { + const stored = store.sessions.getSessionByNamespace(id, 'default') + return stored ? { ok: true, value: stored } : { ok: false, reason: 'not-found' } + }, + emitAccessError: () => {}, + onAgentProgress: (id: string, at: number) => { + progress.push({ sessionId: id, at }) + cache.recordAgentProgress(id, at) + } + } as never) + + // An *assistant* message: it never bumps `updatedAt`, so the progress + // hook is the only thing that can wake the session. + handlers.get('message')?.({ + sid: sessionId, + message: JSON.stringify({ role: 'agent', content: { type: 'text', text: 'resumed work' } }) + }) + expect(progress).toHaveLength(1) + expect(progress[0].sessionId).toBe(sessionId) + + cache.reconcileKeepaliveIdle(progress[0].at + 1 * HOUR, window) + expect(cache.getSession(sessionId)!.metadata?.lifecycleState).toBe('running') + }) + + it('does nothing when the window is disabled', () => { + const { cache, sessionId, later } = setup() + cache.handleSessionAlive({ sid: sessionId, time: Date.now() }) + + expect(cache.reconcileKeepaliveIdle(later, 0)).toEqual([]) + expect(cache.getSession(sessionId)!.metadata?.lifecycleState).toBe('running') + }) +}) diff --git a/hub/src/sync/sessionIdle.ts b/hub/src/sync/sessionIdle.ts new file mode 100644 index 00000000..ddb04089 --- /dev/null +++ b/hub/src/sync/sessionIdle.ts @@ -0,0 +1,94 @@ +/** + * Keepalive-idle reconciliation (tiann/hapi#1820). + * + * `sessionCache.expireInactive` only expires a session when its `activeAt` + * goes stale, and `session-alive` refreshes `activeAt` every couple of + * seconds for as long as the CLI socket lives. A session whose agent has done + * nothing for days therefore stays `active: true` / `lifecycleState: running` + * forever: socket pinging is being read as agent health. + * + * This module supplies the missing second signal. `active` keeps its existing + * meaning (the CLI is reachable — flipping it would arm resume-respawn, dedup + * merge and delete paths against a session whose process is very much alive); + * `lifecycleState` moves `running` → `idle` once we have seen nothing but + * keepalives for the configured window. + */ + +import { SESSION_LIFECYCLE_IDLE, SESSION_LIFECYCLE_RUNNING } from '@hapi/protocol' +import type { Session } from '@hapi/protocol/types' + +/** Keepalive-only for this long ⇒ reconcile `running` → `idle`. */ +export const DEFAULT_SESSION_IDLE_TIMEOUT_MS = 12 * 60 * 60 * 1000 + +/** + * `HAPI_SESSION_IDLE_TIMEOUT_MS` window, in ms. `0` disables reconciliation + * entirely; an unset or unparseable value falls back to the default. + */ +export function resolveSessionIdleTimeoutMs( + env: Record = process.env +): number { + const raw = env.HAPI_SESSION_IDLE_TIMEOUT_MS + if (raw === undefined || raw.trim() === '') { + return DEFAULT_SESSION_IDLE_TIMEOUT_MS + } + const parsed = Number.parseInt(raw.trim(), 10) + if (!Number.isFinite(parsed) || parsed < 0) { + return DEFAULT_SESSION_IDLE_TIMEOUT_MS + } + return parsed +} + +/** Work the hub can see that must never be reconciled away as a zombie. */ +function hasLiveWork(session: Session): boolean { + if (session.thinking) return true + if ((session.backgroundTaskCount ?? 0) > 0) return true + // A permission / input request waiting on the operator is real state the + // agent is blocked on, not an abandoned socket. + const requests = session.agentState?.requests + if (requests && Object.keys(requests).length > 0) return true + return false +} + +/** + * Should this session be reconciled `running` → `idle` right now? + * + * `agentProgressAt` is the last time the hub observed actual agent progress + * (a message in either direction, a queued prompt, a background task), NOT + * the last keepalive. + */ +export function shouldMarkKeepaliveIdle( + session: Session, + agentProgressAt: number, + now: number, + timeoutMs: number +): boolean { + if (timeoutMs <= 0) return false + // Only sessions the hub still believes are live. An inactive row is #842's + // problem, not this one. + if (!session.active) return false + if (session.metadata?.lifecycleState !== SESSION_LIFECYCLE_RUNNING) return false + if (session.metadata.idleReconcileExempt === true) return false + if (hasLiveWork(session)) return false + return now - agentProgressAt > timeoutMs +} + +/** + * Should an already-`idle` session be reconciled back to `running`? + * + * Only real progress wakes a session, never `thinking`. Cursor ACP emits + * ambient idle/running churn on sessions that are doing nothing + * (tiann/hapi#1553); waking on it would flap the lifecycle — and a DB write + * plus a full-session broadcast — on every 5 s tick. A session that is + * genuinely working emits messages, and those do wake it. + */ +export function shouldClearKeepaliveIdle( + session: Session, + agentProgressAt: number, + now: number, + timeoutMs: number +): boolean { + if (session.metadata?.lifecycleState !== SESSION_LIFECYCLE_IDLE) return false + // Opting out after the fact still lifts an existing mark. + if (session.metadata.idleReconcileExempt === true) return true + return timeoutMs > 0 && now - agentProgressAt <= timeoutMs +} diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index f89103fe..607c26e6 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 { isKnownFlavor, isSteeringSupportedForSession, type LocalResumeTarget, type ResumableSession, type SessionEndReason } from '@hapi/protocol' +import { isKnownFlavor, isLiveLifecycleState, isSteeringSupportedForSession, type LocalResumeTarget, type ResumableSession, type SessionEndReason } from '@hapi/protocol' import { cliBinaryUpdatedOnDisk, isMachineCapabilitySkewed, @@ -619,6 +619,16 @@ export class SyncEngine { this.sessionCache.recordSessionActivity(sessionId, updatedAt) } + /** + * tiann/hapi#1820: any message on the wire is agent progress, whichever + * side authored it. Separate from `recordSessionActivity`, which also + * bumps `updatedAt` and is deliberately restricted to human turns so the + * session list keeps ordering by human interaction. + */ + recordAgentProgress(sessionId: string, at: number): void { + this.sessionCache.recordAgentProgress(sessionId, at) + } + /** * tiann/hapi#893 (scratchlist v2). Read-side: list entries for a * session. Auth / namespace check is the route layer's job (via @@ -947,6 +957,10 @@ export class SyncEngine { this.triggerDedupIfNeeded(session.id) } this.machineCache.expireInactive?.() + // tiann/hapi#1820: `activeAt` expiry above only catches sessions whose + // socket went quiet. Keepalive-only zombies keep `activeAt` fresh + // forever, so reconcile their agent-health signal separately. + this.sessionCache.reconcileKeepaliveIdle() // Piggybacked on the inactivity tick; not a logical part of expireInactive // but shares its 5s cadence (avoids a second timer). this.messageService.releaseMatureScheduledMessages(Date.now(), this.historyActionsInFlight) @@ -1772,11 +1786,13 @@ export class SyncEngine { // running forever and any downstream code that filters by // lifecycleState (not the cache active flag) would keep // treating archived ACP sessions as live. + // tiann/hapi#1820: 'idle' is the same stale-live case as 'running' + // once the row is inactive, so clear it the same way. const oldLifecycle = typeof latest.metadata.lifecycleState === 'string' ? latest.metadata.lifecycleState : undefined const nextMetadata: typeof latest.metadata = { ...latest.metadata, cursorSessionProtocol: 'acp' as const, - ...(oldLifecycle === 'running' ? { lifecycleState: 'archived' as const } : {}) + ...(isLiveLifecycleState(oldLifecycle) ? { lifecycleState: 'archived' as const } : {}) } // Drop the migration-in-progress flag in the same write (see // header comment). Safe whether or not it was set. diff --git a/hub/src/web/routes/sessions.test.ts b/hub/src/web/routes/sessions.test.ts index 3346eb64..8e6afbf7 100644 --- a/hub/src/web/routes/sessions.test.ts +++ b/hub/src/web/routes/sessions.test.ts @@ -1416,6 +1416,32 @@ describe('sessions routes', () => { expect(await response.json()).toEqual({ ok: true }) }) + // tiann/hapi#1820: 'idle' is a live lifecycle. Once a keepalive-only + // session finally loses its socket it must stay archivable, exactly + // like a stale 'running' row — comparing against the 'running' + // literal here would strand it behind a 409. + it('archives an inactive session left in the keepalive-idle lifecycle', async () => { + const calls: string[] = [] + const session = createSession({ + active: false, + metadata: { + path: '/tmp/project', + host: 'localhost', + flavor: 'cursor', + lifecycleState: 'idle' + } + }) + const { app } = createApp(session, { + archiveSession: async (sessionId: string) => { calls.push(sessionId) } + }) + + const response = await app.request('/api/sessions/session-1/archive', { method: 'POST' }) + + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ ok: true }) + expect(calls).toEqual(['session-1']) + }) + it('returns 2xx and skips archiveSession when the row is already archived (idempotent)', async () => { let called = false const session = createSession({ diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index e8fea7ce..dfb21d44 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -4,6 +4,7 @@ import { ForkConversationRequestSchema, ImplementCodexPlanRequestSchema, getPermissionModesForFlavor, + isLiveLifecycleState, isPermissionModeAllowedForFlavor, RenameSessionRequestSchema, SetSessionPinnedRequestSchema, @@ -454,7 +455,10 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho return c.json({ ok: true, alreadyArchived: true }) } - if (!sessionResult.session.active && lifecycleState !== 'running') { + // tiann/hapi#1820: `idle` is a live lifecycle too — a session the hub + // reconciled as keepalive-only must stay archivable once its socket + // finally drops, exactly like a stale `running` row. + if (!sessionResult.session.active && !isLiveLifecycleState(lifecycleState)) { return c.json({ error: 'Session is inactive' }, 409) } diff --git a/shared/package.json b/shared/package.json index a8371503..35dd5bd4 100644 --- a/shared/package.json +++ b/shared/package.json @@ -18,6 +18,7 @@ "./schemas": "./src/schemas.ts", "./sessionCitation": "./src/sessionCitation.ts", "./sessionExport": "./src/sessionExport.ts", + "./sessionLifecycle": "./src/sessionLifecycle.ts", "./types": "./src/types.ts", "./voice": "./src/voice.ts", "./voicePickerCatalog": "./src/voicePickerCatalog.ts", diff --git a/shared/src/index.ts b/shared/src/index.ts index 4fa14330..3e35fdd0 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -16,6 +16,7 @@ export * from './search' export * from './socket' export * from './sessionSummary' export * from './sessionCitation' +export * from './sessionLifecycle' export * from './sessionExport' export * from './piThinkingLevel' export * from './runnerCapabilities' diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index 9177c805..a35260d8 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -112,8 +112,15 @@ export const MetadataSchema = z.object({ hostPid: z.number().optional(), hapiMcpUrl: z.string().url().optional(), startedBy: z.enum(['runner', 'terminal']).optional(), + // 'running' | 'idle' | 'archived' (see shared/src/sessionLifecycle.ts). + // 'idle' is written by the hub's keepalive-idle reconciler (tiann/hapi#1820) + // and reverts to 'running' on the next agent progress. lifecycleState: z.string().optional(), lifecycleStateSince: z.number().optional(), + // Opt out of keepalive-idle reconciliation for sessions that are meant to + // sit quiet indefinitely (operator holding pens, sessions owning work the + // hub cannot see). Never reconciled to 'idle' while true. + idleReconcileExempt: z.boolean().optional(), archivedBy: z.string().optional(), archiveReason: z.string().optional(), // Set only after a completed fresh-session clear. The source row remains diff --git a/shared/src/sessionLifecycle.ts b/shared/src/sessionLifecycle.ts new file mode 100644 index 00000000..9afb3eeb --- /dev/null +++ b/shared/src/sessionLifecycle.ts @@ -0,0 +1,35 @@ +/** + * `metadata.lifecycleState` vocabulary. + * + * Two different liveness signals travel on a Session and they answer + * different questions (tiann/hapi#1820): + * + * - `active` / `activeAt` — **transport** liveness. The CLI socket is + * connected and its `session-alive` keepalive is landing. It says nothing + * about whether the agent behind that socket is doing, or has recently + * done, any work. + * - `metadata.lifecycleState` — **agent** liveness. `running` while the + * session is a live working session, `idle` once the hub has observed + * keepalives with no agent progress for the configured window, `archived` + * once the session is closed. + * + * `idle` is a reversible, non-destructive marker: the session stays `active` + * (its CLI really is reachable and a turn would be served immediately), it is + * simply flagged as keepalive-only so operators and the session list can tell + * a working fleet from a pile of zombies. + */ + +export const SESSION_LIFECYCLE_RUNNING = 'running' +export const SESSION_LIFECYCLE_IDLE = 'idle' +export const SESSION_LIFECYCLE_ARCHIVED = 'archived' + +/** + * True for the lifecycle values that mean "a CLI still owns this session". + * + * Call sites that used to compare against `'running'` literally must use this + * instead, otherwise a session that the hub reconciled to `idle` reads as a + * dead row and becomes eligible for archive-as-stale / migrate-over paths. + */ +export function isLiveLifecycleState(value: unknown): boolean { + return value === SESSION_LIFECYCLE_RUNNING || value === SESSION_LIFECYCLE_IDLE +} diff --git a/web/src/components/SessionList.test.ts b/web/src/components/SessionList.test.ts index c516981b..28a47941 100644 --- a/web/src/components/SessionList.test.ts +++ b/web/src/components/SessionList.test.ts @@ -7,6 +7,7 @@ import { filterActiveSessionsOnly, filterUnreadSessionsOnly, UNKNOWN_MACHINE_ID, + bucketRunningSessions, getSessionTimeRange, getNextSessionVisibleCount, getPullRefreshIndicatorRotation, @@ -653,3 +654,54 @@ describe('getPullRefreshIndicatorRotation', () => { expect(getPullRefreshIndicatorRotation('ready')).toBe(180) }) }) + +describe('bucketRunningSessions', () => { + // tiann/hapi#1820: a keepalive-only session stays `active` (its socket is + // genuinely up) but must not read as a ready session in the list. + const idle = makeSession({ + id: 'idle-1', + active: true, + updatedAt: 10, + metadata: { path: '/p', host: 'h', lifecycleState: 'idle' } as SessionSummary['metadata'] + }) + const quiet = makeSession({ + id: 'quiet-1', + active: true, + updatedAt: 20, + metadata: { path: '/p', host: 'h', lifecycleState: 'running' } as SessionSummary['metadata'] + }) + + it('separates keepalive-only sessions from quiet-but-ready ones', () => { + const buckets = bucketRunningSessions([idle, quiet], true) + + expect(buckets.idle.map((s) => s.id)).toEqual(['idle-1']) + expect(buckets.active.map((s) => s.id)).toEqual(['quiet-1']) + // Exactly one bucket each — the row must not be duplicated. + expect(buckets.working).toHaveLength(0) + expect(buckets.pending).toHaveLength(0) + }) + + it('moves a session out of idle once it is working again', () => { + const woken = { ...idle, thinking: true } + const buckets = bucketRunningSessions([woken, quiet], true) + + expect(buckets.idle).toHaveLength(0) + expect(buckets.working.map((s) => s.id)).toEqual(['idle-1']) + }) + + it('keeps real work ahead of the idle mark', () => { + // An idle-marked session that picked up a background task or a pending + // request belongs in its work bucket, not in idle. + expect(bucketRunningSessions([{ ...idle, backgroundTaskCount: 1 }], true).working).toHaveLength(1) + expect(bucketRunningSessions([{ ...idle, pendingRequestsCount: 1 }], true).pending).toHaveLength(1) + }) + + it('ignores disconnected and pinned sessions', () => { + const buckets = bucketRunningSessions([ + { ...idle, active: false }, + { ...idle, id: 'idle-pinned', pinned: true } + ], true) + + expect(buckets.idle).toHaveLength(0) + }) +}) diff --git a/web/src/components/SessionList.tsx b/web/src/components/SessionList.tsx index 37dd96eb..771c971d 100644 --- a/web/src/components/SessionList.tsx +++ b/web/src/components/SessionList.tsx @@ -1,6 +1,7 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { SessionListScrollAnchor } from './SessionListScrollAnchor' import type { SessionSummary } from '@/types/api' +import { SESSION_LIFECYCLE_IDLE } from '@hapi/protocol' import type { ApiClient } from '@/api/client' import { buildSessionSearchScoreIndex, @@ -78,10 +79,56 @@ const RUNNING_BUCKETS = [ { key: 'working', labelKey: 'session.item.running', colorClass: 'text-[var(--app-badge-success-text)]', pulse: true }, { key: 'pending', labelKey: 'session.item.pending', colorClass: 'text-[var(--app-badge-warning-text)]', pulse: true }, { key: 'active', labelKey: 'session.item.active', colorClass: 'text-[var(--app-hint)]', pulse: false }, + // tiann/hapi#1820: connected, but the hub has seen nothing except + // keepalives for the configured window. Split out so a fleet of zombies + // does not read as a fleet of ready sessions. + { key: 'idle', labelKey: 'session.item.idle', colorClass: 'text-[var(--app-hint)]', pulse: false }, ] as const type RunningBucketKey = (typeof RUNNING_BUCKETS)[number]['key'] +export function emptyRunningBuckets(): Record { + return { working: [], pending: [], active: [], idle: [] } +} + +/** + * Split the connected sessions into the in-progress / active sub-buckets the + * pinned sections render. Pure so the bucketing rules stay testable. + */ +export function bucketRunningSessions( + sessions: SessionSummary[], + pinInProgressSessions: boolean, + compare: (a: SessionSummary, b: SessionSummary) => number = (a, b) => b.updatedAt - a.updatedAt +): Record { + const buckets = emptyRunningBuckets() + if (!pinInProgressSessions) { + return buckets + } + for (const session of sessions) { + if (session.globalPinned || session.pinned) { + continue + } + if (!session.active) { + continue + } + if (session.thinking || (session.backgroundTaskCount ?? 0) > 0) { + buckets.working.push(session) + } else if ((session.pendingRequestsCount ?? 0) > 0) { + buckets.pending.push(session) + } else if (session.metadata?.lifecycleState === SESSION_LIFECYCLE_IDLE) { + // Keepalive-only: socket up, no agent progress for hours. + buckets.idle.push(session) + } else { + // Quiet but connected: finished executing, operator will continue. + buckets.active.push(session) + } + } + for (const key of Object.keys(buckets) as RunningBucketKey[]) { + buckets[key].sort(compare) + } + return buckets +} + /** * Sessions that warrant the optional pinned top sections. * Any connected session floats — a session that just finished executing stays @@ -1332,45 +1379,17 @@ export function SessionList(props: { return [...pinned].sort((a, b) => b.updatedAt - a.updatedAt) }, [machineFilteredSessions, searchScoreIndex, hasTextQuery]) const runningSessions = useMemo(() => { - const buckets: Record = { - working: [], - pending: [], - active: [], - } - if (!pinInProgressSessions) { - return buckets - } - for (const session of machineFilteredSessions) { - if (session.globalPinned || session.pinned) { - continue - } - if (!session.active) { - continue - } - if (session.thinking || (session.backgroundTaskCount ?? 0) > 0) { - buckets.working.push(session) - } else if ((session.pendingRequestsCount ?? 0) > 0) { - buckets.pending.push(session) - } else { - // Quiet but connected: finished executing, operator will continue. - buckets.active.push(session) - } - } - const byRecent = (a: SessionSummary, b: SessionSummary) => b.updatedAt - a.updatedAt const byRelevanceOrRecent = (a: SessionSummary, b: SessionSummary) => { if (searchScoreIndex && hasTextQuery) { return compareSessionsBySearchRelevance(a, b, searchScoreIndex) } - return byRecent(a, b) + return b.updatedAt - a.updatedAt } - for (const key of Object.keys(buckets) as RunningBucketKey[]) { - buckets[key].sort(byRelevanceOrRecent) - } - return buckets + return bucketRunningSessions(machineFilteredSessions, pinInProgressSessions, byRelevanceOrRecent) }, [machineFilteredSessions, pinInProgressSessions, searchScoreIndex, hasTextQuery]) const runningSessionTotal = runningSessions.working.length + runningSessions.pending.length - const activeSessionTotal = runningSessions.active.length + const activeSessionTotal = runningSessions.active.length + runningSessions.idle.length const groups = useMemo( () => { const grouped = groupSessionsByDirectory( @@ -2092,7 +2111,7 @@ export function SessionList(props: { onToggle: () => setActiveSectionCollapsed((value) => !value), pulse: false, count: activeSessionTotal, - bucketKeys: ['active'], + bucketKeys: ['active', 'idle'], })} {groups.map(renderDirectoryGroup)} {actionOnlyGroups.map(renderActionOnlyGroupHeader)} diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index fb62fac6..6fc57569 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -187,6 +187,7 @@ export default { 'session.item.thinking': 'thinking', 'session.item.running': 'Running', 'session.item.active': 'Active', + 'session.item.idle': 'Idle (keepalive only)', 'session.item.permission': 'Permission required', 'session.item.needsInput': 'Needs input', 'session.item.background': 'Background tasks running', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 16333628..25378bb8 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -187,6 +187,7 @@ export default { 'session.item.thinking': '思考中', 'session.item.running': '运行中', 'session.item.active': '活跃', + 'session.item.idle': '空闲(仅心跳)', 'session.item.permission': '需要权限', 'session.item.needsInput': '需要输入', 'session.item.background': '后台任务运行中', From ca1fd80afdaa41748aec9ea0ee2bc416249a012a Mon Sep 17 00:00:00 2001 From: SSU-WEI HUANG Date: Wed, 16 Sep 2026 08:12:16 +0800 Subject: [PATCH 10/34] fix(cursor): pin Auto to CLI --model auto instead of account default (#1819) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(cursor): pin Auto to CLI --model auto instead of account default Selecting Auto was treated as unset/ACP default[] after the Default→Auto rename. Persist and spawn `auto` so the picker matches `agent --list-models`. Co-authored-by: Cursor * fix(cursor): keep live ACP model until Auto actually applies Pin session.model to auto for the next `--model auto` spawn, but do not claim the live backend switched when ACP only advertises default[]. Co-authored-by: Cursor * fix(cursor): reject live Auto unless ACP auto or spawn confirmed it Do not persist Auto when the running catalog has no auto option. Clear the spawn-auto flag after a concrete model apply so Auto → concrete → Auto cannot fake a live switch. Co-authored-by: Cursor * fix(cursor): keep ACP wire ids spawn-safe and apply effort Cursor's parameterized picker (`clientCapabilities._meta.parameterizedModelPicker`) advertises bare model bases plus separate `fast` / `thought_level` config options. `buildCursorModelsSnapshotFromAcp` synthesized every base as `${base}[fast=${fast}]`, and Cursor rejects any bracket id whose parameter set is not that model's complete set, so 74 of the 76 published picker ids failed at ACP `session/new` with `Cannot use this model` (#1818). - Stop synthesizing wire ids: keep the advertised values verbatim (bare bases are accepted by `--model`, defaults applied). Parameter sets differ per model, so a synthesized id cannot be validated from the options alone. - Flag such catalogs as `parameterized` so variant CLI skus still attach to their base rows — the ACP apply path expresses them through config options. - Apply effort in `applyParameterizedCursorModel` (ids `effort`, `reasoning`, `reasoning_effort`), applied against the config options Cursor re-advertises for the newly selected model, and skipped on models without that axis. - Match CLI sku bases across Cursor's legacy `cursor-` family prefix (`cursor-grok-4.6-high` → ACP base `grok-4.6`) so those variant rows are not dropped. - Version the shared on-disk catalog cache (v2) so runners that already cached the rejected synthesized ids re-probe instead of serving them. Verified with live `cursor-agent 2026.09.10-fd3934a` ACP runs: the catalog no longer contains bracket ids, every advertised base and sampled variant sku spawns, and in-session `claude-opus-4-8-low` / `cursor-grok-4.6-low` set the matching `effort`/`reasoning` option. * test(cursor): cover aliased effort ids and thinking coexistence Covers the branches the HAPI bot review called out for #1818: the `xhigh` → `extra-high` alias on `gpt-5.5` (`reasoning`), the `reasoning_effort` id used by `gemini-3.8-flash`, and switching effort on a model that also advertises Claude's separate `thought_level` `thinking` toggle. * test(cursor): cover legacy sku base and post-switch effort option Adds the two apply-path cases the HAPI bot review called out for #1818: resolving `cursor-grok-4.6-high` onto an advertised `grok-4.6` base, and reading the effort option Cursor advertises for the newly selected model (`reasoning` for gpt-5.5 → `effort` for claude-opus-4-8) instead of the previous model's options. * test(cursor): create the cache dir in the migration test The version-envelope test wrote $HAPI_HOME/cache/cursor-models.json without creating the directory, so running it alone (or filtering with -t) failed with ENOENT before the assertion; it only passed because sibling tests in the same file had already created the path. Reported in the HAPI bot review of #1822. Verified: `vitest run ... -t 'ignores pre-versioned'` → 1 passed, whole file → 4 passed, and every other changed test file passes when run standalone. * Clarify Cursor Auto live-switch limitation in session pickers * Reconcile partial Cursor model changes before acknowledging Auto * Serialize Cursor model changes across clients with the existing async lock --------- Co-authored-by: Cursor --- .../cursor/cursorAcpRemoteLauncher.test.ts | 244 ++++++++++++++++-- cli/src/cursor/cursorAcpRemoteLauncher.ts | 82 +++--- cli/src/cursor/utils/cursorAcpBackend.test.ts | 10 +- cli/src/cursor/utils/cursorAcpBackend.ts | 12 +- cli/src/cursor/utils/cursorAcpModelsBridge.ts | 2 + .../utils/cursorAcpModelsSnapshot.test.ts | 12 +- .../cursor/utils/cursorAcpModelsSnapshot.ts | 60 ++--- cli/src/cursor/utils/cursorModeConfig.test.ts | 220 +++++++++++++++- cli/src/cursor/utils/cursorModeConfig.ts | 120 +++++++-- .../utils/cursorStaleModelRemap.test.ts | 5 + cli/src/cursor/utils/cursorStaleModelRemap.ts | 18 +- cli/src/modules/common/cursorAcpModelProbe.ts | 3 +- cli/src/modules/common/cursorModels.test.ts | 44 ++++ cli/src/modules/common/cursorModels.ts | 30 ++- .../common/cursorModelsSharedCache.test.ts | 19 +- .../modules/common/cursorModelsSharedCache.ts | 23 +- e2e/composer-copy.spec.ts | 16 +- shared/src/apiTypes.ts | 10 +- shared/src/cursorCliSku.test.ts | 41 +++ shared/src/cursorCliSku.ts | 44 ++++ web/README.md | 1 + .../AssistantChat/HappyComposer.tsx | 7 +- .../AssistantChat/modelOptions.test.ts | 10 +- .../components/AssistantChat/modelOptions.ts | 4 +- web/src/components/NewSession/index.tsx | 4 +- web/src/components/SessionChat.tsx | 6 +- web/src/lib/cursorCliSkuCatalog.test.ts | 22 ++ web/src/lib/cursorModelOptions.test.ts | 2 +- web/src/lib/cursorModelOptions.ts | 43 ++- web/src/lib/cursorPickerState.ts | 12 +- web/src/lib/locales/en.ts | 1 + web/src/lib/locales/zh-CN.ts | 1 + web/src/lib/sessionChatCursorModel.test.ts | 28 ++ web/src/lib/sessionChatCursorModel.ts | 20 +- 34 files changed, 977 insertions(+), 199 deletions(-) diff --git a/cli/src/cursor/cursorAcpRemoteLauncher.test.ts b/cli/src/cursor/cursorAcpRemoteLauncher.test.ts index 010b4bd0..bc283a72 100644 --- a/cli/src/cursor/cursorAcpRemoteLauncher.test.ts +++ b/cli/src/cursor/cursorAcpRemoteLauncher.test.ts @@ -10,6 +10,7 @@ const harness = vi.hoisted(() => ({ loadSessionError: null as Error | null, newSessionError: null as Error | null, failSetConfigOption: false, + failFastConfigOption: false, supportsLoadSession: true, loadSessionCalled: false, newSessionCalled: false, @@ -26,6 +27,15 @@ const harness = vi.hoisted(() => ({ promptStderrErrors: [] as Array<{ type: string; message: string; raw: string }>, releasePrompt: null as (() => void) | null, backendArgs: null as { command: string; args?: string[] } | null, + modelOptionValues: [ + 'default[]', + 'composer-2.5[fast=true]', + 'composer-2.5[fast=false]', + 'gpt-5.3-codex[reasoning=medium,fast=false]', + 'gpt-5.3-codex[reasoning=medium,fast=true]', + 'cursor-grok-4.5-medium', + 'cursor-grok-4.5-medium-fast', + ] as string[], setConfigOptionCalls: [] as Array<{ sessionId: string; configId: string; value: string }>, deferSetConfigOption: null as Promise | null, releaseSetConfigOption: null as (() => void) | null, @@ -48,8 +58,11 @@ vi.mock('./utils/cursorAcpBackend', () => ({ createCursorAcpBackend: vi.fn((opts?: { model?: string | null }) => { const args = ['acp']; const model = opts?.model?.trim(); - if (model && model !== 'auto' && model !== 'default' && model !== 'default[]') { - args.unshift('--model', model); + const spawn = !model + ? null + : (model === 'auto' || model === 'default' || model === 'default[]' ? 'auto' : model); + if (spawn) { + args.unshift('--model', spawn); } harness.backendArgs = { command: 'agent', args }; return { @@ -96,6 +109,9 @@ vi.mock('./utils/cursorAcpBackend', () => ({ if (harness.failSetConfigOption && configId === 'model-opt') { throw new Error('set_config_option rejected'); } + if (harness.failFastConfigOption && configId === 'fast') { + throw new Error('fast update rejected'); + } harness.setConfigOptionCalls.push({ sessionId, configId, value }); }), pinSessionModelWireId: vi.fn(), @@ -111,6 +127,12 @@ vi.mock('./utils/cursorAcpBackend', () => ({ currentModelId: 'composer-2.5[fast=true]' })), getConfigOptionByCategory: vi.fn((_sessionId: string, category: string) => { + if (category === 'fast' && harness.failFastConfigOption) { + return { + id: 'fast', + options: [{ value: 'false' }, { value: 'true' }] + }; + } if (category === 'mode') { return { id: 'mode-opt', @@ -124,15 +146,7 @@ vi.mock('./utils/cursorAcpBackend', () => ({ if (category === 'model') { return { id: 'model-opt', - options: [ - { value: 'default[]' }, - { value: 'composer-2.5[fast=true]' }, - { value: 'composer-2.5[fast=false]' }, - { value: 'gpt-5.3-codex[reasoning=medium,fast=false]' }, - { value: 'gpt-5.3-codex[reasoning=medium,fast=true]' }, - { value: 'cursor-grok-4.5-medium' }, - { value: 'cursor-grok-4.5-medium-fast' }, - ] + options: harness.modelOptionValues.map((value) => ({ value })) }; } return undefined; @@ -285,6 +299,16 @@ describe('cursorAcpRemoteLauncher', () => { harness.loadSessionError = null; harness.newSessionError = null; harness.failSetConfigOption = false; + harness.failFastConfigOption = false; + harness.modelOptionValues = [ + 'default[]', + 'composer-2.5[fast=true]', + 'composer-2.5[fast=false]', + 'gpt-5.3-codex[reasoning=medium,fast=false]', + 'gpt-5.3-codex[reasoning=medium,fast=true]', + 'cursor-grok-4.5-medium', + 'cursor-grok-4.5-medium-fast', + ]; harness.supportsLoadSession = true; harness.loadSessionCalled = false; harness.newSessionCalled = false; @@ -596,6 +620,15 @@ describe('cursorAcpRemoteLauncher', () => { expect(legacyLauncher).not.toHaveBeenCalled(); }); + it('pins CLI auto with --model auto on spawn', async () => { + const session = makeSession(null); + session.model = 'auto'; + await cursorAcpRemoteLauncher(session); + + expect(harness.backendArgs).toEqual({ command: 'agent', args: ['--model', 'auto', 'acp'] }); + expect(session.model).toBe('auto'); + }); + it('applies harness thinking transitions once per edge (#1470)', async () => { const keepAlive = vi.fn(); const queue = new MessageQueue2(() => 'mode'); @@ -1533,7 +1566,7 @@ describe('cursorAcpRemoteLauncher', () => { await runPromise; }); - it('applies ACP default model when setModel is cleared', async () => { + it('does not claim live Auto when ACP has no auto option', async () => { const queue = new MessageQueue2((mode) => mode.permissionMode); const client = { rpcHandlerManager: { registerHandler: vi.fn() }, @@ -1575,16 +1608,14 @@ describe('cursorAcpRemoteLauncher', () => { }); harness.setConfigOptionCalls.length = 0; - session.setModel(null); + session.setModel('auto'); await vi.waitFor(() => { - expect( - harness.setConfigOptionCalls.some( - (call) => call.configId === 'model-opt' && call.value === 'default[]' - ) - ).toBe(true); - expect(session.model).toBeUndefined(); + expect(session.model).toBe('composer-2.5[fast=false]'); }); + await new Promise((resolve) => setTimeout(resolve, 30)); + expect(session.model).toBe('composer-2.5[fast=false]'); + expect(harness.setConfigOptionCalls.filter((call) => call.configId === 'model-opt')).toEqual([]); queue.close(); await runPromise; @@ -1634,7 +1665,7 @@ describe('cursorAcpRemoteLauncher', () => { await runPromise; }); - it('applyModelConfig(null) resets ACP to the default model option', async () => { + it('rejects live applyModelConfig Auto when ACP has no auto option', async () => { const queue = new MessageQueue2((mode) => mode.permissionMode); const client = { rpcHandlerManager: { registerHandler: vi.fn() }, @@ -1669,11 +1700,59 @@ describe('cursorAcpRemoteLauncher', () => { await session.applyModelConfig('composer-2.5[fast=false]'); harness.setConfigOptionCalls.length = 0; - await session.applyModelConfig(null); + await expect(session.applyModelConfig('auto')).rejects.toThrow( + 'Cursor Auto requires restarting with --model auto' + ); + expect(session.model).toBe('composer-2.5[fast=false]'); + expect(harness.setConfigOptionCalls.filter((call) => call.configId === 'model-opt')).toEqual([]); + + queue.close(); + await runPromise; + }); + + it('applies Auto via ACP when the catalog advertises auto', async () => { + harness.modelOptionValues = ['auto', 'composer-2.5[fast=false]']; + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn(); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + + await session.applyModelConfig('composer-2.5[fast=false]'); + harness.setConfigOptionCalls.length = 0; + + await session.applyModelConfig('auto'); + + expect(session.model).toBe('auto'); expect( harness.setConfigOptionCalls.some( - (call) => call.configId === 'model-opt' && call.value === 'default[]' + (call) => call.configId === 'model-opt' && call.value === 'auto' ) ).toBe(true); @@ -1681,6 +1760,127 @@ describe('cursorAcpRemoteLauncher', () => { await runPromise; }); + it('rejects applyModelConfig Auto when advertised auto cannot be set', async () => { + harness.modelOptionValues = ['auto', 'composer-2.5[fast=false]']; + harness.failSetConfigOption = true; + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn(); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + + await expect(session.applyModelConfig('auto')).rejects.toThrow( + 'Cursor auto model is not available via ACP' + ); + expect(session.model).not.toBe('auto'); + + queue.close(); + await runPromise; + }); + + it.each([[false, false], [true, false], [false, true], [true, true]])('rejects Auto after an Auto-spawned concrete switch (partial=%s, concurrent=%s)', async (partial, concurrent) => { + const queue = new MessageQueue2((mode) => mode.permissionMode); + const client = { + rpcHandlerManager: { registerHandler: vi.fn() }, + updateMetadata: vi.fn(), + flushMetadata: vi.fn(async () => true), + sendSessionEvent: vi.fn(), + sendAgentMessage: vi.fn(), + keepAlive: vi.fn(), + emitSessionReady: vi.fn() + } as unknown as ApiSessionClient; + + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default', + model: 'auto' + }); + session.onSessionFoundWithProtocol = vi.fn(); + queue.push('hold-open', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.newSessionCalled).toBe(true)); + await vi.waitFor(() => expect(session.canApplyModelConfig()).toBe(true)); + expect(harness.backendArgs).toEqual({ command: 'agent', args: ['--model', 'auto', 'acp'] }); + + if (partial) { + harness.modelOptionValues = ['default', 'composer-2.5']; + harness.failFastConfigOption = true; + } + if (concurrent) { + harness.deferSetConfigOption = new Promise((resolve) => { + harness.releaseSetConfigOption = resolve; + }); + } + const concreteRequest = session.applyModelConfig('composer-2.5[fast=false]'); + const autoRequest = concurrent + ? session.applyModelConfig('auto').then( + value => ({ value, error: null }), + error => ({ value: null, error }) + ) + : null; + if (concurrent) { + await new Promise(resolve => setImmediate(resolve)); + harness.releaseSetConfigOption?.(); + } + if (partial) { + await expect(concreteRequest).rejects.toThrow( + 'Cursor model is not available via ACP' + ); + } else { + await concreteRequest; + } + if (autoRequest) { + expect((await autoRequest).error?.message).toContain('Cursor Auto requires restarting with --model auto'); + } + const concreteModel = partial ? 'composer-2.5' : 'composer-2.5[fast=false]'; + expect(session.model).toBe(concreteModel); + harness.setConfigOptionCalls.length = 0; + + await expect(session.applyModelConfig('auto')).rejects.toThrow( + 'Cursor Auto requires restarting with --model auto' + ); + expect(session.model).toBe(concreteModel); + expect(harness.setConfigOptionCalls.filter((call) => call.configId === 'model-opt')).toEqual([]); + + queue.close(); + await runPromise; + }); + it('rejects applyModelConfig when ACP does not expose the requested model', async () => { const queue = new MessageQueue2((mode) => mode.permissionMode); const client = { diff --git a/cli/src/cursor/cursorAcpRemoteLauncher.ts b/cli/src/cursor/cursorAcpRemoteLauncher.ts index 5130a17c..8ac1c978 100644 --- a/cli/src/cursor/cursorAcpRemoteLauncher.ts +++ b/cli/src/cursor/cursorAcpRemoteLauncher.ts @@ -1,6 +1,7 @@ import React from 'react'; import { randomUUID } from 'node:crypto'; import { logger } from '@/ui/logger'; +import { AsyncLock } from '@/utils/lock'; import { buildHapiMcpBridge } from '@/codex/utils/buildHapiMcpBridge'; import { convertAgentMessage } from '@/agent/messageConverter'; import { PermissionAdapter } from '@/agent/permissionAdapter'; @@ -28,6 +29,7 @@ import { resolveCursorModeAfterPlanApproval, wireIdForCursorSessionState } from './utils/cursorModeConfig'; +import { CURSOR_AUTO_MODEL_ID, cursorSpawnModelId, isCursorAutoModelId } from '@hapi/protocol'; import { CURSOR_PLAN_CONTINUE } from './utils/cursorPlanContinue'; import { cursorPassThroughStatusMessage, parseCursorSpecialCommand } from './cursorSpecialCommands'; import { buildCursorModelsSeedPayload, seedCursorModelsCache } from '@/modules/common/cursorModels'; @@ -66,7 +68,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { private currentBackendModel: string | null = null; private defaultBackendModel: string | null = null; private unregisterModelApplyHandler: (() => void) | null = null; - private modelApplySeq = 0; + private readonly modelApplyLock = new AsyncLock(); private activePromptModeHash: string | null = null; /** True while a backend.prompt turn is in flight. */ private promptInFlight = false; @@ -74,6 +76,8 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { private softSteerWaiters: Promise[] = []; /** True when ACP process was spawned with `--auto-review`. */ private spawnedWithAutoReview = false; + /** True when this ACP process was spawned with `--model auto`. */ + private spawnedWithCliAuto = false; /** Avoid re-queueing `/auto-review` on every mid-session mode sync. */ private autoReviewSlashQueued = false; private cursorMcpOverlay: CursorMcpOverlayHandle | null = null; @@ -368,6 +372,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { throw new Error('Failed to establish Cursor ACP session'); } this.acpSessionId = acpSessionId; + this.spawnedWithCliAuto = cursorSpawnModelId(spawnModel) === CURSOR_AUTO_MODEL_ID; if (acpSessionId !== resumeSessionId) { session.onSessionFoundWithProtocol(acpSessionId, 'acp'); @@ -410,7 +415,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { optimistic: false, throwOnFailure: mustRestoreDesiredModel }); - } else if (this.currentBackendModel && !isSpawnDefaultModel(this.currentBackendModel)) { + } else if (this.currentBackendModel && !isCursorAutoModelId(this.currentBackendModel)) { this.pushModelStatusLine(this.currentBackendModel); } @@ -944,34 +949,54 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { model: string | null | undefined, previousSetModel: CursorSession['setModel'], options: { optimistic: boolean; throwOnFailure: boolean } + ): Promise { + return this.modelApplyLock.inLock(() => + this.applyLiveModelLocked(backend, acpSessionId, model, previousSetModel, options)); + } + + private async applyLiveModelLocked( + backend: AcpSdkBackend, + acpSessionId: string, + model: string | null | undefined, + previousSetModel: CursorSession['setModel'], + options: { optimistic: boolean; throwOnFailure: boolean } ): Promise { const requested = model?.trim(); const previousModel = this.currentBackendModel ?? this.session.model ?? null; - const applySeq = ++this.modelApplySeq; - if (!requested || isSpawnDefaultModel(requested)) { + if (!requested || isCursorAutoModelId(requested)) { const modelOption = backend.getConfigOptionByCategory?.(acpSessionId, 'model'); - const defaultWire = modelOption?.options?.find( - (option) => isSpawnDefaultModel(option.value) + const autoWire = modelOption?.options?.find( + (option) => option.value.trim().toLowerCase() === CURSOR_AUTO_MODEL_ID )?.value; - if (modelOption && defaultWire && backend.setConfigOption) { + let appliedLive = false; + if (modelOption && autoWire && backend.setConfigOption) { try { - await backend.setConfigOption(acpSessionId, modelOption.id, defaultWire); - backend.pinSessionModelWireId(acpSessionId, defaultWire); + await backend.setConfigOption(acpSessionId, modelOption.id, autoWire); + backend.pinSessionModelWireId(acpSessionId, autoWire); + appliedLive = true; } catch (error) { - logger.debug('[cursor-acp] Failed to set default model via ACP', error); + logger.debug('[cursor-acp] Failed to set auto model via ACP', error); if (options.throwOnFailure) { - throw new Error('Cursor default model is not available via ACP'); + throw new Error('Cursor auto model is not available via ACP'); } } - } else if (options.throwOnFailure) { - throw new Error('Cursor default model is not available via ACP'); } - this.currentBackendModel = null; - previousSetModel(undefined); + // Live ACP catalogs usually advertise `default[]`, which is not CLI + // Auto (#1817). Only acknowledge Auto after a confirmed spawn or ACP + // `auto` option. In-session Auto without either requires a restart. + if (!appliedLive && !this.spawnedWithCliAuto) { + if (options.throwOnFailure) { + throw new Error('Cursor Auto requires restarting with --model auto'); + } + return previousModel; + } + previousSetModel(CURSOR_AUTO_MODEL_ID); + this.currentBackendModel = CURSOR_AUTO_MODEL_ID; + this.pushModelStatusLine(CURSOR_AUTO_MODEL_ID); this.session.pushKeepAlive(); syncCursorModelsFromAcp(backend, acpSessionId); - return null; + return CURSOR_AUTO_MODEL_ID; } if (options.optimistic) { @@ -982,15 +1007,23 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { } const result = await applyCursorAcpModel(backend, acpSessionId, requested); + if (result.applied || result.partiallyAppliedWireId) { + this.spawnedWithCliAuto = false; + } if (!result.applied || !result.resolvedWireId) { const message = `Cursor model is not available via ACP: ${requested}`; logger.warn(`[cursor-acp] ${message}`); - if (options.optimistic && applySeq === this.modelApplySeq) { + if (result.partiallyAppliedWireId) { + this.currentBackendModel = result.partiallyAppliedWireId; + previousSetModel(result.partiallyAppliedWireId); + this.pushModelStatusLine(result.partiallyAppliedWireId); + this.session.pushKeepAlive(); + } else if (options.optimistic) { this.currentBackendModel = previousModel; previousSetModel(previousModel ?? undefined); this.session.pushKeepAlive(); - } else if (!options.throwOnFailure && previousModel && !isSpawnDefaultModel(previousModel)) { + } else if (!options.throwOnFailure && previousModel && !isCursorAutoModelId(previousModel)) { this.currentBackendModel = previousModel; previousSetModel(previousModel); this.session.pushKeepAlive(); @@ -1000,7 +1033,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { if (options.throwOnFailure) { throw new Error(message); } - return previousModel; + return result.partiallyAppliedWireId ?? previousModel; } const sessionWire = wireIdForCursorSessionState( @@ -1008,10 +1041,6 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { result.resolvedWireId ); - if (applySeq !== this.modelApplySeq) { - return this.currentBackendModel; - } - const changed = sessionWire !== this.currentBackendModel || this.session.model !== sessionWire; this.currentBackendModel = sessionWire; previousSetModel(sessionWire); @@ -1025,7 +1054,7 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { private pushModelStatusLine(model: string | null | undefined): void { const trimmed = model?.trim(); - if (!trimmed || isSpawnDefaultModel(trimmed)) { + if (!trimmed || isCursorAutoModelId(trimmed)) { this.messageBuffer.addMessage('[MODEL:auto]', 'system'); return; } @@ -1236,11 +1265,6 @@ function formatAcpLoadError(error: unknown): Record { return { message: String(error) }; } -function isSpawnDefaultModel(modelId: string): boolean { - const normalized = modelId.trim().toLowerCase(); - return normalized === 'auto' || normalized === 'default' || normalized === 'default[]'; -} - function syncCursorModelsFromAcp(backend: AcpSdkBackend, acpSessionId: string): void { const snapshot = buildCursorModelsSnapshotFromAcp(backend, acpSessionId); if (!snapshot) { diff --git a/cli/src/cursor/utils/cursorAcpBackend.test.ts b/cli/src/cursor/utils/cursorAcpBackend.test.ts index 43cfe308..03c8b064 100644 --- a/cli/src/cursor/utils/cursorAcpBackend.test.ts +++ b/cli/src/cursor/utils/cursorAcpBackend.test.ts @@ -30,8 +30,14 @@ describe('createCursorAcpBackend', () => { ]); }); - it('omits --model for default/auto spawn selection', () => { - expect(buildCursorAcpArgs({ model: 'auto' })).toEqual(['acp']); + it('pins CLI auto with --model auto', () => { + expect(buildCursorAcpArgs({ model: 'auto' })).toEqual(['--model', 'auto', 'acp']); + expect(buildCursorAcpArgs({ model: 'default[]' })).toEqual(['--model', 'auto', 'acp']); + }); + + it('omits --model when spawn model is unset', () => { + expect(buildCursorAcpArgs({ model: null })).toEqual(['acp']); + expect(buildCursorAcpArgs({})).toEqual(['acp']); }); it('adds --auto-review, --worktree, and --add-dir before acp', () => { diff --git a/cli/src/cursor/utils/cursorAcpBackend.ts b/cli/src/cursor/utils/cursorAcpBackend.ts index a1c3ea9e..e3955bba 100644 --- a/cli/src/cursor/utils/cursorAcpBackend.ts +++ b/cli/src/cursor/utils/cursorAcpBackend.ts @@ -1,5 +1,6 @@ import { basename, join } from 'node:path'; import { homedir } from 'node:os'; +import { cursorSpawnModelId } from '@hapi/protocol'; import { AcpSdkBackend } from '@/agent/backends/acp'; import { getAgentLaunchCommand } from '@/agent/agentLaunchCommand'; @@ -13,12 +14,6 @@ function filterEnv(env: NodeJS.ProcessEnv): Record { return result; } -function isDefaultSpawnModel(model: string | null | undefined): boolean { - if (!model) return true; - const normalized = model.trim().toLowerCase(); - return normalized === 'auto' || normalized === 'default' || normalized === 'default[]'; -} - export type CursorAcpBackendOptions = { cwd: string; model?: string | null; @@ -58,8 +53,9 @@ export function buildCursorAcpArgs(opts: Omit): } } - if (!isDefaultSpawnModel(opts.model)) { - args.push('--model', opts.model!.trim()); + const spawnModel = cursorSpawnModelId(opts.model); + if (spawnModel) { + args.push('--model', spawnModel); } args.push('acp'); diff --git a/cli/src/cursor/utils/cursorAcpModelsBridge.ts b/cli/src/cursor/utils/cursorAcpModelsBridge.ts index 89efbc42..6703731c 100644 --- a/cli/src/cursor/utils/cursorAcpModelsBridge.ts +++ b/cli/src/cursor/utils/cursorAcpModelsBridge.ts @@ -3,6 +3,8 @@ import type { CursorModelSummary } from '@hapi/protocol/apiTypes'; export type CursorModelsSnapshot = { availableModels: CursorModelSummary[]; currentModelId: string | null; + /** ACP advertised the parameterized picker (bare bases + fast/thought_level options). */ + parameterized?: boolean; }; let snapshot: CursorModelsSnapshot | null = null; diff --git a/cli/src/cursor/utils/cursorAcpModelsSnapshot.test.ts b/cli/src/cursor/utils/cursorAcpModelsSnapshot.test.ts index 8b4903c3..860a0689 100644 --- a/cli/src/cursor/utils/cursorAcpModelsSnapshot.test.ts +++ b/cli/src/cursor/utils/cursorAcpModelsSnapshot.test.ts @@ -48,7 +48,7 @@ describe('buildCursorModelsSnapshotFromAcp', () => { expect(snapshot?.availableModels).toHaveLength(2); }); - it('synthesizes Composer fast variants from parameterized model + fast config options', () => { + it('keeps parameterized model + fast options as bare bases without synthesizing wires', () => { const backend = { getSessionModelsMetadata: () => ({ availableModels: [{ modelId: 'composer-2.5', name: 'Composer 2.5' }], @@ -87,10 +87,10 @@ describe('buildCursorModelsSnapshotFromAcp', () => { const snapshot = buildCursorModelsSnapshotFromAcp(backend, 's1'); - expect(snapshot?.availableModels.map((entry) => entry.modelId).sort()).toEqual([ - 'composer-2.5[fast=false]', - 'composer-2.5[fast=true]' - ]); - expect(snapshot?.currentModelId).toBe('composer-2.5[fast=false]'); + // `composer-2.5[fast=…]` is rejected by Cursor's `--model` whenever the wire + // omits another parameter of the model, so only the bare base is advertised. + expect(snapshot?.availableModels.map((entry) => entry.modelId)).toEqual(['composer-2.5']); + expect(snapshot?.currentModelId).toBe('composer-2.5'); + expect(snapshot?.parameterized).toBe(true); }); }); diff --git a/cli/src/cursor/utils/cursorAcpModelsSnapshot.ts b/cli/src/cursor/utils/cursorAcpModelsSnapshot.ts index 5c3b27e2..09446899 100644 --- a/cli/src/cursor/utils/cursorAcpModelsSnapshot.ts +++ b/cli/src/cursor/utils/cursorAcpModelsSnapshot.ts @@ -4,6 +4,8 @@ import type { CursorModelSummary } from '@hapi/protocol/apiTypes'; export type CursorModelsSnapshot = { availableModels: CursorModelSummary[]; currentModelId: string | null; + /** ACP advertised the parameterized picker (bare bases + fast/thought_level options). */ + parameterized?: boolean; }; type CursorAcpModelSnapshotBackend = Pick @@ -39,8 +41,16 @@ function mergeModelEntries( } /** - * Zed-style Cursor catalog: `configOptions` model category lists every wire id; + * Zed-style Cursor catalog: `configOptions` model category lists every model id; * `availableModels` alone is often one variant per base family. + * + * Cursor's parameterized picker advertises bare model bases plus separate + * `fast` / `thought_level` config options. Cursor rejects every bracket id whose + * parameter set is not that model's complete set, and those per-model sets are not + * derivable from the options, so no wire ids are ever synthesized here: the + * advertised values are kept verbatim (bare bases are accepted by `--model`, with + * defaults applied) and the requested parameters are applied over ACP config + * options by `applyParameterizedCursorModel`. */ export function buildCursorModelsSnapshotFromAcp( backend: CursorAcpModelSnapshotBackend, @@ -48,38 +58,14 @@ export function buildCursorModelsSnapshotFromAcp( ): CursorModelsSnapshot | null { const metadata = backend.getSessionModelsMetadata(sessionId); const modelOption = findConfigOption(backend, sessionId, 'model'); - const fastOption = findConfigOption(backend, sessionId, 'fast'); if (!metadata && !modelOption) { return null; } const merged = new Map(); - const parameterizedFastModels: CursorModelSummary[] = []; - if (modelOption?.options?.length && fastOption?.options?.length) { - const fastValues = fastOption.options - .map((option) => option.value.trim()) - .filter((value) => value === 'false' || value === 'true'); - if (fastValues.length > 0) { - for (const option of modelOption.options) { - const modelId = option.value.trim(); - if (!modelId || modelId.includes('[')) { - continue; - } - for (const fast of fastValues) { - parameterizedFastModels.push({ - modelId: `${modelId}[fast=${fast}]`, - name: option.name - }); - } - } - } - } - - if (parameterizedFastModels.length > 0) { - mergeModelEntries(merged, parameterizedFastModels); - } else if (modelOption?.options?.length) { + if (modelOption?.options?.length) { mergeModelEntries(merged, modelOption.options.map((option) => ({ modelId: option.value, name: option.name @@ -87,26 +73,24 @@ export function buildCursorModelsSnapshotFromAcp( } if (metadata?.availableModels?.length) { - mergeModelEntries( - merged, - parameterizedFastModels.length > 0 - ? metadata.availableModels.filter((entry) => entry.modelId.includes('[')) - : metadata.availableModels - ); + mergeModelEntries(merged, metadata.availableModels); } if (merged.size === 0) { return null; } - const currentModelId = parameterizedFastModels.length > 0 && modelOption?.currentValue && fastOption?.currentValue - ? `${modelOption.currentValue}[fast=${fastOption.currentValue}]` - : metadata?.currentModelId - ?? modelOption?.currentValue - ?? null; + const parameterized = Boolean( + modelOption?.options?.length + && modelOption.options.every((option) => { + const value = option.value.trim(); + return value.length > 0 && !value.includes('['); + }) + ); return { availableModels: [...merged.values()], - currentModelId + currentModelId: metadata?.currentModelId ?? modelOption?.currentValue ?? null, + ...(parameterized ? { parameterized: true } : {}) }; } diff --git a/cli/src/cursor/utils/cursorModeConfig.test.ts b/cli/src/cursor/utils/cursorModeConfig.test.ts index fbc987b3..0fd59235 100644 --- a/cli/src/cursor/utils/cursorModeConfig.test.ts +++ b/cli/src/cursor/utils/cursorModeConfig.test.ts @@ -330,6 +330,221 @@ describe('applyCursorAcpModel', () => { expect(setConfigOption).toHaveBeenNthCalledWith(2, 's1', 'fast', 'true'); }); + it('applies the requested effort over config options for variant sku requests (#1818)', async () => { + const setConfigOption = vi.fn(async () => {}); + const backend = mockModelBackend({ + setConfigOption, + getSessionModelsMetadata: vi.fn(() => ({ + availableModels: [{ modelId: 'claude-opus-4-8', name: 'Claude Opus 4.8' }], + currentModelId: 'claude-opus-4-8' + })), + getConfigOptionByCategory: vi.fn((_sessionId: string, category: string) => { + if (category === 'model') { + return { id: 'model', category: 'model', options: [{ value: 'claude-opus-4-8' }] }; + } + if (category === 'fast') { + return { id: 'fast', category: 'fast', options: [{ value: 'false' }, { value: 'true' }] }; + } + return undefined; + }), + getSessionConfigOptions: vi.fn(() => [ + { id: 'model', category: 'model', options: [{ value: 'claude-opus-4-8' }] }, + { + id: 'effort', + category: 'thought_level', + currentValue: 'high', + options: [{ value: 'low' }, { value: 'medium' }, { value: 'high' }, { value: 'xhigh' }] + }, + { id: 'fast', category: 'model_config', options: [{ value: 'false' }, { value: 'true' }] } + ]) + }); + + await expect(applyCursorAcpModel(backend, 's1', 'claude-opus-4-8-low')).resolves.toMatchObject({ + applied: true, + resolvedWireId: 'claude-opus-4-8[fast=false,effort=low]', + requestedWireId: 'claude-opus-4-8-low' + }); + expect(setConfigOption).toHaveBeenNthCalledWith(1, 's1', 'model', 'claude-opus-4-8'); + expect(setConfigOption).toHaveBeenNthCalledWith(2, 's1', 'fast', 'false'); + expect(setConfigOption).toHaveBeenNthCalledWith(3, 's1', 'effort', 'low'); + }); + + it('skips parameter axes the selected model does not expose (#1818)', async () => { + let selected = 'grok-4.6'; + const fastOption = { id: 'fast', category: 'fast', options: [{ value: 'false' }, { value: 'true' }] }; + const modelOption = { id: 'model', category: 'model', options: [{ value: 'gemini-3-flash' }] }; + const setConfigOption = vi.fn(async (_sessionId: string, id: string, value: string) => { + if (id === 'model') { + selected = value; + } + }); + // Cursor drops fast/thought_level for a model that supports neither. + const activeOptions = () => (selected === 'gemini-3-flash' ? [modelOption] : [modelOption, fastOption]); + const backend = mockModelBackend({ + setConfigOption, + getSessionModelsMetadata: vi.fn(() => ({ + availableModels: [{ modelId: 'gemini-3-flash' }], + currentModelId: 'gemini-3-flash' + })), + getConfigOptionByCategory: vi.fn((_sessionId: string, category: string) => + activeOptions().find((option) => option.category === category) + ), + getSessionConfigOptions: vi.fn(() => activeOptions()) + }); + + await expect(applyCursorAcpModel(backend, 's1', 'gemini-3-flash')).resolves.toMatchObject({ + applied: true, + resolvedWireId: 'gemini-3-flash' + }); + expect(setConfigOption).toHaveBeenCalledTimes(1); + expect(setConfigOption).toHaveBeenCalledWith('s1', 'model', 'gemini-3-flash'); + }); + + it('maps aliased effort values onto the per-model option id (#1818)', async () => { + const modelOption = { id: 'model', category: 'model', options: [{ value: 'gpt-5.5' }] }; + const backend = mockModelBackend({ + setConfigOption: vi.fn(async () => {}), + getSessionModelsMetadata: vi.fn(() => ({ + availableModels: [{ modelId: 'gpt-5.5' }], + currentModelId: 'gpt-5.5' + })), + getConfigOptionByCategory: vi.fn((_sessionId: string, category: string) => { + if (category === 'model') { + return modelOption; + } + // gpt-5.5 spells the top effort `extra-high` on the `reasoning` id. + if (category === 'reasoning') { + return { + id: 'reasoning', + category: 'thought_level', + currentValue: 'medium', + options: [{ value: 'none' }, { value: 'low' }, { value: 'medium' }, { value: 'high' }, { value: 'extra-high' }] + }; + } + return undefined; + }), + getSessionConfigOptions: vi.fn(() => [modelOption, { id: 'reasoning', category: 'thought_level', options: [{ value: 'extra-high' }] }]) + }); + + await expect(applyCursorAcpModel(backend, 's1', 'gpt-5.5-xhigh')).resolves.toMatchObject({ + applied: true, + resolvedWireId: 'gpt-5.5[reasoning=extra-high]' + }); + expect(backend.setConfigOption).toHaveBeenNthCalledWith(1, 's1', 'model', 'gpt-5.5'); + expect(backend.setConfigOption).toHaveBeenNthCalledWith(2, 's1', 'reasoning', 'extra-high'); + }); + + it('leaves Claude thinking untouched while switching effort (#1818)', async () => { + const setConfigOption = vi.fn(async () => {}); + const options = [ + { id: 'model', category: 'model', options: [{ value: 'claude-opus-4-8' }] }, + { id: 'thinking', category: 'thought_level', currentValue: 'true', options: [{ value: 'false' }, { value: 'true' }] }, + { id: 'effort', category: 'thought_level', currentValue: 'high', options: [{ value: 'low' }, { value: 'high' }, { value: 'xhigh' }] } + ]; + const backend = mockModelBackend({ + setConfigOption, + getSessionModelsMetadata: vi.fn(() => ({ availableModels: [{ modelId: 'claude-opus-4-8' }], currentModelId: 'claude-opus-4-8' })), + getConfigOptionByCategory: vi.fn((_sessionId: string, category: string) => { + if (category === 'model') { + return options[0]; + } + // Both `thinking` and `effort` are thought_level: category lookup must not + // pick the toggle when the requested axis is effort. + return category === 'effort' ? options[2] : undefined; + }), + getSessionConfigOptions: vi.fn(() => options) + }); + + await expect(applyCursorAcpModel(backend, 's1', 'claude-opus-4-8-xhigh')).resolves.toMatchObject({ + applied: true, + resolvedWireId: 'claude-opus-4-8[effort=xhigh]' + }); + expect(setConfigOption).toHaveBeenCalledTimes(2); + expect(setConfigOption).toHaveBeenNthCalledWith(2, 's1', 'effort', 'xhigh'); + }); + + it('applies effort on gemini models through the reasoning_effort option id (#1818)', async () => { + const options = [ + { id: 'model', category: 'model', options: [{ value: 'gemini-3.8-flash' }] }, + { id: 'reasoning_effort', category: 'thought_level', currentValue: 'high', options: [{ value: 'low' }, { value: 'medium' }, { value: 'high' }] } + ]; + const setConfigOption = vi.fn(async () => {}); + const backend = mockModelBackend({ + setConfigOption, + getSessionModelsMetadata: vi.fn(() => ({ availableModels: [{ modelId: 'gemini-3.8-flash' }], currentModelId: 'gemini-3.8-flash' })), + getConfigOptionByCategory: vi.fn((_sessionId: string, category: string) => + category === 'model' ? options[0] : undefined + ), + getSessionConfigOptions: vi.fn(() => options) + }); + + await expect(applyCursorAcpModel(backend, 's1', 'gemini-3.8-flash-high')).resolves.toMatchObject({ + applied: true, + resolvedWireId: 'gemini-3.8-flash[reasoning_effort=high]' + }); + expect(setConfigOption).toHaveBeenNthCalledWith(2, 's1', 'reasoning_effort', 'high'); + }); + + it('resolves the advertised base for a legacy cursor- prefixed sku (#1818)', async () => { + const setConfigOption = vi.fn(async () => {}); + const options = [ + { id: 'model', category: 'model', options: [{ value: 'grok-4.6' }] }, + { id: 'effort', category: 'thought_level', currentValue: 'high', options: [{ value: 'low' }, { value: 'high' }] } + ]; + const backend = mockModelBackend({ + setConfigOption, + getSessionModelsMetadata: vi.fn(() => ({ availableModels: [{ modelId: 'grok-4.6' }], currentModelId: 'grok-4.6' })), + getConfigOptionByCategory: vi.fn((_sessionId: string, category: string) => + category === 'model' ? options[0] : undefined + ), + getSessionConfigOptions: vi.fn(() => options) + }); + + await expect(applyCursorAcpModel(backend, 's1', 'cursor-grok-4.6-high')).resolves.toMatchObject({ + applied: true, + resolvedWireId: 'grok-4.6[effort=high]', + requestedWireId: 'cursor-grok-4.6-high' + }); + // The `cursor-` family prefix must map onto the advertised `grok-4.6` base. + expect(setConfigOption).toHaveBeenNthCalledWith(1, 's1', 'model', 'grok-4.6'); + expect(setConfigOption).toHaveBeenNthCalledWith(2, 's1', 'effort', 'high'); + }); + + it('reads the new model effort option after the base switch (#1818)', async () => { + // Cursor renames the effort axis across families: gpt-5.5 uses `reasoning`, + // claude-opus-4-8 uses `effort`. The apply path must resolve against the + // options advertised for the model it just selected, not the previous ones. + let selected = 'gpt-5.5'; + const modelOption = { id: 'model', category: 'model', options: [{ value: 'gpt-5.5' }, { value: 'claude-opus-4-8' }] }; + const gptOptions = [modelOption, { id: 'reasoning', category: 'thought_level', currentValue: 'medium', options: [{ value: 'low' }, { value: 'medium' }, { value: 'high' }] }]; + const claudeOptions = [modelOption, { id: 'effort', category: 'thought_level', currentValue: 'high', options: [{ value: 'low' }, { value: 'high' }, { value: 'xhigh' }] }]; + const activeOptions = () => (selected === 'gpt-5.5' ? gptOptions : claudeOptions); + const setConfigOption = vi.fn(async (_sessionId: string, id: string, value: string) => { + if (id === 'model') { + selected = value; + } + }); + const backend = mockModelBackend({ + setConfigOption, + getSessionModelsMetadata: vi.fn(() => ({ + availableModels: [{ modelId: 'claude-opus-4-8' }], + currentModelId: 'claude-opus-4-8' + })), + getConfigOptionByCategory: vi.fn((_sessionId: string, category: string) => + activeOptions().find((option) => option.category === category) + ), + getSessionConfigOptions: vi.fn(() => activeOptions()) + }); + + await expect(applyCursorAcpModel(backend, 's1', 'claude-opus-4-8-xhigh')).resolves.toMatchObject({ + applied: true, + resolvedWireId: 'claude-opus-4-8[effort=xhigh]' + }); + expect(setConfigOption).toHaveBeenNthCalledWith(1, 's1', 'model', 'claude-opus-4-8'); + expect(setConfigOption).toHaveBeenNthCalledWith(2, 's1', 'effort', 'xhigh'); + expect(setConfigOption).not.toHaveBeenCalledWith('s1', 'reasoning', expect.anything()); + }); + it('does not fall back to base-only model apply when parameterized fast update fails', async () => { const setConfigOption = vi.fn() .mockResolvedValueOnce(undefined) @@ -360,10 +575,11 @@ describe('applyCursorAcpModel', () => { }); await expect(applyCursorAcpModel(backend, 's1', 'composer-2.5')).resolves.toEqual({ - applied: false + applied: false, + partiallyAppliedWireId: 'composer-2.5' }); expect(setConfigOption).toHaveBeenCalledTimes(2); - expect(backend.pinSessionModelWireId).not.toHaveBeenCalled(); + expect(backend.pinSessionModelWireId).toHaveBeenCalledWith('s1', 'composer-2.5'); }); it('retries set_config_option once before failing apply', async () => { diff --git a/cli/src/cursor/utils/cursorModeConfig.ts b/cli/src/cursor/utils/cursorModeConfig.ts index 83389071..72dd00b4 100644 --- a/cli/src/cursor/utils/cursorModeConfig.ts +++ b/cli/src/cursor/utils/cursorModeConfig.ts @@ -1,15 +1,10 @@ import type { CursorPermissionMode } from '@hapi/protocol/types'; -import { cursorCliSkuBaseId, cursorModelBaseId, matchCliSkuToAcpWireId, resolveCursorLegacyModelBase } from '@hapi/protocol'; +import { cursorCliSkuBaseId, cursorModelBaseId, cursorModelBaseMatches, isCursorAutoModelId, matchCliSkuToAcpWireId, parseCursorSkuParamHints, parseCursorWireParams, resolveCursorLegacyModelBase } from '@hapi/protocol'; import type { AcpSdkBackend } from '@/agent/backends/acp'; import { logger } from '@/ui/logger'; export type CursorAcpMode = 'agent' | 'plan' | 'ask' | 'debug'; -function isDefaultCursorModelId(modelId: string): boolean { - const normalized = modelId.trim().toLowerCase(); - return normalized === 'auto' || normalized === 'default' || normalized === 'default[]'; -} - export function toCursorAcpMode(mode: CursorPermissionMode | undefined): CursorAcpMode { if (mode === 'plan') return 'plan'; if (mode === 'ask') return 'ask'; @@ -85,6 +80,7 @@ export async function applyCursorAcpMode( export type ApplyCursorAcpModelResult = { applied: boolean; + partiallyAppliedWireId?: string; /** Wire id applied via ACP when switching succeeds */ resolvedWireId?: string; /** Original hub/UI request before catalog resolution */ @@ -164,10 +160,69 @@ function fastHintForCursorSkuOrWire(modelId: string): 'false' | 'true' { return lower.includes('-fast') ? 'true' : 'false'; } -function cursorRequestBaseId(modelId: string): string { - return modelId.includes('[') +function cursorRequestBaseId(modelId: string, modelOption?: ConfigOption): string { + const raw = modelId.includes('[') ? cursorModelBaseId(modelId) : cursorCliSkuBaseId(modelId); + // CLI skus may carry the legacy `cursor-` family prefix (cursor-grok-4.6-high). + const advertised = modelOption?.options?.find((option) => cursorModelBaseMatches(option.value, raw)); + return advertised?.value ?? raw; +} + +/** CLI sku / ACP wire effort values → Cursor config option values (aliases included). */ +const EFFORT_OPTION_VALUES: Readonly> = { + none: ['none'], + low: ['low'], + medium: ['medium'], + high: ['high'], + xhigh: ['xhigh', 'extra-high'], + 'extra-high': ['extra-high', 'xhigh'], + max: ['max'] +}; + +/** Cursor exposes the effort axis under different ids per model family. */ +const EFFORT_OPTION_IDS = ['effort', 'reasoning', 'reasoning_effort'] as const; + +function effortHintForCursorSkuOrWire(modelId: string): string | null { + const params = modelId.includes('[') + ? parseCursorWireParams(modelId) + : parseCursorSkuParamHints(modelId); + const hint = params.effort ?? params.reasoning ?? params.reasoning_effort; + return hint?.trim() || null; +} + +function resolveOptionValue(option: ConfigOption | undefined, candidates: readonly string[]): string | null { + if (!option?.options?.length) { + return null; + } + for (const candidate of candidates) { + if (option.options.some((entry) => entry.value === candidate)) { + return candidate; + } + } + return null; +} + +/** + * Effort config option for the model that is currently selected. Ids are tried first + * because `thought_level` also covers Claude's separate `thinking` toggle. + */ +function findEffortConfigOption( + backend: AcpSdkBackend, + sessionId: string, + hint: string +): { option: ConfigOption; value: string } | null { + const candidates = EFFORT_OPTION_VALUES[hint] ?? [hint]; + for (const id of EFFORT_OPTION_IDS) { + const option = findConfigOption(backend, sessionId, id); + const value = resolveOptionValue(option, candidates); + if (option && value) { + return { option, value }; + } + } + const thoughtLevel = backend.getConfigOptionByCategory?.(sessionId, 'thought_level'); + const value = resolveOptionValue(thoughtLevel, candidates); + return thoughtLevel && value ? { option: thoughtLevel, value } : null; } async function applyParameterizedCursorModel( @@ -176,28 +231,57 @@ async function applyParameterizedCursorModel( requested: string ): Promise { const modelOption = findConfigOption(backend, sessionId, 'model'); - const fastOption = findConfigOption(backend, sessionId, 'fast'); - if (!modelOption || !fastOption || !backend.setConfigOption) { + if (!modelOption || !backend.setConfigOption) { return 'unsupported'; } - const baseModel = cursorRequestBaseId(requested); + const baseModel = cursorRequestBaseId(requested, modelOption); const fast = fastHintForCursorSkuOrWire(requested); - if (!optionHasValue(modelOption, baseModel) || !optionHasValue(fastOption, fast)) { + // Parameterized sessions advertise bare bases. A model option holding complete + // wires belongs to the non-parameterized path, which applies the wire as-is. + if (!optionHasValue(modelOption, baseModel)) { return 'unsupported'; } + let partiallyAppliedWireId: string | undefined; try { await backend.setConfigOption(sessionId, modelOption.id, baseModel); - await backend.setConfigOption(sessionId, fastOption.id, fast); + partiallyAppliedWireId = baseModel; + + // Selecting the base refreshes Cursor's per-model config options. Re-read them so + // the parameters are applied against the model that is now active, and skipped + // for models that do not expose that axis. + const appliedParams: string[] = []; + const activeFast = findConfigOption(backend, sessionId, 'fast'); + if (activeFast && optionHasValue(activeFast, fast)) { + await backend.setConfigOption(sessionId, activeFast.id, fast); + appliedParams.push(`fast=${fast}`); + partiallyAppliedWireId = `${baseModel}[${appliedParams.join(',')}]`; + } + + const effortHint = effortHintForCursorSkuOrWire(requested); + const effort = effortHint ? findEffortConfigOption(backend, sessionId, effortHint) : null; + if (effort) { + await backend.setConfigOption(sessionId, effort.option.id, effort.value); + appliedParams.push(`${effort.option.id}=${effort.value}`); + partiallyAppliedWireId = `${baseModel}[${appliedParams.join(',')}]`; + } + + // Only parameters that were actually applied belong in the pinned wire; a model + // that exposes neither axis stays on its bare base. + const resolved = appliedParams.length > 0 + ? `${baseModel}[${appliedParams.join(',')}]` + : baseModel; + backend.pinSessionModelWireId(sessionId, resolved); + return { applied: true, resolvedWireId: resolved, requestedWireId: requested }; } catch (error) { logger.debug('[cursor-acp] parameterized model config failed', error); + if (partiallyAppliedWireId) { + backend.pinSessionModelWireId(sessionId, partiallyAppliedWireId); + return { applied: false, partiallyAppliedWireId }; + } return 'failed'; } - - const resolved = `${baseModel}[fast=${fast}]`; - backend.pinSessionModelWireId(sessionId, resolved); - return { applied: true, resolvedWireId: resolved, requestedWireId: requested }; } /** @@ -210,7 +294,7 @@ export async function applyCursorAcpModel( modelId: string | null | undefined ): Promise { const trimmed = modelId?.trim(); - if (!trimmed || isDefaultCursorModelId(trimmed)) { + if (!trimmed || isCursorAutoModelId(trimmed)) { return { applied: false }; } diff --git a/cli/src/cursor/utils/cursorStaleModelRemap.test.ts b/cli/src/cursor/utils/cursorStaleModelRemap.test.ts index 76194d64..561615f2 100644 --- a/cli/src/cursor/utils/cursorStaleModelRemap.test.ts +++ b/cli/src/cursor/utils/cursorStaleModelRemap.test.ts @@ -28,6 +28,11 @@ describe('cursorStaleModelRemap', () => { expect(resolveCursorSpawnModel('grok-4.5[fast=false]')).toBe('cursor-grok-4.5-medium'); }); + it('pins default aliases to CLI auto before spawn remap', () => { + expect(resolveCursorSpawnModel('auto')).toBe('auto'); + expect(resolveCursorSpawnModel('default[]')).toBe('auto'); + }); + it('remaps once from stderr Available models on model_not_found', () => { const remapped = tryRemapCursorSpawnModelFromError( 'grok-4.5[fast=true]', diff --git a/cli/src/cursor/utils/cursorStaleModelRemap.ts b/cli/src/cursor/utils/cursorStaleModelRemap.ts index 63f2521c..e60ed98b 100644 --- a/cli/src/cursor/utils/cursorStaleModelRemap.ts +++ b/cli/src/cursor/utils/cursorStaleModelRemap.ts @@ -1,15 +1,13 @@ import type { CursorModelsResponse } from '@hapi/protocol/apiTypes'; import { + CURSOR_AUTO_MODEL_ID, + cursorSpawnModelId, + isCursorAutoModelId, parseCursorAvailableModelsFromRejection, remapStaleCursorModelId } from '@hapi/protocol'; import { readSharedCursorModelsCache } from '@/modules/common/cursorModelsSharedCache'; -function isDefaultSpawnModel(modelId: string): boolean { - const normalized = modelId.trim().toLowerCase(); - return normalized === 'auto' || normalized === 'default' || normalized === 'default[]'; -} - export function catalogEntriesFromCursorModelsResponse( response: CursorModelsResponse | null | undefined ): { modelId: string }[] { @@ -36,10 +34,14 @@ export function catalogEntriesFromCursorModelsResponse( export function resolveCursorSpawnModel( model: string | null | undefined ): string | null | undefined { - const trimmed = model?.trim(); - if (!trimmed || isDefaultSpawnModel(trimmed)) { + const pinned = cursorSpawnModelId(model); + if (!pinned) { return model; } + if (pinned === CURSOR_AUTO_MODEL_ID) { + return CURSOR_AUTO_MODEL_ID; + } + const trimmed = pinned; const cached = catalogEntriesFromCursorModelsResponse(readSharedCursorModelsCache()); if (cached.length === 0) { @@ -54,7 +56,7 @@ export function tryRemapCursorSpawnModelFromError( ...sources: Array ): string | null { const trimmed = model?.trim(); - if (!trimmed || isDefaultSpawnModel(trimmed)) { + if (!trimmed || isCursorAutoModelId(trimmed)) { return null; } diff --git a/cli/src/modules/common/cursorAcpModelProbe.ts b/cli/src/modules/common/cursorAcpModelProbe.ts index b694cac7..214f6459 100644 --- a/cli/src/modules/common/cursorAcpModelProbe.ts +++ b/cli/src/modules/common/cursorAcpModelProbe.ts @@ -30,7 +30,8 @@ export async function runCursorAcpModelProbe(cwd?: string): Promise { expect(spawnMock).not.toHaveBeenCalled() }) + test('attaches variant cliModelSkus to parameterized bare base catalogs (#1818)', async () => { + vi.mocked(isAgentAcpTransportActive).mockReturnValue(true) + const bareCatalog = [ + { modelId: 'composer-2.5', name: 'Composer 2.5' }, + { modelId: 'claude-opus-4-8', name: 'Claude Opus 4.8' }, + { modelId: 'grok-4.6', name: 'Cursor Grok 4.6' } + ] + setCursorAcpModelsSnapshot({ + availableModels: bareCatalog, + currentModelId: 'composer-2.5', + parameterized: true + }) + writeSharedCursorModelsCache({ + success: true, + parameterized: true, + availableModels: bareCatalog, + currentModelId: 'composer-2.5', + cliModelSkus: [ + { modelId: 'composer-2.5', name: 'Composer 2.5' }, + { modelId: 'composer-2.5-fast', name: 'Composer 2.5 Fast' }, + { modelId: 'claude-opus-4-8-low', name: 'Claude Opus 4.8 Low' }, + { modelId: 'cursor-grok-4.6-high', name: 'Cursor Grok 4.6' } + ] + }) + + const result = await listCursorModels() + + expect(result.availableModels?.map((row) => row.modelId)).toEqual([ + 'composer-2.5', + 'claude-opus-4-8', + 'grok-4.6' + ]) + // Parameterized ACP sessions apply fast/effort over config options, so the + // spawn-safe variant skus stay attached to their bare base rows — including + // CLI skus that keep Cursor's legacy `cursor-` family prefix. + expect(result.cliModelSkus?.map((row) => row.modelId)).toEqual([ + 'composer-2.5', + 'composer-2.5-fast', + 'claude-opus-4-8-low', + 'cursor-grok-4.6-high' + ]) + expect(spawnMock).not.toHaveBeenCalled() + }) + test('enriches live ACP snapshot with fuller shared cliModelSkus while lock is active', async () => { vi.mocked(isAgentAcpTransportActive).mockReturnValue(true) setCursorAcpModelsSnapshot({ diff --git a/cli/src/modules/common/cursorModels.ts b/cli/src/modules/common/cursorModels.ts index 33a17c5e..5da61a34 100644 --- a/cli/src/modules/common/cursorModels.ts +++ b/cli/src/modules/common/cursorModels.ts @@ -18,6 +18,7 @@ import { import { cursorCliSkuBaseId, cursorModelBaseId, + cursorModelBaseMatches, isCursorAcpCatalogModelId, isCursorAcpWireModelId } from '@hapi/protocol'; @@ -31,6 +32,7 @@ export function buildCursorModelsSeedPayload( availableModels: CursorModelSummary[]; currentModelId: string | null; cliModelSkus?: readonly CursorModelSummary[]; + parameterized?: boolean; }, shared?: CursorModelsResponse | null ): ListCursorModelsResponse { @@ -42,6 +44,7 @@ export function buildCursorModelsSeedPayload( success: true, availableModels: snapshot.availableModels, currentModelId: snapshot.currentModelId, + ...(snapshot.parameterized ? { parameterized: true } : {}), ...(cliModelSkus.length > 0 ? { cliModelSkus } : {}) }; } @@ -68,9 +71,9 @@ function filterCliSkusForWireBases( cliSkus: CursorModelSummary[], wires: CursorModelSummary[] ): CursorModelSummary[] { - const wireBases = new Set( - wires.map((entry) => cursorModelBaseId(entry.modelId)).filter((base) => base.length > 0) - ); + const wireBases = wires + .map((entry) => cursorModelBaseId(entry.modelId)) + .filter((base) => base.length > 0); return cliSkus.filter((entry) => { const modelId = entry.modelId.trim(); @@ -78,7 +81,8 @@ function filterCliSkusForWireBases( if (!modelId || modelId === 'auto' || isCursorAcpWireModelId(modelId)) { return false; } - return wireBases.has(cursorCliSkuBaseId(modelId)); + const skuBase = cursorCliSkuBaseId(modelId); + return wireBases.some((base) => cursorModelBaseMatches(skuBase, base)); }); } @@ -87,22 +91,24 @@ function attachCliSkusToResponse( cliSkus: readonly CursorModelSummary[] ): ListCursorModelsResponse { const wires = (response.availableModels ?? []).filter((entry) => isCursorAcpCatalogModelId(entry.modelId)); - // Suffixed CLI variants (effort/speed) only apply when ACP exposes parameterized - // wires for that base. Bare-only catalogs cannot express those variants - // (apply path is model + fast at most), so attaching them creates dead picker rows. - const parameterizedBases = new Set( - wires + // Variant skus are only usable when the ACP apply path can express them: + // parameterized pickers apply model + fast + thought_level over config options, + // and wire catalogs already pair each variant with a base wire. Bare-only + // catalogs without the parameterized picker keep base rows only. + const applyableBases = (response.parameterized === true + ? wires.map((entry) => cursorModelBaseId(entry.modelId)) + : wires .filter((entry) => isCursorAcpWireModelId(entry.modelId)) .map((entry) => cursorModelBaseId(entry.modelId)) - .filter((base) => base.length > 0) - ); + ).filter((base) => base.length > 0); const filtered = filterCliSkusForWireBases( mergeCliModelSkus(response.cliModelSkus ?? [], [...cliSkus]), wires ).filter((entry) => { const modelId = entry.modelId.trim(); const base = cursorCliSkuBaseId(modelId); - return modelId === base || parameterizedBases.has(base); + return modelId === base + || applyableBases.some((candidate) => cursorModelBaseMatches(base, candidate)); }); if (filtered.length === 0) { return response.cliModelSkus?.length diff --git a/cli/src/modules/common/cursorModelsSharedCache.test.ts b/cli/src/modules/common/cursorModelsSharedCache.test.ts index d9394587..8ed3700a 100644 --- a/cli/src/modules/common/cursorModelsSharedCache.test.ts +++ b/cli/src/modules/common/cursorModelsSharedCache.test.ts @@ -1,5 +1,5 @@ import { afterAll, afterEach, describe, expect, test } from 'vitest'; -import { mkdtempSync, rmSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -59,4 +59,21 @@ describe('cursorModelsSharedCache', () => { expect(readSharedCursorModelsCache()?.cliModelSkus).toEqual(payload.cliModelSkus); }); + + test('ignores pre-versioned cache files that carry synthesized wire ids', () => { + // v1 files carried `[fast=…]` wires Cursor rejects; a runner must re-probe + // instead of serving them forever (listCursorModels trusts the cache). + mkdirSync(join(testHapiHome, 'cache'), { recursive: true }); + writeFileSync( + join(testHapiHome, 'cache', 'cursor-models.json'), + JSON.stringify({ + success: true, + availableModels: [{ modelId: 'grok-4.6[fast=false]', name: 'Cursor Grok 4.6' }], + currentModelId: 'grok-4.6[fast=false]' + }), + 'utf8' + ); + + expect(readSharedCursorModelsCache()).toBeNull(); + }); }); diff --git a/cli/src/modules/common/cursorModelsSharedCache.ts b/cli/src/modules/common/cursorModelsSharedCache.ts index b7e50849..e51e5e71 100644 --- a/cli/src/modules/common/cursorModelsSharedCache.ts +++ b/cli/src/modules/common/cursorModelsSharedCache.ts @@ -18,6 +18,18 @@ function isUsableModelsResponse(response: CursorModelsResponse | null): response ); } +/** + * Bumped when a cached catalog can no longer be trusted. v1 carried synthesized + * `[fast=…]` wire ids that Cursor rejects at `session/new`; `listCursorModels` + * serves the on-disk cache without re-probing, so stale entries must not be read. + */ +const SHARED_CACHE_VERSION = 2; + +type SharedCacheEnvelope = { + version: number; + response: CursorModelsResponse; +}; + /** Cross-process catalog for New Session while an ACP lock blocks `agent --list-models`. */ export function readSharedCursorModelsCache(): CursorModelsResponse | null { const path = getSharedCachePath(); @@ -26,8 +38,12 @@ export function readSharedCursorModelsCache(): CursorModelsResponse | null { } try { - const parsed = JSON.parse(readFileSync(path, 'utf8')) as CursorModelsResponse; - return isUsableModelsResponse(parsed) ? parsed : null; + const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial | null; + if (!parsed || parsed.version !== SHARED_CACHE_VERSION) { + return null; + } + const response = parsed.response ?? null; + return isUsableModelsResponse(response) ? response : null; } catch { return null; } @@ -41,7 +57,8 @@ export function writeSharedCursorModelsCache(response: CursorModelsResponse): vo const path = getSharedCachePath(); try { mkdirSync(dirname(path), { recursive: true }); - writeFileSync(path, JSON.stringify(response), 'utf8'); + const envelope: SharedCacheEnvelope = { version: SHARED_CACHE_VERSION, response }; + writeFileSync(path, JSON.stringify(envelope), 'utf8'); } catch { // Best effort — in-process cache still works in the session child. } diff --git a/e2e/composer-copy.spec.ts b/e2e/composer-copy.spec.ts index d6f353c0..a4e8a586 100644 --- a/e2e/composer-copy.spec.ts +++ b/e2e/composer-copy.spec.ts @@ -16,11 +16,11 @@ test.describe('composer Ctrl+A + Ctrl+C copy', () => { }) test('Ctrl+A outside the composer selects the message thread and Ctrl+C copies it', async ({ page }) => { - await page.keyboard.press('Control+a') + await page.keyboard.press('ControlOrMeta+a') const selected = await page.evaluate(() => window.getSelection()?.toString() ?? '') expect(selected).toContain('The quick brown fox jumps over the lazy dog') expect(selected).toContain('my earlier user message') - await page.keyboard.press('Control+c') + await page.keyboard.press('ControlOrMeta+c') const copied = await page.evaluate(() => navigator.clipboard.readText()) expect(copied).toBe(selected) }) @@ -29,8 +29,8 @@ test.describe('composer Ctrl+A + Ctrl+C copy', () => { const editor = page.locator('[data-testid="rich-composer-input"]') await editor.click() await page.keyboard.type('my draft message') - await page.keyboard.press('Control+a') - await page.keyboard.press('Control+c') + await page.keyboard.press('ControlOrMeta+a') + await page.keyboard.press('ControlOrMeta+c') const copied = await page.evaluate(() => navigator.clipboard.readText()) expect(copied).toBe('my draft message') }) @@ -44,8 +44,8 @@ test.describe('composer Ctrl+A + Ctrl+C copy', () => { }) const textarea = page.locator('#plain-textarea') await textarea.click() - await page.keyboard.press('Control+a') - await page.keyboard.press('Control+c') + await page.keyboard.press('ControlOrMeta+a') + await page.keyboard.press('ControlOrMeta+c') const copied = await page.evaluate(() => navigator.clipboard.readText()) expect(copied).toBe('textarea draft') }) @@ -53,10 +53,10 @@ test.describe('composer Ctrl+A + Ctrl+C copy', () => { test('mouse-drag selection still copies via plain Ctrl+C', async ({ page }) => { const msg = page.locator('[data-testid="assistant-message-2"]') await msg.dragTo(page.locator('[data-testid="user-message-1"]'), { - sourcePosition: { x: 5, y: 2 }, + sourcePosition: { x: 0, y: 2 }, targetPosition: { x: 300, y: 2 }, }) - await page.keyboard.press('Control+c') + await page.keyboard.press('ControlOrMeta+c') const copied = await page.evaluate(() => navigator.clipboard.readText()) expect(copied).toContain('Another assistant message') expect(copied).toContain('my earlier user message') diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 4a871fa5..d45fd7e4 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -877,7 +877,15 @@ export type ListAgyModelsResponse = AgyModelsResponse export type CursorModelSummary = OpencodeModelSummary -export type CursorModelsResponse = OpencodeModelsResponse +export type CursorModelsResponse = OpencodeModelsResponse & { + /** + * True when ACP advertised Cursor's parameterized model picker: bare model bases + * plus separate `fast` / `thought_level` config options. The ACP apply path + * expresses variant CLI skus through those options, so variant rows stay valid + * even when the catalog itself carries no bracket wire ids. + */ + parameterized?: boolean +} export type ListCursorModelsResponse = CursorModelsResponse diff --git a/shared/src/cursorCliSku.test.ts b/shared/src/cursorCliSku.test.ts index 36316337..96351839 100644 --- a/shared/src/cursorCliSku.test.ts +++ b/shared/src/cursorCliSku.test.ts @@ -1,12 +1,17 @@ import { describe, expect, it } from 'vitest'; import { + CURSOR_AUTO_MODEL_ID, cursorCliSkuBaseId, + cursorSpawnModelId, + cursorModelBaseMatches, findBestCliSkuForAcpWire, isCursorAcpCatalogModelId, isCursorAcpWireModelId, + isCursorAutoModelId, isCursorCliSkuVariantId, matchCliSkuToAcpWireId, parseCursorAvailableModelsFromRejection, + parseCursorSkuParamHints, remapStaleCursorModelId } from './cursorCliSku'; @@ -19,6 +24,19 @@ const cursorGrokCatalog = [ { modelId: 'cursor-grok-4.5-high-fast' }, ]; +describe('cursorSpawnModelId', () => { + it('pins Auto as the CLI auto id and omits unset models', () => { + expect(isCursorAutoModelId('auto')).toBe(true); + expect(isCursorAutoModelId('default[]')).toBe(true); + expect(isCursorAutoModelId('composer-2.5')).toBe(false); + expect(cursorSpawnModelId('auto')).toBe(CURSOR_AUTO_MODEL_ID); + expect(cursorSpawnModelId('default')).toBe(CURSOR_AUTO_MODEL_ID); + expect(cursorSpawnModelId('default[]')).toBe(CURSOR_AUTO_MODEL_ID); + expect(cursorSpawnModelId(null)).toBeNull(); + expect(cursorSpawnModelId('composer-2.5[fast=true]')).toBe('composer-2.5[fast=true]'); + }); +}); + describe('cursorCliSkuBaseId', () => { it('strips effort/speed suffixes from CLI skus', () => { expect(cursorCliSkuBaseId('gpt-5.5-high-fast')).toBe('gpt-5.5'); @@ -273,6 +291,29 @@ describe('round-trip (regression for #883: "selected but no response")', () => { }); }); +describe('cursorModelBaseMatches', () => { + it('matches bases across the legacy cursor- CLI family prefix', () => { + expect(cursorModelBaseMatches('cursor-grok-4.6', 'grok-4.6')).toBe(true); + expect(cursorModelBaseMatches('grok-4.6', 'cursor-grok-4.6')).toBe(true); + expect(cursorModelBaseMatches('cursor-grok-4.5', 'cursor-grok-4.5')).toBe(true); + expect(cursorModelBaseMatches('composer-2.5', 'composer-2.5')).toBe(true); + expect(cursorModelBaseMatches('grok-4.6', 'grok-4.5')).toBe(false); + expect(cursorModelBaseMatches('claude-opus-4-8', 'claude-opus-5')).toBe(false); + }); + + it('parses parameter hints from CLI sku suffixes', () => { + expect(parseCursorSkuParamHints('cursor-grok-4.6-low')).toMatchObject({ + effort: 'low', + fast: 'false' + }); + expect(parseCursorSkuParamHints('gpt-5.5-extra-high-fast')).toMatchObject({ + reasoning: 'extra-high', + fast: 'true' + }); + expect(parseCursorSkuParamHints('composer-2.5')).toMatchObject({ fast: 'false' }); + }); +}); + describe('isCursorAcpWireModelId', () => { it('detects parameterized wire ids only', () => { expect(isCursorAcpWireModelId('gpt-5.5[fast=false]')).toBe(true); diff --git a/shared/src/cursorCliSku.ts b/shared/src/cursorCliSku.ts index 0414d33f..57479ff7 100644 --- a/shared/src/cursorCliSku.ts +++ b/shared/src/cursorCliSku.ts @@ -8,18 +8,54 @@ export function resolveCursorLegacyModelBase(baseId: string): string { return CURSOR_LEGACY_MODEL_BASE_ALIASES[trimmed] ?? trimmed; } +/** CLI `agent --list-models` id for Cursor Auto (`auto - Auto`). */ +export const CURSOR_AUTO_MODEL_ID = 'auto'; + /** ACP parameterized wire ids use bracket params; CLI `agent --list-models` slugs do not. */ export function isCursorAcpWireModelId(modelId: string): boolean { const trimmed = modelId.trim(); return trimmed === 'default[]' || trimmed.includes('['); } +/** True for CLI Auto and the legacy default aliases that must not stay as a Default option. */ +export function isCursorAutoModelId(modelId: string | null | undefined): boolean { + const normalized = modelId?.trim().toLowerCase(); + return normalized === 'auto' || normalized === 'default' || normalized === 'default[]'; +} + +/** Spawn `--model` value: pin Auto as `auto`. Empty/unset omits `--model`. */ +export function cursorSpawnModelId(model: string | null | undefined): string | null { + const trimmed = model?.trim(); + if (!trimmed) { + return null; + } + return isCursorAutoModelId(trimmed) ? CURSOR_AUTO_MODEL_ID : trimmed; +} + export function cursorModelBaseId(modelId: string): string { const trimmed = modelId.trim(); const bracket = trimmed.indexOf('['); return bracket === -1 ? trimmed : trimmed.slice(0, bracket); } +function stripCursorFamilyPrefix(base: string): string { + return base.startsWith('cursor-') ? base.slice('cursor-'.length) : base; +} + +/** + * Compare an ACP wire base with a CLI sku base. Cursor's CLI keeps a legacy `cursor-` + * family prefix for some models (`cursor-grok-4.6-high` vs ACP base `grok-4.6`), so a + * plain equality check silently drops those variant rows. + */ +export function cursorModelBaseMatches(a: string, b: string): boolean { + const left = a.trim(); + const right = b.trim(); + if (left === right) { + return true; + } + return stripCursorFamilyPrefix(left) === stripCursorFamilyPrefix(right); +} + /** Longest-first suffixes from Cursor CLI sku ids (e.g. `gpt-5.5-high-fast` → `gpt-5.5`). */ const CLI_SKU_SUFFIXES = [ '-extra-high-fast', @@ -116,6 +152,14 @@ export function parseCursorWireParams(modelId: string): Record { return params; } +/** + * Parameter hints carried by a CLI `agent --list-models` sku + * (effort/reasoning/thinking/fast suffixes). + */ +export function parseCursorSkuParamHints(slug: string): Record { + return inferSkuParamHints(slug); +} + function inferSkuParamHints(slug: string): Record { const lower = slug.toLowerCase(); const hints: Record = {}; diff --git a/web/README.md b/web/README.md index 4b65b18c..ff30e448 100644 --- a/web/README.md +++ b/web/README.md @@ -65,6 +65,7 @@ See `src/router.tsx` for route definitions. - Message thread with infinite scroll. - Composer for sending messages. - Permission mode and model selection for supported agents. + Cursor Auto uses CLI Auto for new/resumed sessions configured with Auto. When ACP does not advertise a literal Auto option, the session picker warns that switching back from a concrete model requires a restart; HAPI does not automatically restart an active session. - Session abort and handoff controls. - Codex **Continue planning** hides the current proposal's action menu locally and focuses the composer without sending a message or replacing its draft. diff --git a/web/src/components/AssistantChat/HappyComposer.tsx b/web/src/components/AssistantChat/HappyComposer.tsx index 03d8f4f7..78ddb242 100644 --- a/web/src/components/AssistantChat/HappyComposer.tsx +++ b/web/src/components/AssistantChat/HappyComposer.tsx @@ -1645,10 +1645,9 @@ export function HappyComposer(props: { } if (modelOptions.length === 0) return undefined const rawKey = selectedModelBase !== undefined ? selectedModelBase : model - // `null` (default selection) and the `auto`/`default` wire values all - // mean "let the agent pick" — normalize them onto the `value: null` - // option so the localized option label is always found. - const normalizedKey = !rawKey || rawKey === 'auto' || rawKey === 'default' ? null : rawKey + const normalizedKey = agentFlavor === 'cursor' + ? (!rawKey || rawKey === 'auto' || rawKey === 'default' || rawKey === 'default[]' ? 'auto' : rawKey) + : (!rawKey || rawKey === 'auto' || rawKey === 'default' ? null : rawKey) const option = modelOptions.find((candidate) => candidate.value === normalizedKey) return option?.label ?? rawKey ?? undefined }, [isNarrowViewport, onModelChange, agentFlavor, selectedPiModel, model, modelOptions, selectedModelBase]) diff --git a/web/src/components/AssistantChat/modelOptions.test.ts b/web/src/components/AssistantChat/modelOptions.test.ts index c0b0eea1..e4cb4410 100644 --- a/web/src/components/AssistantChat/modelOptions.test.ts +++ b/web/src/components/AssistantChat/modelOptions.test.ts @@ -137,7 +137,7 @@ describe('getModelOptionsForFlavor', () => { it('returns only default/current for cursor before models are discovered (no claude fallback)', () => { const options = getModelOptionsForFlavor('cursor', 'composer-2.5') expect(options).toEqual([ - { value: null, label: 'Auto' }, + { value: 'auto', label: 'Auto' }, { value: 'composer-2.5', label: 'composer-2.5' } ]) }) @@ -156,12 +156,12 @@ describe('getModelOptionsForFlavor', () => { it('does not inject raw wire id when dual picker base is already listed', () => { const wire = 'claude-opus-4-8[thinking=true,context=300k,effort=high,fast=false]' const options = getModelOptionsForFlavor('cursor', wire, [ - { value: null, label: 'Auto' }, + { value: 'auto', label: 'Auto' }, { value: 'claude-opus-4-8', label: 'Claude Opus 4.8' }, { value: 'composer-2.5', label: 'Composer 2.5' }, ]) expect(options).toEqual([ - { value: null, label: 'Auto' }, + { value: 'auto', label: 'Auto' }, { value: 'claude-opus-4-8', label: 'Claude Opus 4.8' }, { value: 'composer-2.5', label: 'Composer 2.5' }, ]) @@ -170,11 +170,11 @@ describe('getModelOptionsForFlavor', () => { it('injects unknown wire id only when catalog lacks base and wire', () => { const wire = 'claude-opus-4-9[effort=high,fast=false]' const options = getModelOptionsForFlavor('cursor', wire, [ - { value: null, label: 'Auto' }, + { value: 'auto', label: 'Auto' }, { value: 'composer-2.5', label: 'Composer 2.5' }, ]) expect(options).toEqual([ - { value: null, label: 'Auto' }, + { value: 'auto', label: 'Auto' }, { value: wire, label: wire }, { value: 'composer-2.5', label: 'Composer 2.5' }, ]) diff --git a/web/src/components/AssistantChat/modelOptions.ts b/web/src/components/AssistantChat/modelOptions.ts index d68e5a63..f40e42ef 100644 --- a/web/src/components/AssistantChat/modelOptions.ts +++ b/web/src/components/AssistantChat/modelOptions.ts @@ -40,7 +40,7 @@ function withCurrentModelOption( } const nextOptions = [...options] - const autoIndex = nextOptions.findIndex((option) => option.value === null) + const autoIndex = nextOptions.findIndex((option) => option.value === null || option.value === 'auto') nextOptions.splice(autoIndex >= 0 ? autoIndex + 1 : 0, 0, { value: normalizedCurrentModel, label: resolveLabel?.(normalizedCurrentModel) ?? normalizedCurrentModel @@ -144,7 +144,7 @@ export function getModelOptionsForFlavor( return [] } if (flavor === 'cursor') { - return withCurrentModelOption([{ value: null, label: CURSOR_AUTO_MODEL_LABEL }], currentModel) + return withCurrentModelOption([{ value: 'auto', label: CURSOR_AUTO_MODEL_LABEL }], currentModel) } // Kimi has no predefined model list — show just the auto/default option. if (flavor === 'kimi') { diff --git a/web/src/components/NewSession/index.tsx b/web/src/components/NewSession/index.tsx index 934f6bbd..0a9dbeec 100644 --- a/web/src/components/NewSession/index.tsx +++ b/web/src/components/NewSession/index.tsx @@ -1534,7 +1534,9 @@ export function NewSession(props: { ? (opencodeSelectedModel ?? undefined) : agent === 'agy' ? (agySelectedModel ?? undefined) - : (model !== 'auto' ? model : undefined) + : agent === 'cursor' + ? (model === 'auto' || !model ? 'auto' : model) + : (model !== 'auto' ? model : undefined) const resolvedEffort = (agent === 'claude' || agent === 'grok' || agent === 'pi') && effort !== 'auto' ? effort : undefined diff --git a/web/src/components/SessionChat.tsx b/web/src/components/SessionChat.tsx index e59d3673..14f9ffae 100644 --- a/web/src/components/SessionChat.tsx +++ b/web/src/components/SessionChat.tsx @@ -1092,7 +1092,8 @@ function SessionChatInner(props: SessionChatProps) { machineModels: machineCursorModelsState.availableModels, cliModelSkus: sessionCliModelSkus, sessionModel: props.session.model, - sessionCurrentModelId: cursorModelsState.currentModelId + sessionCurrentModelId: cursorModelsState.currentModelId, + autoRestartLabel: t('session.modelChange.cursorAutoRestart') }) }, [ agentFlavor, @@ -1100,7 +1101,8 @@ function SessionChatInner(props: SessionChatProps) { cursorModelsState.currentModelId, machineCursorModelsState.availableModels, sessionCliModelSkus, - props.session.model + props.session.model, + t ]) const agyModelsState = useAgyModels({ api: props.api, diff --git a/web/src/lib/cursorCliSkuCatalog.test.ts b/web/src/lib/cursorCliSkuCatalog.test.ts index 6aae4bb7..09c1d608 100644 --- a/web/src/lib/cursorCliSkuCatalog.test.ts +++ b/web/src/lib/cursorCliSkuCatalog.test.ts @@ -36,4 +36,26 @@ describe('CLI sku variant catalog', () => { expect(variantIds).toContain('gpt-5.5-low') expect(variantIds.length).toBeGreaterThan(2) }) + + it('groups legacy cursor-prefixed skus under their ACP base (#1818)', () => { + const bareWires = [ + { modelId: 'grok-4.6', name: 'Cursor Grok 4.6' }, + { modelId: 'composer-2.5', name: 'Composer 2.5' }, + ] + const catalog = appendCliSkusToCatalog(buildCursorModelCatalog(bareWires), [ + { modelId: 'cursor-grok-4.6-high', name: 'Cursor Grok 4.6' }, + { modelId: 'cursor-grok-4.6-high-fast', name: 'Cursor Grok 4.6 Fast' }, + { modelId: 'composer-2.5-fast', name: 'Composer 2.5 Fast' }, + ]) + + const grokVariants = catalog.variantsByBase.get('grok-4.6') ?? [] + expect(grokVariants.map((row) => row.wireId)).toContain('cursor-grok-4.6-high') + expect(grokVariants.map((row) => row.wireId)).toContain('cursor-grok-4.6-high-fast') + expect(catalog.wireToBase.get('cursor-grok-4.6-high')).toBe('grok-4.6') + // The unrelated prefix group must not absorb other bases' skus. + expect(catalog.variantsByBase.get('composer-2.5')?.map((row) => row.wireId)).toEqual([ + 'composer-2.5', + 'composer-2.5-fast' + ]) + }) }) diff --git a/web/src/lib/cursorModelOptions.test.ts b/web/src/lib/cursorModelOptions.test.ts index ea6b654d..b264a0a8 100644 --- a/web/src/lib/cursorModelOptions.test.ts +++ b/web/src/lib/cursorModelOptions.test.ts @@ -74,7 +74,7 @@ describe('buildCursorModelCatalog', () => { { modelId: 'composer-2.5[fast=true]', name: 'composer-2.5' }, ]) expect(catalog.baseOptions.map((o) => o.value)).toEqual([ - null, + 'auto', 'composer-2.5', 'composer-2.5-fast', ]) diff --git a/web/src/lib/cursorModelOptions.ts b/web/src/lib/cursorModelOptions.ts index 6bf17986..f720b379 100644 --- a/web/src/lib/cursorModelOptions.ts +++ b/web/src/lib/cursorModelOptions.ts @@ -1,8 +1,11 @@ import { + CURSOR_AUTO_MODEL_ID, cursorCliSkuBaseId, + cursorModelBaseMatches, findBestCliSkuForAcpWire, isCursorAcpCatalogModelId, - isCursorAcpWireModelId as isSharedCursorAcpWireModelId + isCursorAcpWireModelId as isSharedCursorAcpWireModelId, + isCursorAutoModelId } from '@hapi/protocol' import type { CursorModelSummary } from '@/types/api' @@ -46,14 +49,25 @@ export function cursorModelDedupeKey(modelId: string): string { return cursorModelBaseId(modelId) } -function isDefaultCursorModelId(modelId: string): boolean { - const normalized = modelId.trim().toLowerCase() - return normalized === 'auto' || normalized === 'default' || normalized === 'default[]' +/** Existing catalog base for a CLI sku base, tolerating the legacy `cursor-` prefix. */ +function findCatalogBaseKey( + catalog: CursorModelCatalog, + skuBaseId: string +): string | null { + if (catalog.variantsByBase.has(skuBaseId)) { + return skuBaseId + } + for (const baseKey of catalog.variantsByBase.keys()) { + if (cursorModelBaseMatches(skuBaseId, baseKey)) { + return baseKey + } + } + return null } function normalizeCurrentModel(model?: string | null): string | null { const trimmed = model?.trim() - if (!trimmed || isDefaultCursorModelId(trimmed)) { + if (!trimmed || isCursorAutoModelId(trimmed)) { return null } return trimmed @@ -199,18 +213,18 @@ export function buildCursorModelCatalog( availableModels: readonly CursorModelSummary[], options?: { currentModel?: string | null - /** New-session spawn uses `auto`; active session uses `null` for default. */ + /** Auto row is always CLI `auto`; kept for caller compatibility. */ defaultValue?: null | 'auto' } ): CursorModelCatalog { - const defaultValue = options?.defaultValue === 'auto' ? 'auto' : null + const defaultValue = CURSOR_AUTO_MODEL_ID const variantsByBase = new Map() const wireToBase = new Map() const baseLabels = new Map() const addWire = (rawModelId: string): void => { const modelId = rawModelId.trim() - if (!modelId || isDefaultCursorModelId(modelId)) { + if (!modelId || isCursorAutoModelId(modelId)) { return } @@ -262,13 +276,16 @@ export function appendCliSkusToCatalog( for (const sku of cliSkus) { const modelId = sku.modelId.trim() - if (!modelId || isDefaultCursorModelId(modelId) || isCursorAcpWireModelId(modelId)) { + if (!modelId || isCursorAutoModelId(modelId) || isCursorAcpWireModelId(modelId)) { continue } const baseId = cursorCliSkuBaseId(modelId) - const existing = catalog.variantsByBase.get(baseId) - if (!existing || existing.length === 0) { + // CLI sku bases may carry the legacy `cursor-` family prefix + // (`cursor-grok-4.6-high` → ACP base `grok-4.6`). + const catalogBaseId = findCatalogBaseKey(catalog, baseId) + const existing = catalogBaseId ? catalog.variantsByBase.get(catalogBaseId) : undefined + if (!catalogBaseId || !existing || existing.length === 0) { continue } @@ -281,7 +298,7 @@ export function appendCliSkusToCatalog( label: sku.name?.trim() && sku.name !== modelId ? sku.name.trim() : modelId, sortKey: modelId }) - catalog.wireToBase.set(modelId, baseId) + catalog.wireToBase.set(modelId, catalogBaseId) } return catalog @@ -354,7 +371,7 @@ export function buildFlatCursorModelPickerOptions( catalog: CursorModelCatalog, options?: { defaultValue?: null | 'auto' } ): Array<{ value: string; label: string }> { - const defaultValue = options?.defaultValue === 'auto' ? 'auto' : null + const defaultValue = CURSOR_AUTO_MODEL_ID const rows: Array<{ value: string; label: string }> = [] for (const [baseId, variants] of catalog.variantsByBase) { diff --git a/web/src/lib/cursorPickerState.ts b/web/src/lib/cursorPickerState.ts index 31ec6ed2..f5a3a025 100644 --- a/web/src/lib/cursorPickerState.ts +++ b/web/src/lib/cursorPickerState.ts @@ -1,4 +1,4 @@ -import { isCursorAcpCatalogModelId } from '@hapi/protocol' +import { CURSOR_AUTO_MODEL_ID, isCursorAcpCatalogModelId, isCursorAutoModelId } from '@hapi/protocol' import type { CursorModelSummary } from '@/types/api' import { appendCliSkusToCatalog, @@ -118,11 +118,11 @@ export function buildCursorCatalogFromSources(args: { export function normalizeCursorPickerWireId( wireId: string | null | undefined, - defaultToken: 'auto' | null = null + defaultToken: 'auto' | null = CURSOR_AUTO_MODEL_ID ): string | null { const trimmed = wireId?.trim() - if (!trimmed || trimmed === 'auto' || trimmed === 'default' || trimmed === 'default[]') { - return defaultToken + if (!trimmed || isCursorAutoModelId(trimmed)) { + return defaultToken ?? CURSOR_AUTO_MODEL_ID } return trimmed } @@ -132,7 +132,7 @@ export function buildCursorPickerState(args: { currentWireId?: string | null defaultValue?: null | 'auto' }): CursorPickerState { - const defaultToken = args.defaultValue === 'auto' ? 'auto' : null + const defaultToken = CURSOR_AUTO_MODEL_ID const wireId = normalizeCursorPickerWireId(args.currentWireId, defaultToken) const baseKey = wireId && wireId !== 'auto' ? resolveCursorBaseKey(wireId, args.catalog) @@ -149,7 +149,7 @@ export function buildCursorPickerState(args: { label: option.label })) : buildFlatCursorModelPickerOptions(args.catalog, { - defaultValue: args.defaultValue === 'auto' ? 'auto' : undefined + defaultValue: CURSOR_AUTO_MODEL_ID }).map((option) => ({ value: option.value ?? 'auto', label: option.label diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index 6fc57569..2d5e8215 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -181,6 +181,7 @@ export default { 'session.item.model': 'model', 'session.item.machine': 'machine', 'session.modelChange.pending': 'Changing…', + 'session.modelChange.cursorAutoRestart': 'Auto (switching back requires restart)', 'session.modelChange.pendingTooltip': 'The model will change when the current task finishes.', 'session.item.worktree': 'worktree', 'session.item.pending': 'pending', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 25378bb8..6dca4945 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -181,6 +181,7 @@ export default { 'session.item.model': '模型', 'session.item.machine': '机器', 'session.modelChange.pending': '更改中…', + 'session.modelChange.cursorAutoRestart': 'Auto(切回需要重启)', 'session.modelChange.pendingTooltip': '当前任务完成后将更改模型。', 'session.item.worktree': '工作树', 'session.item.pending': '待处理', diff --git a/web/src/lib/sessionChatCursorModel.test.ts b/web/src/lib/sessionChatCursorModel.test.ts index 66763809..7bf1992e 100644 --- a/web/src/lib/sessionChatCursorModel.test.ts +++ b/web/src/lib/sessionChatCursorModel.test.ts @@ -16,6 +16,18 @@ const sessionModels = [ ] as const describe('resolveSessionCursorModelChange', () => { + it.each([false, true])('labels the live Auto limitation only without native Auto (native=%s)', (nativeAuto) => { + const picker = buildSessionCursorPickerState({ + sessionModels: [{ modelId: nativeAuto ? 'auto' : 'default' }, ...sessionModels], + machineModels: [{ modelId: 'auto' }], + sessionModel: 'composer-2.5[fast=true]', + sessionCurrentModelId: 'composer-2.5[fast=true]', + autoRestartLabel: 'Auto (switching back requires restart)' + }) + expect(picker.modelOptions.find(option => option.value === 'auto')?.label) + .toBe(nativeAuto ? 'Auto' : 'Auto (switching back requires restart)') + }) + const picker = buildSessionCursorPickerState({ sessionModels, machineModels: [], @@ -39,6 +51,22 @@ describe('resolveSessionCursorModelChange', () => { }) }) + it('selecting Auto applies the CLI auto model id', () => { + const plan = resolveSessionCursorModelChange({ + picker, + sessionModel: 'composer-2.5[fast=true]', + cursorSelectedBase: 'composer-2.5', + kind: 'base', + value: 'auto' + }) + expect(plan).toEqual({ + ok: true, + wireId: 'auto', + nextSelectedBase: 'auto', + shouldApply: true + }) + }) + it('applies a base change when the base has exactly one wire variant', () => { const singlePicker = buildSessionCursorPickerState({ sessionModels: [{ modelId: 'gpt-5.5[context=272k,reasoning=medium,fast=false]' }], diff --git a/web/src/lib/sessionChatCursorModel.ts b/web/src/lib/sessionChatCursorModel.ts index e9075542..6dc015b1 100644 --- a/web/src/lib/sessionChatCursorModel.ts +++ b/web/src/lib/sessionChatCursorModel.ts @@ -45,7 +45,7 @@ export function resolveSessionCursorModelChange(args: { if (kind === 'base') { if (!value || value === 'auto') { - return { ok: true, wireId: null, nextSelectedBase: 'auto', shouldApply: true } + return { ok: true, wireId: 'auto', nextSelectedBase: 'auto', shouldApply: true } } if (value.includes('[')) { const base = resolveCursorBaseFromWire(value, picker.catalog) @@ -64,7 +64,7 @@ export function resolveSessionCursorModelChange(args: { const wireId = resolveWireIdForBaseChange(value, picker.catalog, sessionModel) return { ok: true, - wireId: wireId === 'auto' ? null : wireId, + wireId: wireId === 'auto' ? 'auto' : wireId, nextSelectedBase: value, shouldApply: wireId !== null } @@ -83,7 +83,7 @@ export function resolveSessionCursorModelChange(args: { // flat picker: value is wire id or auto if (!value || value === 'auto') { - return { ok: true, wireId: null, nextSelectedBase: 'auto', shouldApply: true } + return { ok: true, wireId: 'auto', nextSelectedBase: 'auto', shouldApply: true } } if (!picker.catalog.wireToBase.has(value)) { return { ok: false, reason: 'model wire id not in catalog' } @@ -208,6 +208,7 @@ export function buildSessionCursorPickerState(args: { cliModelSkus?: readonly CursorModelSummary[] sessionModel: string | null | undefined sessionCurrentModelId: string | null + autoRestartLabel?: string }): CursorPickerState { const catalog = buildCursorCatalogFromSources({ sessionModels: args.sessionModels, @@ -215,11 +216,18 @@ export function buildSessionCursorPickerState(args: { cliModelSkus: args.cliModelSkus, currentWireId: args.sessionCurrentModelId ?? args.sessionModel, sessionModelFromHub: args.sessionModel, - defaultValue: null + defaultValue: 'auto' }) - return buildCursorPickerState({ + const picker = buildCursorPickerState({ catalog, currentWireId: args.sessionModel ?? args.sessionCurrentModelId, - defaultValue: null + defaultValue: 'auto' }) + const autoRestartLabel = args.autoRestartLabel + if (autoRestartLabel && !args.sessionModels.some(model => model.modelId.trim() === 'auto')) { + picker.modelOptions = picker.modelOptions.map(option => option.value === 'auto' + ? { ...option, label: autoRestartLabel } + : option) + } + return picker } From a7ad63169194cf8eb3753676d4dd39851a3988f4 Mon Sep 17 00:00:00 2001 From: Ananovo Date: Wed, 16 Sep 2026 08:15:02 +0800 Subject: [PATCH 11/34] feat(web): auto-hide primary session scrollbars (#1730) * feat(web): auto-hide primary session scrollbars * test(web): run scrollbar auto-hide E2E in CI --- .github/workflows/test.yml | 2 +- e2e/scrollbar-auto-hide.spec.ts | 105 +++++++++++ .../session-list-scrollbar-fixture.html | 12 ++ .../session-list-scrollbar-fixture.tsx | 62 +++++++ .../components/AssistantChat/HappyThread.tsx | 4 +- web/src/components/SessionList.tsx | 4 +- web/src/hooks/useTransientScrollbar.test.tsx | 103 +++++++++++ web/src/hooks/useTransientScrollbar.ts | 163 ++++++++++++++++++ web/src/index.css | 85 +++++++++ 9 files changed, 537 insertions(+), 3 deletions(-) create mode 100644 e2e/scrollbar-auto-hide.spec.ts create mode 100644 web/e2e-fixtures/session-list-scrollbar-fixture.html create mode 100644 web/e2e-fixtures/session-list-scrollbar-fixture.tsx create mode 100644 web/src/hooks/useTransientScrollbar.test.tsx create mode 100644 web/src/hooks/useTransientScrollbar.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 09de87f9..6c13d0de 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,7 +15,7 @@ jobs: - run: bun install --frozen-lockfile - run: bun typecheck - run: bunx playwright install --with-deps chromium - - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts + - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts scrollbar-auto-hide.spec.ts - run: bun run test # Serial runner-integration suite: starts real detached runner/session diff --git a/e2e/scrollbar-auto-hide.spec.ts b/e2e/scrollbar-auto-hide.spec.ts new file mode 100644 index 00000000..bd7d4c8c --- /dev/null +++ b/e2e/scrollbar-auto-hide.spec.ts @@ -0,0 +1,105 @@ +import { devices, expect, test, type Locator } from '@playwright/test' + +const SCROLLBAR_ATTRIBUTE = 'data-scrollbar-visible' +const HIDE_DELAY_MS = 1_000 +const FADE_DURATION = '0.3s' + +async function expectScrollbarToHide(locator: Locator) { + await expect.poll(async () => locator.getAttribute(SCROLLBAR_ATTRIBUTE), { + timeout: HIDE_DELAY_MS + 2_000, + intervals: [100, 250] + }).toBeNull() +} + +test.use({ ...devices['Pixel 5'], viewport: { width: 412, height: 915 }, deviceScaleFactor: 1 }) + +test.describe('session scrollbar auto-hide', () => { + test.describe.configure({ timeout: 60_000 }) + + test('hides the session list scrollbar after one second and keeps it visible on focus', async ({ page }) => { + await page.goto('/e2e-fixtures/session-list-scrollbar-fixture.html') + + const viewport = page.locator('.session-list-scrollbar-left') + await expect(viewport).toBeVisible() + const fallback = page.locator('.transient-scrollbar-fallback-left') + const fallbackThumb = fallback.locator('.transient-scrollbar-fallback-thumb') + await expect(fallback).toBeVisible() + await expect(fallback).toHaveAttribute('data-visible', 'true') + await expect(fallbackThumb).toHaveCSS('transition-property', /opacity/) + const transitions = await viewport.evaluate((element) => ({ + surface: getComputedStyle(element).transitionProperty, + surfaceDuration: getComputedStyle(element).transitionDuration, + thumb: getComputedStyle(element, '::-webkit-scrollbar-thumb').transitionProperty, + thumbDuration: getComputedStyle(element, '::-webkit-scrollbar-thumb').transitionDuration, + })) + expect(transitions.surface).toContain('scrollbar-color') + expect(transitions.surfaceDuration).toBe(FADE_DURATION) + expect(transitions.thumb).toContain('background-color') + expect(transitions.thumbDuration).toBe(FADE_DURATION) + await expect(fallbackThumb).toHaveCSS('transition-duration', FADE_DURATION) + await expect(viewport).toHaveAttribute(SCROLLBAR_ATTRIBUTE, 'true') + await expectScrollbarToHide(viewport) + await expect(fallback).not.toHaveAttribute('data-visible') + await expect(fallbackThumb).toHaveCSS('opacity', '0') + + await viewport.evaluate((element) => { + element.scrollTop = Math.min(200, element.scrollHeight) + element.dispatchEvent(new Event('scroll')) + }) + await expect(viewport).toHaveAttribute(SCROLLBAR_ATTRIBUTE, 'true') + await expect(fallback).toHaveAttribute('data-visible', 'true') + await expect(fallbackThumb).toHaveCSS('opacity', '1') + await expectScrollbarToHide(viewport) + await expect(fallback).not.toHaveAttribute('data-visible') + + await viewport.locator('button').first().focus() + await expect(viewport).toHaveAttribute(SCROLLBAR_ATTRIBUTE, 'true') + await expect(fallback).toHaveAttribute('data-visible', 'true') + await page.waitForTimeout(HIDE_DELAY_MS + 200) + await expect(viewport).toHaveAttribute(SCROLLBAR_ATTRIBUTE, 'true') + await expect(fallback).toHaveAttribute('data-visible', 'true') + }) + + test('hides the main chat scrollbar after one second and keeps it visible on focus', async ({ page }) => { + await page.goto('/e2e-fixtures/history-load-fixture.html') + + const viewport = page.locator('.chat-scroll-y') + await expect(viewport).toBeVisible() + const fallback = page.locator('.transient-scrollbar-fallback-right') + const fallbackThumb = fallback.locator('.transient-scrollbar-fallback-thumb') + await expect(fallback).toBeVisible() + await expect(fallback).toHaveAttribute('data-visible', 'true') + await expect(fallbackThumb).toHaveCSS('transition-property', /opacity/) + const transitions = await viewport.evaluate((element) => ({ + surface: getComputedStyle(element).transitionProperty, + surfaceDuration: getComputedStyle(element).transitionDuration, + thumb: getComputedStyle(element, '::-webkit-scrollbar-thumb').transitionProperty, + thumbDuration: getComputedStyle(element, '::-webkit-scrollbar-thumb').transitionDuration, + })) + expect(transitions.surface).toContain('scrollbar-color') + expect(transitions.surfaceDuration).toBe(FADE_DURATION) + expect(transitions.thumb).toContain('background-color') + expect(transitions.thumbDuration).toBe(FADE_DURATION) + await expect(fallbackThumb).toHaveCSS('transition-duration', FADE_DURATION) + await expect(viewport).toHaveAttribute(SCROLLBAR_ATTRIBUTE, 'true') + await expectScrollbarToHide(viewport) + await expect(fallback).not.toHaveAttribute('data-visible') + await expect(fallbackThumb).toHaveCSS('opacity', '0') + + await viewport.evaluate((element) => { + element.dispatchEvent(new Event('scroll')) + }) + await expect(viewport).toHaveAttribute(SCROLLBAR_ATTRIBUTE, 'true') + await expect(fallback).toHaveAttribute('data-visible', 'true') + await expect(fallbackThumb).toHaveCSS('opacity', '1') + await expectScrollbarToHide(viewport) + await expect(fallback).not.toHaveAttribute('data-visible') + + await viewport.focus() + await expect(viewport).toHaveAttribute(SCROLLBAR_ATTRIBUTE, 'true') + await expect(fallback).toHaveAttribute('data-visible', 'true') + await page.waitForTimeout(HIDE_DELAY_MS + 200) + await expect(viewport).toHaveAttribute(SCROLLBAR_ATTRIBUTE, 'true') + await expect(fallback).toHaveAttribute('data-visible', 'true') + }) +}) diff --git a/web/e2e-fixtures/session-list-scrollbar-fixture.html b/web/e2e-fixtures/session-list-scrollbar-fixture.html new file mode 100644 index 00000000..73bb6f26 --- /dev/null +++ b/web/e2e-fixtures/session-list-scrollbar-fixture.html @@ -0,0 +1,12 @@ + + + + + + HAPI session list scrollbar e2e fixture + + +
+ + + diff --git a/web/e2e-fixtures/session-list-scrollbar-fixture.tsx b/web/e2e-fixtures/session-list-scrollbar-fixture.tsx new file mode 100644 index 00000000..6df92b3c --- /dev/null +++ b/web/e2e-fixtures/session-list-scrollbar-fixture.tsx @@ -0,0 +1,62 @@ +import ReactDOM from 'react-dom/client' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import '../src/index.css' +import { I18nProvider } from '../src/lib/i18n-context' +import { ToastProvider } from '../src/lib/toast-context' +import { SessionList } from '../src/components/SessionList' +import type { SessionSummary } from '../src/types/api' + +const sessions: SessionSummary[] = Array.from({ length: 40 }, (_, index) => ({ + id: `session-list-scroll-${index}`, + active: true, + thinking: false, + activeAt: 1_700_000_000_000 - index, + updatedAt: 1_700_000_000_000 - index, + metadata: { + path: '/work/hapi', + name: `Fixture session ${index + 1}`, + machineId: 'fixture-machine', + agentSessionId: `thread-${index}` + }, + metadataVersion: 0, + agentStateVersion: 0, + todosUpdatedAt: 0, + todoProgress: null, + pendingRequestsCount: 0, + pendingRequestKinds: [], + pendingRequests: [], + backgroundTaskCount: 0, + futureScheduledMessageCount: 0, + nextScheduledAt: null, + model: null, + effort: null +})) + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false } + } +}) + +ReactDOM.createRoot(document.getElementById('root')!).render( + + + +
+ {}} + onNewSession={() => {}} + onRefresh={() => {}} + isLoading={false} + renderHeader={false} + api={null} + machineLabelsById={{ 'fixture-machine': 'Fixture machine' }} + /> +
+
+
+
+) diff --git a/web/src/components/AssistantChat/HappyThread.tsx b/web/src/components/AssistantChat/HappyThread.tsx index e428e97b..388cae21 100644 --- a/web/src/components/AssistantChat/HappyThread.tsx +++ b/web/src/components/AssistantChat/HappyThread.tsx @@ -33,6 +33,7 @@ import { formatRelativeTime } from '@/lib/relativeTime' import { formatSessionHeaderTimestamp } from '@/lib/sessionHeaderTimestamp' import { getShareTurnReasoningLabel, selectShareTurnMetadata } from '@/lib/shareTurnMetadata' import { useMinuteTick } from '@/hooks/useMinuteTick' +import { useTransientScrollbar } from '@/hooks/useTransientScrollbar' import { queryKeys } from '@/lib/query-keys' import { matchesSearchQuery } from '@hapi/protocol' @@ -619,6 +620,7 @@ export function HappyThread(props: { const appliedMessagesVersion = runtimeExtras?.messagesVersion ?? props.messagesVersion const appliedHistoryVersion = runtimeExtras?.historyVersion ?? props.historyVersion const viewportRef = useRef(null) + useTransientScrollbar(viewportRef, 'right') const contentRef = useRef(null) const [pullToLoadState, setPullToLoadState] = useState('idle') const [showScrollToBottom, setShowScrollToBottom] = useState(false) @@ -1748,7 +1750,7 @@ export function HappyThread(props: { >
diff --git a/web/src/components/SessionList.tsx b/web/src/components/SessionList.tsx index 771c971d..d09f346e 100644 --- a/web/src/components/SessionList.tsx +++ b/web/src/components/SessionList.tsx @@ -55,6 +55,7 @@ import type { Machine } from '@/types/api' import { getMachinePlatform, presentMachineHealth } from '@/lib/machineHealth' import { MachineFilterBar, MachineFilterMenu } from '@/components/MachineFilterBar' import { useSessionListMachineFilter } from '@/hooks/useSessionListMachineFilter' +import { useTransientScrollbar } from '@/hooks/useTransientScrollbar' import { useCursorChatStoreStatus } from '@/hooks/queries/useCursorChatStoreStatus' import { SessionRowSummary } from '@/components/SessionRowSummary' import { Spinner } from '@/components/Spinner' @@ -1829,6 +1830,7 @@ export function SessionList(props: { // pull-to-load-older pattern in HappyThread; desktop has no overscroll // bounce to make a wheel pull feel right, so it stays on live updates. const scrollContainerRef = useRef(null) + useTransientScrollbar(scrollContainerRef, 'left') const [pullState, setPullState] = useState('idle') const pullStateRef = useRef('idle') const [isRefreshing, setIsRefreshing] = useState(false) @@ -2027,7 +2029,7 @@ export function SessionList(props: {
) : null} -
+
{props.sessions.length === 0 && !props.isLoading ? ( (null) + useTransientScrollbar(ref) + return
{props.children}
+} + +function renderSurface() { + const result = render( + + + + ) + const surface = result.container.firstElementChild + if (!(surface instanceof HTMLElement)) { + throw new Error('Scrollable surface was not rendered') + } + const button = surface.querySelector('button') + if (!(button instanceof HTMLButtonElement)) { + throw new Error('Scrollable surface focus target was not rendered') + } + return { ...result, surface, button } +} + +beforeEach(() => { + vi.useFakeTimers() +}) + +afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() +}) + +describe('useTransientScrollbar', () => { + it('shows on mount and hides after one second without scrolling', () => { + const { surface } = renderSurface() + + expect(surface).toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE, 'true') + + act(() => { + vi.advanceTimersByTime(TRANSIENT_SCROLLBAR_HIDE_DELAY_MS - 1) + }) + expect(surface).toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE, 'true') + + act(() => { + vi.advanceTimersByTime(1) + }) + expect(surface).not.toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE) + }) + + it('resets the idle timer whenever the surface scrolls', () => { + const { surface } = renderSurface() + + act(() => { + vi.advanceTimersByTime(TRANSIENT_SCROLLBAR_HIDE_DELAY_MS) + }) + expect(surface).not.toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE) + + fireEvent.scroll(surface) + expect(surface).toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE, 'true') + + act(() => { + vi.advanceTimersByTime(TRANSIENT_SCROLLBAR_HIDE_DELAY_MS - 1) + }) + expect(surface).toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE, 'true') + + act(() => { + vi.advanceTimersByTime(1) + }) + expect(surface).not.toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE) + }) + + it('keeps the scrollbar visible while the surface or a child has focus', () => { + const { surface, button } = renderSurface() + + act(() => { + vi.advanceTimersByTime(TRANSIENT_SCROLLBAR_HIDE_DELAY_MS) + }) + expect(surface).not.toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE) + + fireEvent.focus(button) + expect(surface).toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE, 'true') + + act(() => { + vi.advanceTimersByTime(TRANSIENT_SCROLLBAR_HIDE_DELAY_MS * 2) + }) + expect(surface).toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE, 'true') + + fireEvent.blur(button) + act(() => { + vi.advanceTimersByTime(TRANSIENT_SCROLLBAR_HIDE_DELAY_MS) + }) + expect(surface).not.toHaveAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE) + }) +}) diff --git a/web/src/hooks/useTransientScrollbar.ts b/web/src/hooks/useTransientScrollbar.ts new file mode 100644 index 00000000..677c8902 --- /dev/null +++ b/web/src/hooks/useTransientScrollbar.ts @@ -0,0 +1,163 @@ +import { useEffect, useRef, type RefObject } from 'react' + +export const TRANSIENT_SCROLLBAR_HIDE_DELAY_MS = 1_000 +export const TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE = 'data-scrollbar-visible' + +export type TransientScrollbarSide = 'left' | 'right' + +/** + * Keeps a scoped scrollbar visible while its surface is being used, then + * hides only the thumb after a short idle period without changing layout. + */ +export function useTransientScrollbar( + ref: RefObject, + side: TransientScrollbarSide = 'right' +): void { + const hideTimerRef = useRef(null) + + useEffect(() => { + const element = ref.current + const host = element?.parentElement + if (!element || !host) return + + const fallback = document.createElement('span') + fallback.className = `transient-scrollbar-fallback transient-scrollbar-fallback-${side}` + fallback.setAttribute('aria-hidden', 'true') + const thumb = document.createElement('span') + thumb.className = 'transient-scrollbar-fallback-thumb' + fallback.append(thumb) + host.append(fallback) + const addedHostClass = !host.classList.contains('scrollbar-auto-hide-container') + host.classList.add('scrollbar-auto-hide-container') + + let hasFocusWithin = false + let frameId: number | null = null + let frameIsTimeout = false + + const clearHideTimer = () => { + if (hideTimerRef.current !== null) { + window.clearTimeout(hideTimerRef.current) + hideTimerRef.current = null + } + } + + const hideWhenIdle = () => { + hideTimerRef.current = null + if (!hasFocusWithin) { + setScrollbarVisible(false) + } + } + + const scheduleHide = () => { + clearHideTimer() + hideTimerRef.current = window.setTimeout(hideWhenIdle, TRANSIENT_SCROLLBAR_HIDE_DELAY_MS) + } + + const setScrollbarVisible = (visible: boolean) => { + if (visible) { + element.setAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE, 'true') + fallback.setAttribute('data-visible', 'true') + } else { + element.removeAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE) + fallback.removeAttribute('data-visible') + } + } + + const updateFallbackThumb = () => { + frameId = null + const viewportHeight = element.clientHeight + const scrollHeight = element.scrollHeight + const maxScrollTop = scrollHeight - viewportHeight + if (viewportHeight <= 0 || maxScrollTop <= 0) { + thumb.style.display = 'none' + return + } + + const thumbHeight = Math.max(24, Math.round(viewportHeight * viewportHeight / scrollHeight)) + const maxThumbOffset = Math.max(0, viewportHeight - thumbHeight) + const thumbOffset = maxScrollTop > 0 + ? maxThumbOffset * element.scrollTop / maxScrollTop + : 0 + thumb.style.display = '' + thumb.style.height = `${thumbHeight}px` + thumb.style.transform = `translateY(${thumbOffset}px)` + } + + const scheduleFallbackThumbUpdate = () => { + if (frameId !== null) return + if (typeof window.requestAnimationFrame === 'function') { + frameIsTimeout = false + frameId = window.requestAnimationFrame(updateFallbackThumb) + } else { + frameIsTimeout = true + frameId = window.setTimeout(updateFallbackThumb, 0) + } + } + + const show = () => { + setScrollbarVisible(true) + scheduleHide() + } + + const handleScroll = () => { + show() + scheduleFallbackThumbUpdate() + } + + const handleFocusIn = () => { + hasFocusWithin = true + clearHideTimer() + setScrollbarVisible(true) + } + + const handleFocusOut = () => { + hasFocusWithin = false + scheduleHide() + } + + element.addEventListener('scroll', handleScroll, { passive: true }) + element.addEventListener('focusin', handleFocusIn) + element.addEventListener('focusout', handleFocusOut) + + let resizeObserver: ResizeObserver | null = null + if (typeof ResizeObserver !== 'undefined') { + resizeObserver = new ResizeObserver(() => { + scheduleFallbackThumbUpdate() + }) + resizeObserver.observe(element) + if (element.firstElementChild) { + resizeObserver.observe(element.firstElementChild) + } + } + + const activeElement = document.activeElement + hasFocusWithin = activeElement === element || Boolean(activeElement && element.contains(activeElement)) + if (hasFocusWithin) { + handleFocusIn() + } else { + show() + } + updateFallbackThumb() + + return () => { + clearHideTimer() + if (frameId !== null) { + if (frameIsTimeout) { + window.clearTimeout(frameId) + } else { + window.cancelAnimationFrame(frameId) + } + frameId = null + } + resizeObserver?.disconnect() + element.removeEventListener('scroll', handleScroll) + element.removeEventListener('focusin', handleFocusIn) + element.removeEventListener('focusout', handleFocusOut) + element.removeAttribute(TRANSIENT_SCROLLBAR_VISIBLE_ATTRIBUTE) + fallback.remove() + if (addedHostClass) { + host.classList.remove('scrollbar-auto-hide-container') + } + } + }, [ref, side]) +} diff --git a/web/src/index.css b/web/src/index.css index 2e5a087d..7bcb6023 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -334,6 +334,91 @@ html:has(.chat-scroll-y) #root { touch-action: pan-y; } +/* Keep only the two primary session surfaces visually quiet while idle. + * Preserve scrollbar width/gutters so hiding the thumb cannot shift content. */ +.scrollbar-auto-hide { + transition: scrollbar-color 300ms ease-out; +} + +.scrollbar-auto-hide::-webkit-scrollbar-thumb { + transition: background-color 300ms ease-out; +} + +.scrollbar-auto-hide:not([data-scrollbar-visible="true"]):not(:focus-within) { + scrollbar-color: transparent transparent; +} + +.scrollbar-auto-hide:not([data-scrollbar-visible="true"]):not(:focus-within)::-webkit-scrollbar-thumb { + background-color: transparent; +} + +.scrollbar-auto-hide:not([data-scrollbar-visible="true"]):not(:focus-within)::-webkit-scrollbar-thumb:hover { + background-color: var(--app-scrollbar-thumb-hover); +} + +.scrollbar-auto-hide-container { + position: relative; +} + +.transient-scrollbar-fallback { + display: none; + position: absolute; + top: 0; + bottom: 0; + z-index: 10; + width: 10px; + pointer-events: none; +} + +.transient-scrollbar-fallback-left { + left: 0; +} + +.transient-scrollbar-fallback-right { + right: 0; +} + +.transient-scrollbar-fallback-thumb { + position: absolute; + top: 0; + left: 3px; + width: 4px; + min-height: 24px; + border-radius: 999px; + background-color: var(--app-scrollbar-thumb); + opacity: 0; + transition: opacity 300ms ease-out; +} + +.transient-scrollbar-fallback[data-visible="true"] .transient-scrollbar-fallback-thumb { + opacity: 1; +} + +@media (hover: none) and (pointer: coarse) { + /* Mobile browsers may paint native overlay scrollbars outside the CSS + * transition pipeline. Keep the native hit area, but use the fallback + * thumb for the animated visual. */ + .scrollbar-auto-hide { + scrollbar-color: transparent transparent; + } + + .scrollbar-auto-hide::-webkit-scrollbar-thumb { + background-color: transparent; + } + + .transient-scrollbar-fallback { + display: block; + } +} + +@media (prefers-reduced-motion: reduce) { + .scrollbar-auto-hide, + .scrollbar-auto-hide::-webkit-scrollbar-thumb, + .transient-scrollbar-fallback-thumb { + transition-duration: 0s; + } +} + /* On touch-first devices, keep the chat scrollbar from shifting centered content. */ @media (hover: none) and (pointer: coarse) { .chat-scroll-y { From 773af2cf6597fdd7ceed6dd5a154e1f7df78d7f1 Mon Sep 17 00:00:00 2001 From: IanMStevenson Date: Sat, 19 Sep 2026 02:46:38 +0100 Subject: [PATCH 12/34] feat(web): setting to open external links in a new tab (#1884) * feat(web): setting to open external links in a new tab Left-clicking an external http(s) link renders it with no explicit target, defaulting to _self. In an installed/standalone PWA this gets intercepted by the browser and shown as a captive in-app overlay instead of leaving the app; in a normal tab it navigates away from HAPI entirely. Right-click already opens in a new tab, but that's not a fair ask for every link. Add an opt-in Settings > Display > Links toggle that forces target="_blank" rel="noopener noreferrer" on genuine external http(s) links only (relative/SPA hrefs and other schemes like mailto are left untouched). Defaults to off, preserving today's behaviour, since the overlay may be intentional/liked by some users. Vibe Coding disclosure: implemented with Claude Sonnet 5 (Claude Code). * fix(web): simplify link-toggle setting description per review The description mentioned the target attribute (an implementation detail, not user-facing) and asserted the in-app overlay is what every installed PWA shows, which was only actually confirmed on Chromium/ Edge. Describe the user-visible behaviour only, without promising a specific rendering across all installed-app environments. * fix(web): stop promising specific behaviour when installed as an app Per follow-up review: describing the setting as "always" opening links in a new tab "even when installed as an app" still guarantees a specific outcome across every browser's PWA handling, which isn't something this change can verify or promise. State only what the setting does (open in a separate tab), not how every installed-app environment will render that. --------- Co-authored-by: Ian Stevenson --- .../assistant-ui/markdown-a.test.tsx | 46 +++++++++ .../assistant-ui/markdown-text.test.ts | 33 +++++++ .../components/assistant-ui/markdown-text.tsx | 36 ++++++- .../useOpenExternalLinksInNewTab.test.ts | 77 +++++++++++++++ web/src/hooks/useOpenExternalLinksInNewTab.ts | 99 +++++++++++++++++++ web/src/lib/locales/en.ts | 3 + web/src/lib/locales/zh-CN.ts | 3 + web/src/routes/settings/display.tsx | 11 +++ 8 files changed, 306 insertions(+), 2 deletions(-) create mode 100644 web/src/hooks/useOpenExternalLinksInNewTab.test.ts create mode 100644 web/src/hooks/useOpenExternalLinksInNewTab.ts diff --git a/web/src/components/assistant-ui/markdown-a.test.tsx b/web/src/components/assistant-ui/markdown-a.test.tsx index d5c16131..0fcf9b58 100644 --- a/web/src/components/assistant-ui/markdown-a.test.tsx +++ b/web/src/components/assistant-ui/markdown-a.test.tsx @@ -66,6 +66,7 @@ function chatContext(overrides: Partial = {}): HappyChatC } const STORAGE_KEY = 'hapi-allowed-schemes' +const OPEN_NEW_TAB_STORAGE_KEY = 'hapi-open-external-links-in-new-tab' beforeEach(() => { localStorage.clear() @@ -422,6 +423,51 @@ describe('markdown component — fail-closed path-like hrefs (#1452)', () => }) }) +// ── "open external links in a new tab" setting (Settings > Display > Links) ── + +describe('markdown component — open external links in new tab setting', () => { + it('defaults to no explicit target on an external http(s) link', () => { + renderA({ href: 'https://example.com', children: 'link' }) + expect(document.querySelector('a')!.getAttribute('target')).toBeNull() + }) + + it('forces target="_blank" + rel="noopener noreferrer" when the setting is enabled', () => { + localStorage.setItem(OPEN_NEW_TAB_STORAGE_KEY, 'true') + renderA({ href: 'https://example.com', children: 'link' }) + const link = document.querySelector('a')! + expect(link.getAttribute('target')).toBe('_blank') + expect(link.getAttribute('rel')).toBe('noopener noreferrer') + }) + + it('does not force target on a relative/SPA href even when the setting is enabled', () => { + localStorage.setItem(OPEN_NEW_TAB_STORAGE_KEY, 'true') + renderA({ href: '/settings', children: 'settings' }, chatContext()) + expect(document.querySelector('a')!.getAttribute('target')).toBeNull() + }) + + it('does not force target on a non-http(s) IANA scheme (mailto) even when enabled', () => { + localStorage.setItem(OPEN_NEW_TAB_STORAGE_KEY, 'true') + renderA({ href: 'mailto:a@b.com', children: 'mail' }) + expect(document.querySelector('a')!.getAttribute('target')).toBeNull() + }) + + it('updates an already-rendered link when the setting changes via storage event (settings page in another tab, or Settings > Display in this one after context refactor)', () => { + renderA({ href: 'https://example.com', children: 'link' }) + expect(document.querySelector('a')!.getAttribute('target')).toBeNull() + + act(() => { + localStorage.setItem(OPEN_NEW_TAB_STORAGE_KEY, 'true') + window.dispatchEvent(new StorageEvent('storage', { + key: OPEN_NEW_TAB_STORAGE_KEY, + newValue: 'true', + storageArea: localStorage, + })) + }) + + expect(document.querySelector('a')!.getAttribute('target')).toBe('_blank') + }) +}) + // ── intra-tab cross-provider sync (schemeListeners emitter) ────────────────── // // P7e.1 added a module-level `schemeListeners: Set` so that diff --git a/web/src/components/assistant-ui/markdown-text.test.ts b/web/src/components/assistant-ui/markdown-text.test.ts index 574a4a33..dab45789 100644 --- a/web/src/components/assistant-ui/markdown-text.test.ts +++ b/web/src/components/assistant-ui/markdown-text.test.ts @@ -12,6 +12,7 @@ import { MARKDOWN_PLUGINS_STANDALONE_WITH_BREAKS, MARKDOWN_PLUGINS_WITH_BREAKS, MARKDOWN_REHYPE_PLUGINS, + isExternalHttpHref, } from '@/components/assistant-ui/markdown-text' describe('MARKDOWN_PLUGINS integration', () => { @@ -97,3 +98,35 @@ describe('MARKDOWN_PLUGINS — currency prose vs KaTeX', () => { expect(html).toContain('class="katex"') }) }) + +describe('isExternalHttpHref', () => { + it('is true for http/https links', () => { + expect(isExternalHttpHref('https://example.com')).toBe(true) + expect(isExternalHttpHref('http://example.com/path?q=1#frag')).toBe(true) + expect(isExternalHttpHref('HTTPS://Example.com')).toBe(true) + }) + + it('is false for relative/SPA hrefs', () => { + expect(isExternalHttpHref('/settings')).toBe(false) + expect(isExternalHttpHref('./foo')).toBe(false) + expect(isExternalHttpHref('#section')).toBe(false) + expect(isExternalHttpHref('?q=1')).toBe(false) + expect(isExternalHttpHref('/path:colon')).toBe(false) + }) + + it('is false for non-http(s) schemes', () => { + expect(isExternalHttpHref('mailto:a@b.com')).toBe(false) + expect(isExternalHttpHref('vscode://file/foo')).toBe(false) + expect(isExternalHttpHref('javascript:alert(1)')).toBe(false) + }) + + it('is false for Windows drive paths (single-letter scheme, not http/https)', () => { + expect(isExternalHttpHref('C:\\Users\\ian\\file.txt')).toBe(false) + }) + + it('is false for empty/nullish input', () => { + expect(isExternalHttpHref('')).toBe(false) + expect(isExternalHttpHref(null)).toBe(false) + expect(isExternalHttpHref(undefined)).toBe(false) + }) +}) diff --git a/web/src/components/assistant-ui/markdown-text.tsx b/web/src/components/assistant-ui/markdown-text.tsx index 68ea713c..26982a6a 100644 --- a/web/src/components/assistant-ui/markdown-text.tsx +++ b/web/src/components/assistant-ui/markdown-text.tsx @@ -32,6 +32,7 @@ import { classifyNoSchemeHref } from '@/lib/markdown-href-policy' import { remarkSessionPathLinks } from '@/lib/remark-session-path-links' import { buildSessionReferencePath, parseSessionPathHref } from '@/lib/sessionReference' import { UriConfirmDialog } from '@/components/UriConfirmDialog' +import { DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB, useOpenExternalLinksInNewTab } from '@/hooks/useOpenExternalLinksInNewTab' import type { MarkdownTextPrimitiveProps } from '@assistant-ui/react-markdown' @@ -217,6 +218,23 @@ function hasScheme(href: string): boolean { return boundaryIdx < 0 || colonIdx < boundaryIdx } +/** + * True when href is a genuine external http(s) link — as opposed to a + * relative/SPA href (no scheme, e.g. `/settings`) or another scheme + * (`mailto:`, `vscode:`, a Windows drive path like `C:\Users\...`, etc). + * + * Used by to decide whether the "open external links in a new tab" + * setting (Settings > Display > Links) applies — forcing target="_blank" on + * a relative href would open the whole app in a second tab instead of + * navigating in-app, so this must stay scoped to real http(s) URLs. + */ +export function isExternalHttpHref(href: string | null | undefined): boolean { + if (!href || !hasScheme(href)) return false + const colonIdx = href.indexOf(':') + const scheme = href.slice(0, colonIdx).toLowerCase() + return scheme === 'http' || scheme === 'https' +} + // ── URL sanitize transform (deny-only) ────────────────────────────────────── // Passed as urlTransform to MarkdownTextPrimitive. Only deny-listed schemes // are stripped; every other scheme (IANA + custom) passes through so the @@ -349,6 +367,8 @@ type UriConfirmContextValue = { openUri: (url: string, scheme: string) => void /** Shared isAllowed so all tags in this tree re-render on the same state update. */ isAllowed: (scheme: string) => boolean + /** User preference (Settings > Display > Links): force target="_blank" on external http(s) links. */ + openExternalLinksInNewTab: boolean } const UriConfirmContext = createContext(null) @@ -366,6 +386,7 @@ const UriConfirmContext = createContext(null) export function UriConfirmProvider({ children }: { children: ReactNode }) { const [dialog, setDialog] = useState(null) const { allow, isAllowed } = useAllowedSchemes() + const { openExternalLinksInNewTab } = useOpenExternalLinksInNewTab() const openUri = useCallback((url: string, scheme: string) => { setDialog({ url, scheme }) @@ -387,7 +408,10 @@ export function UriConfirmProvider({ children }: { children: ReactNode }) { } } - const contextValue = useMemo(() => ({ openUri, isAllowed }), [openUri, isAllowed]) + const contextValue = useMemo( + () => ({ openUri, isAllowed, openExternalLinksInNewTab }), + [openUri, isAllowed, openExternalLinksInNewTab] + ) return ( @@ -693,6 +717,13 @@ function A(props: ComponentPropsWithoutRef<'a'>) { const scheme = colonIdx > 0 && !isRelative ? href!.slice(0, colonIdx).toLowerCase() : '' const isCustomAllowed = classification === 'custom' && isAllowed(scheme) + // Settings > Display > Links toggle: force genuine external http(s) links + // to open in a new browser tab instead of navigating same-tab. + const openExternalLinksInNewTab = ctx?.openExternalLinksInNewTab ?? DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB + const forceNewTab = openExternalLinksInNewTab && isExternalHttpHref(href) + const target = forceNewTab ? '_blank' : props.target + const effectiveRel = forceNewTab ? (rel ?? 'noopener noreferrer') : rel + const domHref = classification === 'iana' || isCustomAllowed ? href @@ -732,7 +763,8 @@ function A(props: ComponentPropsWithoutRef<'a'>) { diff --git a/web/src/hooks/useOpenExternalLinksInNewTab.test.ts b/web/src/hooks/useOpenExternalLinksInNewTab.test.ts new file mode 100644 index 00000000..fe05d1fe --- /dev/null +++ b/web/src/hooks/useOpenExternalLinksInNewTab.test.ts @@ -0,0 +1,77 @@ +import { act, renderHook } from '@testing-library/react' +import { beforeEach, describe, expect, it } from 'vitest' +import { + DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB, + getInitialOpenExternalLinksInNewTab, + useOpenExternalLinksInNewTab, +} from './useOpenExternalLinksInNewTab' + +const STORAGE_KEY = 'hapi-open-external-links-in-new-tab' + +describe('useOpenExternalLinksInNewTab helpers', () => { + beforeEach(() => { + window.localStorage.clear() + }) + + it('defaults to disabled (today’s existing link behaviour)', () => { + expect(getInitialOpenExternalLinksInNewTab()).toBe(DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB) + expect(getInitialOpenExternalLinksInNewTab()).toBe(false) + }) + + it('reads the stored value and falls back for other values', () => { + window.localStorage.setItem(STORAGE_KEY, 'true') + expect(getInitialOpenExternalLinksInNewTab()).toBe(true) + + window.localStorage.setItem(STORAGE_KEY, 'invalid') + expect(getInitialOpenExternalLinksInNewTab()).toBe(false) + }) +}) + +describe('useOpenExternalLinksInNewTab', () => { + beforeEach(() => { + window.localStorage.clear() + }) + + it('persists changes and synchronizes hook instances in the same tab', () => { + const first = renderHook(() => useOpenExternalLinksInNewTab()) + const second = renderHook(() => useOpenExternalLinksInNewTab()) + + act(() => first.result.current.setOpenExternalLinksInNewTab(true)) + + expect(first.result.current.openExternalLinksInNewTab).toBe(true) + expect(second.result.current.openExternalLinksInNewTab).toBe(true) + expect(window.localStorage.getItem(STORAGE_KEY)).toBe('true') + + act(() => second.result.current.setOpenExternalLinksInNewTab(false)) + + expect(first.result.current.openExternalLinksInNewTab).toBe(false) + expect(second.result.current.openExternalLinksInNewTab).toBe(false) + expect(window.localStorage.getItem(STORAGE_KEY)).toBeNull() + }) + + it('synchronizes changes from another browsing context', () => { + const { result } = renderHook(() => useOpenExternalLinksInNewTab()) + + act(() => { + window.dispatchEvent(new StorageEvent('storage', { + key: STORAGE_KEY, + newValue: 'true', + })) + }) + + expect(result.current.openExternalLinksInNewTab).toBe(true) + }) + + it('ignores storage events for unrelated keys', () => { + const { result } = renderHook(() => useOpenExternalLinksInNewTab()) + + act(() => { + window.dispatchEvent(new StorageEvent('storage', { + key: 'hapi-other-setting', + newValue: 'false', + })) + }) + + expect(result.current.openExternalLinksInNewTab).toBe(false) + }) +}) diff --git a/web/src/hooks/useOpenExternalLinksInNewTab.ts b/web/src/hooks/useOpenExternalLinksInNewTab.ts new file mode 100644 index 00000000..3af18613 --- /dev/null +++ b/web/src/hooks/useOpenExternalLinksInNewTab.ts @@ -0,0 +1,99 @@ +import { useCallback, useEffect, useState } from 'react' + +const OPEN_EXTERNAL_LINKS_IN_NEW_TAB_STORAGE_KEY = 'hapi-open-external-links-in-new-tab' +export const DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB = false + +// Same-tab sync: `storage` events only fire in OTHER tabs/windows, but several +// instances can coexist in one window (e.g. one per +// chat message), each with its own useState. Without this, toggling the +// setting in Settings would only affect providers mounted after the change. +const sameTabListeners = new Set<(value: boolean) => void>() + +function isBrowser(): boolean { + return typeof window !== 'undefined' && typeof document !== 'undefined' +} + +function safeGetItem(key: string): string | null { + if (!isBrowser()) { + return null + } + try { + return localStorage.getItem(key) + } catch { + return null + } +} + +function safeSetItem(key: string, value: string): void { + if (!isBrowser()) { + return + } + try { + localStorage.setItem(key, value) + } catch { + // Ignore storage errors + } +} + +function safeRemoveItem(key: string): void { + if (!isBrowser()) { + return + } + try { + localStorage.removeItem(key) + } catch { + // Ignore storage errors + } +} + +function parseOpenExternalLinksInNewTab(raw: string | null): boolean { + if (raw === 'true') { + return true + } + return DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB +} + +export function getInitialOpenExternalLinksInNewTab(): boolean { + return parseOpenExternalLinksInNewTab(safeGetItem(OPEN_EXTERNAL_LINKS_IN_NEW_TAB_STORAGE_KEY)) +} + +export function useOpenExternalLinksInNewTab(): { + openExternalLinksInNewTab: boolean + setOpenExternalLinksInNewTab: (value: boolean) => void +} { + const [openExternalLinksInNewTab, setOpenExternalLinksInNewTabState] = useState(getInitialOpenExternalLinksInNewTab) + + useEffect(() => { + if (!isBrowser()) { + return + } + + const onStorage = (event: StorageEvent) => { + if (event.key !== OPEN_EXTERNAL_LINKS_IN_NEW_TAB_STORAGE_KEY) { + return + } + setOpenExternalLinksInNewTabState(parseOpenExternalLinksInNewTab(event.newValue)) + } + + sameTabListeners.add(setOpenExternalLinksInNewTabState) + window.addEventListener('storage', onStorage) + return () => { + sameTabListeners.delete(setOpenExternalLinksInNewTabState) + window.removeEventListener('storage', onStorage) + } + }, []) + + const setOpenExternalLinksInNewTab = useCallback((value: boolean) => { + for (const listener of sameTabListeners) { + listener(value) + } + + if (value === DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB) { + safeRemoveItem(OPEN_EXTERNAL_LINKS_IN_NEW_TAB_STORAGE_KEY) + } else { + safeSetItem(OPEN_EXTERNAL_LINKS_IN_NEW_TAB_STORAGE_KEY, String(value)) + } + }, []) + + return { openExternalLinksInNewTab, setOpenExternalLinksInNewTab } +} diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index 2d5e8215..647b8005 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -895,6 +895,9 @@ export default { 'settings.display.sessionHeader.createdAt': 'Created time', 'settings.display.sessionHeader.updatedAt': 'Updated time', 'settings.display.sessionHeader.worktree': 'Worktree branch', + 'settings.display.links': 'Links', + 'settings.display.openExternalLinksInNewTab': 'Open external links in a new tab', + 'settings.display.openExternalLinksInNewTab.desc': 'Off (default) keeps today’s behaviour. On opens external links in a separate browser tab instead.', 'session.header.createdAt': 'Created', 'session.header.updatedAt': 'Updated', 'settings.chat.title': 'Chat', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 6dca4945..6886e3ae 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -893,6 +893,9 @@ export default { 'settings.display.sessionHeader.createdAt': '创建时间', 'settings.display.sessionHeader.updatedAt': '更新时间', 'settings.display.sessionHeader.worktree': '工作树分支', + 'settings.display.links': '链接', + 'settings.display.openExternalLinksInNewTab': '在新标签页中打开外部链接', + 'settings.display.openExternalLinksInNewTab.desc': '关闭(默认)保留当前行为。开启后外部链接会在单独的浏览器标签页中打开。', 'session.header.createdAt': '创建', 'session.header.updatedAt': '更新', 'settings.chat.title': '聊天', diff --git a/web/src/routes/settings/display.tsx b/web/src/routes/settings/display.tsx index 10865f1c..92f23f50 100644 --- a/web/src/routes/settings/display.tsx +++ b/web/src/routes/settings/display.tsx @@ -11,6 +11,7 @@ import { MAX_SESSION_PREVIEW_LIMIT, MIN_SESSION_PREVIEW_LIMIT, normalizeSessionP import { useThemeColors, type ThemeColorKeyId } from '@/hooks/useThemeColors' import { useSessionHeaderMetadata, type SessionHeaderMetadataKey } from '@/hooks/useSessionHeaderMetadata' import { useAppBadgePreference } from '@/hooks/useAppBadgePreference' +import { useOpenExternalLinksInNewTab } from '@/hooks/useOpenExternalLinksInNewTab' import { SettingsChoiceGroup, SettingsFieldLabel, SettingsPageContent, SettingsRow, SettingsSection, SettingsSwitch } from '@/components/settings/SettingsPrimitives' function MinusIcon() { @@ -140,6 +141,7 @@ export default function SettingsDisplayPage() { const { showActiveSessionsOnly, setShowActiveSessionsOnly } = useShowActiveSessionsOnly() const { pinInProgressSessions, setPinInProgressSessions } = usePinInProgressSessions() const { appBadgeEnabled, setAppBadgeEnabled } = useAppBadgePreference() + const { openExternalLinksInNewTab, setOpenExternalLinksInNewTab } = useOpenExternalLinksInNewTab() const { preferences: sessionHeaderMetadata, setPreference: setSessionHeaderMetadata } = useSessionHeaderMetadata() const sessionHeaderOptions: ReadonlyArray<{ key: SessionHeaderMetadataKey; labelKey: string }> = [ { key: 'showLabels', labelKey: 'settings.display.sessionHeader.showLabels' }, @@ -197,6 +199,15 @@ export default function SettingsDisplayPage() { /> ))} + + + + ) } From 2f72a8012ebe8632eb6a7ac697264ba970e7edde Mon Sep 17 00:00:00 2001 From: IanMStevenson Date: Sat, 19 Sep 2026 02:47:04 +0100 Subject: [PATCH 13/34] fix(web): save composer draft on visibilitychange, not only on unmount (#1883) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Links in a session open via window.open(_blank). For an installed standalone-display PWA, navigating to a URL outside the manifest's scope is a platform behavior (Chromium/Edge show it as a minimal overlay with a close affordance), not custom code here — but closing it can mean the underlying page had a real top-level teardown, not just an in-app remount. useComposerDraft only ever persisted the draft in its effect's cleanup — reliable for a React-managed unmount (switching sessions), but browsers don't guarantee that cleanup runs to completion before a genuine top-level navigation completes, so the save could simply never happen. Extracts the existing save logic into persistNow() and calls it both from the unmount cleanup (unchanged) and a new visibilitychange listener (when document.visibilityState becomes 'hidden'), mirroring the pattern already used elsewhere in this codebase (useSSE.ts, useAuth.ts, useSyncingState.ts, usePwaUpdate.ts, useVisibilityReporter.ts) for the same class of problem. Fixes #1882 Co-authored-by: Ian Stevenson Co-authored-by: Claude Sonnet 5 --- web/src/hooks/useComposerDraft.test.ts | 38 ++++++++++++++++++++++++++ web/src/hooks/useComposerDraft.ts | 38 ++++++++++++++++++-------- 2 files changed, 65 insertions(+), 11 deletions(-) diff --git a/web/src/hooks/useComposerDraft.test.ts b/web/src/hooks/useComposerDraft.test.ts index 6abc3a25..f081a046 100644 --- a/web/src/hooks/useComposerDraft.test.ts +++ b/web/src/hooks/useComposerDraft.test.ts @@ -151,6 +151,44 @@ describe('useComposerDraft', () => { expect(mockSaveDraftAttachments).toHaveBeenCalledWith('session-1', []) }) + it('saves draft when the page becomes hidden, without unmounting (hapi#1882)', async () => { + mockGetDraft.mockReturnValue('') + const setText = vi.fn() + + const { rerender } = renderHook( + ({ text }) => useComposerDraft('session-1', text, [], true, setText, vi.fn()), + { initialProps: { text: '' } }, + ) + + await act(async () => flushRAF()) + rerender({ text: 'my draft' }) + + // A real top-level page navigation (e.g. an installed PWA's own + // out-of-scope-link overlay) doesn't reliably run React's unmount + // cleanup before the state is gone — this is the fallback save. + Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true }) + document.dispatchEvent(new Event('visibilitychange')) + + expect(mockSaveDraft).toHaveBeenCalledWith('session-1', 'my draft') + expect(mockSaveDraftAttachments).toHaveBeenCalledWith('session-1', []) + + Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true }) + }) + + it('does not save on visibilitychange while the page is becoming visible again', async () => { + mockGetDraft.mockReturnValue('') + const setText = vi.fn() + + renderHook(() => useComposerDraft('session-1', 'my draft', [], true, setText, vi.fn())) + await act(async () => flushRAF()) + mockSaveDraft.mockClear() + + Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true }) + document.dispatchEvent(new Event('visibilitychange')) + + expect(mockSaveDraft).not.toHaveBeenCalled() + }) + it('does not save draft on unmount before rAF has fired', () => { mockGetDraft.mockReturnValue('') const setText = vi.fn() diff --git a/web/src/hooks/useComposerDraft.ts b/web/src/hooks/useComposerDraft.ts index 59c0c721..c40c9f85 100644 --- a/web/src/hooks/useComposerDraft.ts +++ b/web/src/hooks/useComposerDraft.ts @@ -23,7 +23,12 @@ export type ComposerDraftHydration = { * * - On mount: restores saved draft via `setText` (deferred by one animation frame) * - On mount: restores saved attachment files through the composer adapter - * - On unmount: saves current text and attachment files as a draft + * - On unmount, and whenever the page is hidden: saves current text and + * attachment files as a draft. The page-hidden save matters separately from + * unmount — an in-app remount (switching sessions) reliably runs React's + * cleanup, but a real top-level page navigation (e.g. an installed PWA's + * own out-of-scope-link overlay closing) does not guarantee cleanup runs + * before the state is gone (hapi#1882). * - The `draftReady` guard prevents saving before the initial restore completes, * avoiding the case where the runtime's empty initial text overwrites a real draft. * @@ -169,16 +174,10 @@ export function useComposerDraft( }) }) - return () => { - disposed = true - cancelAnimationFrame(frame) - // Cross-session resume already moved this draft; do not recreate the - // obsolete source id after the route change unmounts the composer. - if (composerDraftWasHandedOff(sessionId)) { - draftReadyRef.current = false - attachmentsReadyRef.current = false - return - } + // Cross-session resume already moved this draft; do not recreate the + // obsolete source id after the route change unmounts the composer. + const persistNow = () => { + if (composerDraftWasHandedOff(sessionId)) return if (draftReadyRef.current) { saveDraft(sessionId, composerTextRef.current) } @@ -195,6 +194,23 @@ export function useComposerDraft( console.warn('[composer-draft] inactive persistence failed', error) }) } + } + + // A real top-level page navigation (see the doc comment above) doesn't + // guarantee this effect's own cleanup runs before the state is gone — + // save proactively whenever the page is hidden, not only on unmount. + const handleVisibilityChange = () => { + if (document.visibilityState === 'hidden') { + persistNow() + } + } + document.addEventListener('visibilitychange', handleVisibilityChange) + + return () => { + disposed = true + cancelAnimationFrame(frame) + document.removeEventListener('visibilitychange', handleVisibilityChange) + persistNow() draftReadyRef.current = false attachmentsReadyRef.current = false } From c258a2279e900bbbd02c532325cb824af59e2efa Mon Sep 17 00:00:00 2001 From: SSU-WEI HUANG Date: Mon, 21 Sep 2026 13:56:14 +0800 Subject: [PATCH 14/34] fix(web): synchronize assistant runtime and history loading (#1893) --- bun.lock | 536 +++++++++++------- e2e/history-load.spec.ts | 44 +- web/e2e-fixtures/history-load-fixture.tsx | 29 +- web/package.json | 6 +- .../AssistantChat/AttachmentItem.test.tsx | 3 +- .../AssistantChat/AttachmentItem.tsx | 4 +- .../HappyThread.mobile-scroll.test.tsx | 44 ++ .../components/AssistantChat/HappyThread.tsx | 49 +- .../lib/assistant-runtime.snapshots.test.tsx | 47 ++ 9 files changed, 526 insertions(+), 236 deletions(-) create mode 100644 web/src/lib/assistant-runtime.snapshots.test.tsx diff --git a/bun.lock b/bun.lock index ddfadeab..461b0c07 100644 --- a/bun.lock +++ b/bun.lock @@ -111,9 +111,9 @@ "name": "hapi-web", "version": "0.1.0", "dependencies": { - "@assistant-ui/react": "^0.14.29", - "@assistant-ui/react-markdown": "^0.14.7", - "@assistant-ui/tap": "^0.9.8", + "@assistant-ui/react": "^0.15.21", + "@assistant-ui/react-markdown": "^0.14.16", + "@assistant-ui/tap": "^0.9.18", "@elevenlabs/react": "^0.13.0", "@hapi/protocol": "workspace:*", "@lobehub/icons": "^5.14.0", @@ -329,15 +329,15 @@ "@asamuzakjp/css-color": ["@asamuzakjp/css-color@3.2.0", "", { "dependencies": { "@csstools/css-calc": "^2.1.3", "@csstools/css-color-parser": "^3.0.9", "@csstools/css-parser-algorithms": "^3.0.4", "@csstools/css-tokenizer": "^3.0.3", "lru-cache": "^10.4.3" } }, "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw=="], - "@assistant-ui/core": ["@assistant-ui/core@0.2.23", "", { "dependencies": { "assistant-stream": "^0.3.28", "nanoid": "^6.0.0" }, "peerDependencies": { "@assistant-ui/store": "^0.2.13", "@assistant-ui/tap": "^0.9.0", "@types/react": "*", "assistant-cloud": "^0.1.31", "react": "^18 || ^19", "zustand": "^5.0.11" }, "optionalPeers": ["@types/react", "assistant-cloud", "react", "zustand"] }, "sha512-mD/sWrdH4SF1POxWE0Wn8jrxOSnuGOJfj8j5coDuEtdtoevQT3Z8LzD5mkd2UdyXHIkwFsMb3/vIL1kH8XKyGg=="], + "@assistant-ui/core": ["@assistant-ui/core@0.3.20", "", { "dependencies": { "assistant-stream": "^0.3.44", "nanoid": "^6.0.1" }, "peerDependencies": { "@assistant-ui/store": "^0.3.14", "@assistant-ui/tap": "^0.9.18", "@types/react": "*", "assistant-cloud": "^0.2.1", "react": "^18 || ^19" }, "optionalPeers": ["@types/react", "assistant-cloud", "react"] }, "sha512-gSY7kI5crnbaXFaF2tObBVekXvQCpBz0D8CqzEkDJrKOwe57gn2K52qBr2hL0o36Ssyg0DmiEAi0LjPG5ZSGqQ=="], - "@assistant-ui/react": ["@assistant-ui/react@0.14.29", "", { "dependencies": { "@assistant-ui/core": "^0.2.23", "@assistant-ui/store": "^0.2.22", "@assistant-ui/tap": "^0.9.6", "@radix-ui/primitive": "^1.1.7", "@radix-ui/react-collection": "^1.1.15", "@radix-ui/react-compose-refs": "^1.1.5", "@radix-ui/react-context": "^1.2.2", "@radix-ui/react-primitive": "^2.1.10", "@radix-ui/react-use-callback-ref": "^1.1.4", "@radix-ui/react-use-controllable-state": "^1.2.6", "@radix-ui/react-use-escape-keydown": "^1.1.5", "assistant-cloud": "^0.1.37", "assistant-stream": "^0.3.28", "nanoid": "^6.0.0", "radix-ui": "^1.6.7", "react-textarea-autosize": "^8.5.9", "safe-content-frame": "^0.0.25", "zod": "^4.4.3", "zustand": "^5.0.14" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^18 || ^19", "react-dom": "^18 || ^19" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-QJkrFx1uaf5EiC892EDGSfTPsQ/K6HhXlfcLcuG7Ht8LRM2OKKyKRt79ZB4gzs8iMt81DcyifDXq+MScydTmMg=="], + "@assistant-ui/react": ["@assistant-ui/react@0.15.21", "", { "dependencies": { "@assistant-ui/core": "^0.3.20", "@assistant-ui/store": "^0.3.14", "@assistant-ui/tap": "^0.9.18", "assistant-cloud": "^0.2.2", "assistant-stream": "^0.3.44", "radix-ui": "^1.6.7", "react-textarea-autosize": "^8.5.9", "safe-content-frame": "^0.0.31", "zod": "^4.6.5", "zustand": "^5.0.15" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^18 || ^19", "react-dom": "^18 || ^19" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-5VID3r2YpYFbx6LLfyOSWwRVf4WOJXYsfSN/C67sbCsJsqqBbxeQpn4MB9g73HcyriBkRwqvHY5XXCguyNqP6Q=="], - "@assistant-ui/react-markdown": ["@assistant-ui/react-markdown@0.14.8", "", { "dependencies": { "@radix-ui/react-primitive": "^2.1.10", "@radix-ui/react-use-callback-ref": "^1.1.4", "classnames": "^2.5.1", "react-markdown": "^10.1.0" }, "peerDependencies": { "@assistant-ui/react": "^0.15.0", "@types/react": "*", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-vnJrM7i2fGOMUkg4DSyuorhVmq1VUocRJL3r+1ruaDv8KxHKBfewfEBCvcIt426nmyPaR9CxeoujwKhMI7P3ew=="], + "@assistant-ui/react-markdown": ["@assistant-ui/react-markdown@0.14.16", "", { "dependencies": { "@radix-ui/react-primitive": "^2.1.10", "@radix-ui/react-use-callback-ref": "^1.1.4", "@types/hast": "^3.0.5", "classnames": "^2.5.1", "react-markdown": "^10.1.0" }, "peerDependencies": { "@assistant-ui/react": "^0.15.0", "@types/react": "*", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-RhzvQT7h8ArNcgnOxWAGwRdcOMs7N90ua/PZJiEd5LgK6/9GdGgnTJAoMJa+oneqxFiv6e/jiL2dapHvOrONCA=="], - "@assistant-ui/store": ["@assistant-ui/store@0.2.22", "", { "dependencies": { "use-effect-event": "^2.0.3" }, "peerDependencies": { "@assistant-ui/tap": "^0.9.0", "@types/react": "*", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-RdUFLOFJ3ZwIoOZYrRvps3OAODwnWoUAuNfqbROKrj5qtlQsIJRqxUNdLTjcf4AimhkjCwOaFacGHHm9lE4qBw=="], + "@assistant-ui/store": ["@assistant-ui/store@0.3.14", "", { "peerDependencies": { "@assistant-ui/tap": "^0.9.18", "@types/react": "*", "react": "^18 || ^19" }, "optionalPeers": ["@types/react", "react"] }, "sha512-GqHYBD4TfSBTynyBYs2DDnyskfTVNtKHNaXws6dG5//18fb5PJyTYhXjkOSvDqF+dKX5rlOk9Bbd7G0CfJ+xkQ=="], - "@assistant-ui/tap": ["@assistant-ui/tap@0.9.8", "", { "peerDependencies": { "@types/react": "*", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-pajYWHwvsApAyEtK/TDSr2J2O6/fV1M+ZOmmkKM8apoE6JrC6F8IVKCU1b9rMkB0RidM2lrQxFpN9Ujw3mKEGQ=="], + "@assistant-ui/tap": ["@assistant-ui/tap@0.9.18", "", { "peerDependencies": { "@types/react": "*", "react": "^18 || ^19" }, "optionalPeers": ["@types/react", "react"] }, "sha512-JowBf+JbzQRarun3DWy/4H6XZ7v/1fJ154By00Kn7b30thmlA/bh2lOPa9hPPeYaMcsTiYYYu6yWEM+AFMvdIw=="], "@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], @@ -675,13 +675,13 @@ "@fastify/swagger": ["@fastify/swagger@9.6.1", "", { "dependencies": { "fastify-plugin": "^5.0.0", "json-schema-resolver": "^3.0.0", "openapi-types": "^12.1.3", "rfdc": "^1.3.1", "yaml": "^2.4.2" } }, "sha512-fKlpJqFMWoi4H3EdUkDaMteEYRCfQMEkK0HJJ0eaf4aRlKd8cbq0pVkOfXDXmtvMTXYcnx3E+l023eFDBsA1HA=="], - "@floating-ui/core": ["@floating-ui/core@1.7.3", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w=="], + "@floating-ui/core": ["@floating-ui/core@1.7.5", "", { "dependencies": { "@floating-ui/utils": "^0.2.11" } }, "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ=="], - "@floating-ui/dom": ["@floating-ui/dom@1.7.4", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="], + "@floating-ui/dom": ["@floating-ui/dom@1.7.6", "", { "dependencies": { "@floating-ui/core": "^1.7.5", "@floating-ui/utils": "^0.2.11" } }, "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ=="], "@floating-ui/react": ["@floating-ui/react@0.27.19", "", { "dependencies": { "@floating-ui/react-dom": "^2.1.8", "@floating-ui/utils": "^0.2.11", "tabbable": "^6.0.0" }, "peerDependencies": { "react": ">=17.0.0", "react-dom": ">=17.0.0" } }, "sha512-31B8h5mm8YxotlE7/AU/PhNAl8eWxAmjL/v2QOxroDNkTFLk3Uu82u63N3b6TXa4EGJeeZLVcd/9AlNlVqzeog=="], - "@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.6", "", { "dependencies": { "@floating-ui/dom": "^1.7.4" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw=="], + "@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.8", "", { "dependencies": { "@floating-ui/dom": "^1.7.6" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A=="], "@floating-ui/utils": ["@floating-ui/utils@0.2.10", "", {}, "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ=="], @@ -777,7 +777,7 @@ "@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.12", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA=="], - "@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.15", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA=="], + "@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], "@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.5", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="], @@ -785,23 +785,23 @@ "@radix-ui/react-context-menu": ["@radix-ui/react-context-menu@2.2.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-O8morBEW+HsVG28gYDZPTrT9UUovQUlJue5YO836tiTJhuIWBm/zQHc7j388sHWtdH/xUZurK9olD2+pcqx5ww=="], - "@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw=="], + "@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Ksw4WeROkO4rC9k/onilX/Ao2Cr1ku1unMNH+XSCcP4jSXYu7HDsg9n4ojMjVb22XpYjAQ9qfrFlVbru1vXDUA=="], "@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw=="], - "@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="], + "@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-effect-event": "0.0.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w=="], "@radix-ui/react-dropdown-menu": ["@radix-ui/react-dropdown-menu@2.1.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw=="], - "@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw=="], + "@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.6", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ=="], - "@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="], + "@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.16", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-wmRZ2WWLvmt6KHy2rNPOdPUjwq5xOHY02+m+udwJTn0aNIox/rkskAvJTyTLGhPK6KgrUjlJUJpgmx/+wFiFIQ=="], "@radix-ui/react-form": ["@radix-ui/react-form@0.1.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-label": "2.1.15", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Q4TLEn2A7TAypxwmd6R9EwrlXDvkfYSDMrq9/887AXAGh+G1rH+kYJKSTv+Si9Y0JPKTwKYv6PviAJosysNimA=="], "@radix-ui/react-hover-card": ["@radix-ui/react-hover-card@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-qgTkjNT1CfKMoP0rcasmlH2r1DAiYicWsDsufxl940sT2wHNEWWv6FMWIQXWhVdmC1d/HYfbhQx60KYyAtKxjg=="], - "@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + "@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], "@radix-ui/react-label": ["@radix-ui/react-label@2.1.8", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-FmXs37I6hSBVDlO4y764TNz1rLgKwjJMQ0EGte6F3Cb3f4bIuHB/iLa/8I9VKkmOy+gNHq8rql3j686ACVV21A=="], @@ -815,13 +815,13 @@ "@radix-ui/react-password-toggle-field": ["@radix-ui/react-password-toggle-field@0.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-is-hydrated": "0.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-4gvFnmDXu3dgj21CqsufzIameRvlRd4SBqaWhcrlrNhRo0Y5i/49AmRJYe1fdAM3G2VNBbmin4b0D6cdQocwgw=="], - "@radix-ui/react-popover": ["@radix-ui/react-popover@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA=="], + "@radix-ui/react-popover": ["@radix-ui/react-popover@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mw58MrBlyHWFisTOYignD0vf/3gdcgAR+9of1s9G/38CbFiUwH1nCDkc0AUM9IrXFgN5Ue8n45j9WCgyM1sbiQ=="], - "@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="], + "@radix-ui/react-popper": ["@radix-ui/react-popper@1.3.7", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-rect": "1.1.4", "@radix-ui/react-use-size": "1.1.4", "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UsJrrd7w4wuKKTdvd/DNERVlwSlUcyXzjhyDwBk+3aPOsCjOY6ZSbxuw8E6lZTjjfP8Cpd0J8VVkrYUWyGYXyg=="], - "@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="], + "@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.17", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ=="], - "@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.10", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw=="], "@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.10", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="], @@ -839,7 +839,7 @@ "@radix-ui/react-slider": ["@radix-ui/react-slider@1.3.6", "", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw=="], - "@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="], + "@radix-ui/react-slot": ["@radix-ui/react-slot@1.3.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q=="], "@radix-ui/react-switch": ["@radix-ui/react-switch@1.2.6", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ=="], @@ -865,17 +865,17 @@ "@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.0", "", { "dependencies": { "use-sync-external-store": "^1.5.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-U+UORVEq+cTnRIaostJv9AGdV3G6Y+zbVd+12e18jQ5A3c0xL03IhnHuiU4UV69wolOQp5GfR58NW/EgdQhwOA=="], - "@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], "@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ=="], - "@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.1", "", { "dependencies": { "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w=="], + "@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.4", "", { "dependencies": { "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ=="], "@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ=="], "@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.3", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug=="], - "@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="], + "@radix-ui/rect": ["@radix-ui/rect@1.1.3", "", {}, "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw=="], "@rc-component/async-validator": ["@rc-component/async-validator@5.1.0", "", { "dependencies": { "@babel/runtime": "^7.24.4" } }, "sha512-n4HcR5siNUXRX23nDizbZBQPO0ZM/5oTtmKZ6/eqL0L2bo747cklFdZGRN2f+c9qWGICwDzrhW0H7tE9PptdcA=="], @@ -1227,6 +1227,8 @@ "@types/js-cookie": ["@types/js-cookie@3.0.6", "", {}, "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ=="], + "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], + "@types/katex": ["@types/katex@0.16.7", "", {}, "sha512-HMwFiRujE5PjrgwHQ25+bsLJgowjGjm5Z8FVSf0N6PwgJrwxH0QxzHYDcKsTfV3wva0vzrpqMTJS2jXPr5BMEQ=="], "@types/linkify-it": ["@types/linkify-it@5.0.0", "", {}, "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q=="], @@ -1391,9 +1393,9 @@ "assign-symbols": ["assign-symbols@1.0.0", "", {}, "sha512-Q+JC7Whu8HhmTdBph/Tq59IoRtoy6KAm5zzPv00WdujX82lbAL8K7WVjne7vdCsAmbF4AYaDOPyO3k0kl8qIrw=="], - "assistant-cloud": ["assistant-cloud@0.1.37", "", { "dependencies": { "assistant-stream": "^0.3.28" } }, "sha512-cofr0dM/mRyHZKwIDhMxX8xvZNWd078PM77eBdxbuuzxTa6aXYm5E+rq6q92RZF10CAMn+Ruir3vhjsVg7kZ0w=="], + "assistant-cloud": ["assistant-cloud@0.2.2", "", { "dependencies": { "assistant-stream": "^0.3.44" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-trace-otlp-http": ">=0.200.0", "@opentelemetry/sdk-trace-base": "^2.1.0", "ai": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["@opentelemetry/api", "@opentelemetry/exporter-trace-otlp-http", "@opentelemetry/sdk-trace-base", "ai"] }, "sha512-rScC4VNkUMPnRogMM92mkS87f0qf3Vtc+V7gfaliA0biD64slfvvsmbges3CupoVzJ8Pc4iMP1YhIa+oIjzpzg=="], - "assistant-stream": ["assistant-stream@0.3.31", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "nanoid": "^6.0.0", "secure-json-parse": "^4.1.0" }, "peerDependencies": { "ioredis": "^5.10.1", "redis": "^5.12.1" }, "optionalPeers": ["ioredis", "redis"] }, "sha512-3qkTkttgTLe1jNMHIIiYk7dC4VoJk9MyDA7aNYF08g1rme1DaZAyecUYH/0eywI6naRwu8EAICw9WTn0sahyPw=="], + "assistant-stream": ["assistant-stream@0.3.44", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/json-schema": "^7.0.15", "nanoid": "^6.0.1", "secure-json-parse": "^4.1.0" }, "peerDependencies": { "ioredis": "^5.10.1 || ^6.0.0", "redis": "^5.12.1" }, "optionalPeers": ["ioredis", "redis"] }, "sha512-418FRutG6g6WUd8EckGG+ZVOn/rmgop36oyzAMk1bRqktZOlY2RdtBl0yoUpDM/IDPWVNe7baYtSKN3UvjQzoA=="], "astring": ["astring@1.9.0", "", { "bin": { "astring": "bin/astring" } }, "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg=="], @@ -2751,7 +2753,7 @@ "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], - "safe-content-frame": ["safe-content-frame@0.0.25", "", {}, "sha512-Oztqn3kWTbNzMlWSr6SQiUBPtLJLbjzaJUYtO7PN5SfC5PxtOrBnEfnVy0IMT7do1SGqUkd/o1KTSXMRS+FBMw=="], + "safe-content-frame": ["safe-content-frame@0.0.31", "", {}, "sha512-q5oK9CnNBlsCaYSpMjTkveO9BiQU25PHeMykRyh59hlSkr0g0SSeL7P+dtTljKwNt0+m1qWD8982xUcN5jmPPQ=="], "safe-push-apply": ["safe-push-apply@1.0.0", "", { "dependencies": { "es-errors": "^1.3.0", "isarray": "^2.0.5" } }, "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA=="], @@ -3049,8 +3051,6 @@ "use-composed-ref": ["use-composed-ref@1.4.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-djviaxuOOh7wkj0paeO1Q/4wMZ8Zrnag5H6yBvzN7AKKe8beOaED9SF5/ByLqsku8NP4zQqsvM2u3ew/tJK8/w=="], - "use-effect-event": ["use-effect-event@2.0.3", "", { "peerDependencies": { "react": "^18.3 || ^19.0.0-0" } }, "sha512-fz1en+z3fYXCXx3nMB8hXDMuygBltifNKZq29zDx+xNJ+1vEs6oJlYd9sK31vxJ0YI534VUsHEBY0k2BATsmBQ=="], - "use-isomorphic-layout-effect": ["use-isomorphic-layout-effect@1.2.1", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-tpZZ+EX0gaghDAiFR37hj5MgY6ZN55kLiPkJsKxBMZ6GZdOSPJXiOzPM984oPYZ5AnehYx5WQp1+ME8I/P/pRA=="], "use-latest": ["use-latest@1.3.0", "", { "dependencies": { "use-isomorphic-layout-effect": "^1.1.1" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-mhg3xdm9NaM8q+gLT8KryJPnRFOz1/5XPBhmDEVZK1webPzDjrPk7f/mbpeLqTgB9msytYWANxgALOCJKnLvcQ=="], @@ -3205,19 +3205,19 @@ "yoga-layout": ["yoga-layout@3.2.1", "", {}, "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ=="], - "zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], + "zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], "zod-to-json-schema": ["zod-to-json-schema@3.25.0", "", { "peerDependencies": { "zod": "^3.25 || ^4" } }, "sha512-HvWtU2UG41LALjajJrML6uQejQhNJx+JBO9IflpSja4R03iNWfKXrj6W2h7ljuLyc1nKS+9yDyL/9tD1U/yBnQ=="], - "zustand": ["zustand@5.0.14", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g=="], + "zustand": ["zustand@5.0.15", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A=="], "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], "@asamuzakjp/css-color/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], - "@assistant-ui/core/nanoid": ["nanoid@6.0.0", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-mkUH+rPkwU2qPadJ0oJZOjeZ5Mxn8Q1UhevwkTRWNuUZzyia3h4rhzK39hxaHTk0o2OxB8W2SQ6A8k23ZDi1pQ=="], + "@assistant-ui/core/nanoid": ["nanoid@6.0.1", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw=="], - "@assistant-ui/react/nanoid": ["nanoid@6.0.0", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-mkUH+rPkwU2qPadJ0oJZOjeZ5Mxn8Q1UhevwkTRWNuUZzyia3h4rhzK39hxaHTk0o2OxB8W2SQ6A8k23ZDi1pQ=="], + "@assistant-ui/react-markdown/@types/hast": ["@types/hast@3.0.5", "", { "dependencies": { "@types/unist": "*" } }, "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g=="], "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -3229,6 +3229,8 @@ "@babel/preset-env/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@base-ui/react/@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.6", "", { "dependencies": { "@floating-ui/dom": "^1.7.4" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw=="], + "@base-ui/utils/@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="], "@builder.io/jsx-loc-internals/estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], @@ -3251,7 +3253,9 @@ "@emotion/serialize/@emotion/unitless": ["@emotion/unitless@0.10.0", "", {}, "sha512-dFoMUuQA20zvtVTuxZww6OHoJYgrzfKM1t52mVySDJnMSEa08ruEvdYQbhvyu6soU+NeLVd3yKfTfT0NeV6qGg=="], - "@floating-ui/react/@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.8", "", { "dependencies": { "@floating-ui/dom": "^1.7.6" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A=="], + "@floating-ui/core/@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="], + + "@floating-ui/dom/@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="], "@floating-ui/react/@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="], @@ -3297,12 +3301,12 @@ "@radix-ui/react-accordion/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - "@radix-ui/react-accordion/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], - "@radix-ui/react-accordion/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-accordion/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-accordion/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + "@radix-ui/react-accordion/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-accordion/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], @@ -3313,6 +3317,8 @@ "@radix-ui/react-alert-dialog/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw=="], + "@radix-ui/react-alert-dialog/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-alert-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], @@ -3325,12 +3331,16 @@ "@radix-ui/react-avatar/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], + "@radix-ui/react-avatar/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-checkbox/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], "@radix-ui/react-checkbox/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-checkbox/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-checkbox/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-checkbox/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-checkbox/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], @@ -3341,11 +3351,23 @@ "@radix-ui/react-collapsible/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-collapsible/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + + "@radix-ui/react-collapsible/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-collapsible/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-collapsible/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], - "@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.3.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q=="], + "@radix-ui/react-collapsible/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-collection/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + + "@radix-ui/react-collection/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + + "@radix-ui/react-collection/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], + + "@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-context-menu/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], @@ -3357,46 +3379,18 @@ "@radix-ui/react-context-menu/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], - "@radix-ui/react-dialog/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - - "@radix-ui/react-dialog/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], - - "@radix-ui/react-dialog/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], - - "@radix-ui/react-dialog/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], - - "@radix-ui/react-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], - - "@radix-ui/react-dialog/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], - - "@radix-ui/react-dismissable-layer/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - - "@radix-ui/react-dismissable-layer/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], - - "@radix-ui/react-dismissable-layer/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], - - "@radix-ui/react-dismissable-layer/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], - - "@radix-ui/react-dismissable-layer/@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="], - "@radix-ui/react-dropdown-menu/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], "@radix-ui/react-dropdown-menu/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-dropdown-menu/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-dropdown-menu/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + "@radix-ui/react-dropdown-menu/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-dropdown-menu/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], - "@radix-ui/react-focus-scope/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], - - "@radix-ui/react-focus-scope/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], - - "@radix-ui/react-focus-scope/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], - - "@radix-ui/react-form/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - "@radix-ui/react-form/@radix-ui/react-label": ["@radix-ui/react-label@2.1.15", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-o/rdYEwZTTo5tjknnPeyQFU45kUC4i/XyeDPP+HGyi6XqpOP6Zf5Ya5vh/Yfe9Id5JiuWnnAx2XqIeD3UYZt0g=="], "@radix-ui/react-hover-card/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], @@ -3405,6 +3399,14 @@ "@radix-ui/react-hover-card/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-hover-card/@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="], + + "@radix-ui/react-hover-card/@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="], + + "@radix-ui/react-hover-card/@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="], + + "@radix-ui/react-hover-card/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-hover-card/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-hover-card/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], @@ -3413,12 +3415,24 @@ "@radix-ui/react-menu/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - "@radix-ui/react-menu/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], - "@radix-ui/react-menu/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-menu/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-menu/@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="], + + "@radix-ui/react-menu/@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw=="], + + "@radix-ui/react-menu/@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="], + + "@radix-ui/react-menu/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + + "@radix-ui/react-menu/@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="], + + "@radix-ui/react-menu/@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="], + + "@radix-ui/react-menu/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-menu/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-menu/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], @@ -3427,71 +3441,49 @@ "@radix-ui/react-menubar/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - "@radix-ui/react-menubar/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], - "@radix-ui/react-menubar/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-menubar/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-menubar/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + "@radix-ui/react-menubar/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-menubar/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], "@radix-ui/react-navigation-menu/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - "@radix-ui/react-navigation-menu/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], - "@radix-ui/react-navigation-menu/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-navigation-menu/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-navigation-menu/@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="], + + "@radix-ui/react-navigation-menu/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + + "@radix-ui/react-navigation-menu/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-navigation-menu/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-navigation-menu/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], "@radix-ui/react-navigation-menu/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], + "@radix-ui/react-navigation-menu/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-one-time-password-field/@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="], + "@radix-ui/react-one-time-password-field/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.15", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA=="], + "@radix-ui/react-one-time-password-field/@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-5pzg4FGQNpExhnhT2zlrP1wZFaYCd1K0nYWoFAdcYoYK868IEigqMX3B3f8yIoRlAhAeDWciLI6ZdCKHF9P4Vg=="], "@radix-ui/react-one-time-password-field/@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-V9jI6hDjT7l3jsCQD9bLNvDLM3tH/gdbOTp7Tefp3hbbgCGQoK7tUvrWiRlcoBHIZ809ElXwNQwVo0B98LuTXQ=="], "@radix-ui/react-one-time-password-field/@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw=="], - "@radix-ui/react-one-time-password-field/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], - - "@radix-ui/react-password-toggle-field/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - "@radix-ui/react-password-toggle-field/@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw=="], - "@radix-ui/react-popover/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - - "@radix-ui/react-popover/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], - - "@radix-ui/react-popover/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], - - "@radix-ui/react-popover/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], - - "@radix-ui/react-popover/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], - - "@radix-ui/react-popover/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], - - "@radix-ui/react-popper/@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="], - - "@radix-ui/react-popper/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], - - "@radix-ui/react-popper/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], - - "@radix-ui/react-popper/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], - - "@radix-ui/react-popper/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], - - "@radix-ui/react-portal/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], - - "@radix-ui/react-presence/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], - - "@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.3.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q=="], + "@radix-ui/react-popper/@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-D3anSY15EJoxrihpsXI6SMrmmonnQtR2ni7arO+Lfdg3O95b9hNXxONk8jA5C8ANdF/h5HMAxejgs8PWJ6rlhw=="], "@radix-ui/react-progress/@radix-ui/react-context": ["@radix-ui/react-context@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ieIFACdMpYfMEjF0rEf5KLvfVyIkOz6PDGyNnP+u+4xQ6jny3VCgA4OgXOwNx2aUkxn8zx9fiVcM8CfFYv9Lxw=="], @@ -3503,18 +3495,20 @@ "@radix-ui/react-radio-group/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-radio-group/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-radio-group/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-radio-group/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], "@radix-ui/react-roving-focus/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - "@radix-ui/react-roving-focus/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], - "@radix-ui/react-roving-focus/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-roving-focus/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-roving-focus/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + "@radix-ui/react-roving-focus/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-roving-focus/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], @@ -3527,18 +3521,32 @@ "@radix-ui/react-scroll-area/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-scroll-area/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-scroll-area/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-scroll-area/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], - "@radix-ui/react-select/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], + "@radix-ui/react-scroll-area/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], - "@radix-ui/react-select/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], + "@radix-ui/react-select/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], "@radix-ui/react-select/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-select/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-select/@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="], + + "@radix-ui/react-select/@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw=="], + + "@radix-ui/react-select/@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="], + + "@radix-ui/react-select/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + + "@radix-ui/react-select/@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="], + + "@radix-ui/react-select/@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="], + "@radix-ui/react-select/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-select/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], @@ -3547,12 +3555,12 @@ "@radix-ui/react-select/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], + "@radix-ui/react-select/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-separator/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="], "@radix-ui/react-slider/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], - "@radix-ui/react-slider/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], - "@radix-ui/react-slider/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-slider/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], @@ -3561,7 +3569,7 @@ "@radix-ui/react-slider/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], - "@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + "@radix-ui/react-slider/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], "@radix-ui/react-switch/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], @@ -3577,17 +3585,15 @@ "@radix-ui/react-tabs/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-tabs/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + + "@radix-ui/react-tabs/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-tabs/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-tabs/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], - "@radix-ui/react-toast/@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-effect-event": "0.0.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w=="], - - "@radix-ui/react-toast/@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.17", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ=="], - - "@radix-ui/react-toast/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.10", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw=="], - - "@radix-ui/react-toast/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], + "@radix-ui/react-toast/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.15", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA=="], "@radix-ui/react-toast/@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.11", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-NFS86RYYZb4/exihaESBGOpMJFz8MGLAfu3mOBSGByVnVPC9JPASfYubxd/8KbkQK0sYAv8lVQDEQukDX/qXvQ=="], @@ -3619,15 +3625,23 @@ "@radix-ui/react-tooltip/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="], + "@radix-ui/react-tooltip/@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="], + + "@radix-ui/react-tooltip/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + + "@radix-ui/react-tooltip/@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="], + + "@radix-ui/react-tooltip/@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="], + + "@radix-ui/react-tooltip/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@radix-ui/react-tooltip/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], "@radix-ui/react-tooltip/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-tooltip/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], - "@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], - - "@radix-ui/react-use-effect-event/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], + "@radix-ui/react-use-size/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], "@radix-ui/react-visually-hidden/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], @@ -3703,7 +3717,7 @@ "accepts/mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], - "assistant-stream/nanoid": ["nanoid@6.0.0", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-mkUH+rPkwU2qPadJ0oJZOjeZ5Mxn8Q1UhevwkTRWNuUZzyia3h4rhzK39hxaHTk0o2OxB8W2SQ6A8k23ZDi1pQ=="], + "assistant-stream/nanoid": ["nanoid@6.0.1", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw=="], "babel-plugin-polyfill-corejs2/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -3721,6 +3735,8 @@ "cmdk/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + "cmdk/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + "cmdk/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="], "cosmiconfig/yaml": ["yaml@1.10.3", "", {}, "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA=="], @@ -3765,6 +3781,8 @@ "get-intrinsic/hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="], + "hapi-web/@playwright/test": ["@playwright/test@1.60.0", "", { "dependencies": { "playwright": "1.60.0" }, "bin": { "playwright": "cli.js" } }, "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag=="], + "hapi-website/@types/node": ["@types/node@24.10.4", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg=="], "hapi-website/typescript": ["typescript@5.6.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw=="], @@ -3785,6 +3803,8 @@ "jsdom/https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + "leva/@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="], + "leva/zustand": ["zustand@3.7.2", "", { "peerDependencies": { "react": ">=16.8" }, "optionalPeers": ["react"] }, "sha512-PIJDIZKtokhof+9+60cpockVOq05sJzHCriyvaLBmEJixseQ1a5Kdov6fWZfWOu5SK9c+FhH1jU0tntLxRJYMA=="], "light-my-request/cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], @@ -3829,20 +3849,14 @@ "radix-ui/@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.20", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mcGesGplBnzN2sbvJETzpCNfSMyPnb29q1GRLU+Ib7bJrpIG2ywmRoh2V5VbA2uNvKikKUlVbAPks7JDjz4A8Q=="], - "radix-ui/@radix-ui/react-context-menu": ["@radix-ui/react-context-menu@2.3.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-CtXP35dxaB5T3zXSd+E3uHe/QpXcpYnZmxp6OaIbfthtfW4wyb77M23BG+bwIJDtsMwEP/YssdsmNyZu7jhWew=="], + "radix-ui/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.15", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA=="], - "radix-ui/@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Ksw4WeROkO4rC9k/onilX/Ao2Cr1ku1unMNH+XSCcP4jSXYu7HDsg9n4ojMjVb22XpYjAQ9qfrFlVbru1vXDUA=="], + "radix-ui/@radix-ui/react-context-menu": ["@radix-ui/react-context-menu@2.3.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-CtXP35dxaB5T3zXSd+E3uHe/QpXcpYnZmxp6OaIbfthtfW4wyb77M23BG+bwIJDtsMwEP/YssdsmNyZu7jhWew=="], "radix-ui/@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-5pzg4FGQNpExhnhT2zlrP1wZFaYCd1K0nYWoFAdcYoYK868IEigqMX3B3f8yIoRlAhAeDWciLI6ZdCKHF9P4Vg=="], - "radix-ui/@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-effect-event": "0.0.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w=="], - "radix-ui/@radix-ui/react-dropdown-menu": ["@radix-ui/react-dropdown-menu@2.1.24", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-geq8l2rJkxvkXsT9RMgtUE3P8pITFpTsvYpbySi1IH4fZEABD/Gp85myayFgxk0ktljGMJnCbeFkyTusvSvv7g=="], - "radix-ui/@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.6", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ=="], - - "radix-ui/@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.16", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-wmRZ2WWLvmt6KHy2rNPOdPUjwq5xOHY02+m+udwJTn0aNIox/rkskAvJTyTLGhPK6KgrUjlJUJpgmx/+wFiFIQ=="], - "radix-ui/@radix-ui/react-hover-card": ["@radix-ui/react-hover-card@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-H8qONfZd3ltrU3+jHCIgITbWo6e1iTKvP9DHdrvYbX48ooRM5FjEDTn16AMwdfuOGkWdZEhpl3PLL/Wk/AnHDQ=="], "radix-ui/@radix-ui/react-label": ["@radix-ui/react-label@2.1.15", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-o/rdYEwZTTo5tjknnPeyQFU45kUC4i/XyeDPP+HGyi6XqpOP6Zf5Ya5vh/Yfe9Id5JiuWnnAx2XqIeD3UYZt0g=="], @@ -3853,14 +3867,6 @@ "radix-ui/@radix-ui/react-navigation-menu": ["@radix-ui/react-navigation-menu@1.2.22", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ou7iLEJ+yrhQndkkA4U21XIdS/CS45F4iXIkTZcb6/Ne9EMsOuDudVmCwmDnfFZZ+y1FZqXRNSIgBy+YMvZVZg=="], - "radix-ui/@radix-ui/react-popover": ["@radix-ui/react-popover@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mw58MrBlyHWFisTOYignD0vf/3gdcgAR+9of1s9G/38CbFiUwH1nCDkc0AUM9IrXFgN5Ue8n45j9WCgyM1sbiQ=="], - - "radix-ui/@radix-ui/react-popper": ["@radix-ui/react-popper@1.3.7", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-rect": "1.1.4", "@radix-ui/react-use-size": "1.1.4", "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UsJrrd7w4wuKKTdvd/DNERVlwSlUcyXzjhyDwBk+3aPOsCjOY6ZSbxuw8E6lZTjjfP8Cpd0J8VVkrYUWyGYXyg=="], - - "radix-ui/@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.17", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ=="], - - "radix-ui/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.10", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw=="], - "radix-ui/@radix-ui/react-progress": ["@radix-ui/react-progress@1.1.16", "", { "dependencies": { "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-5XnomAsoZZCY+KNTxbIghpGqPruZvKFNlvcAljVAOdDRDsH4/OZQxhtwo5wdtoDM5R6MhJBb2sPnDuRFep3lzg=="], "radix-ui/@radix-ui/react-radio-group": ["@radix-ui/react-radio-group@1.4.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-cgYFEkntCxppHZgtSZ+7vh0wbZQ+IC7PPMw8DSnRG27B6kDd32/Zw0OJt7dGDigCoprMuWHjg2PvUn3PYvPFoQ=="], @@ -3875,8 +3881,6 @@ "radix-ui/@radix-ui/react-slider": ["@radix-ui/react-slider@1.4.7", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mTSLf1GC/C0moWjTbvCM6Qn/gBjvlFt1azuWF2v7MN5C3Zq2U2J2lN3ZEYkpujuOU5Ro7A28wkviSxaKnG0BYg=="], - "radix-ui/@radix-ui/react-slot": ["@radix-ui/react-slot@1.3.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q=="], - "radix-ui/@radix-ui/react-switch": ["@radix-ui/react-switch@1.3.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-48tB/4dn2UVLBCYhTu9AuR63IHl73l/qLbLgxd86noTUor4/K4LFDAcYjK+isP5313qxaFpjPVogE7+Y0/V3Kw=="], "radix-ui/@radix-ui/react-tabs": ["@radix-ui/react-tabs@1.1.21", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UKxJlZid7FVtsk/WTxj4i4uSEgj2Au+KBbS7SQyTlzMhhn+86Cz3tISZdTa87bfEfcuvZezf2ZsxD4xuEKtkog=="], @@ -3889,8 +3893,6 @@ "radix-ui/@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw=="], - "radix-ui/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], - "radix-ui/@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-D3anSY15EJoxrihpsXI6SMrmmonnQtR2ni7arO+Lfdg3O95b9hNXxONk8jA5C8ANdF/h5HMAxejgs8PWJ6rlhw=="], "radix-ui/@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.11", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-NFS86RYYZb4/exihaESBGOpMJFz8MGLAfu3mOBSGByVnVPC9JPASfYubxd/8KbkQK0sYAv8lVQDEQukDX/qXvQ=="], @@ -3987,12 +3989,12 @@ "yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + "@base-ui/react/@floating-ui/react-dom/@floating-ui/dom": ["@floating-ui/dom@1.7.4", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="], + "@builder.io/vite-plugin-jsx-loc/vite/esbuild": ["esbuild@0.21.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.21.5", "@esbuild/android-arm": "0.21.5", "@esbuild/android-arm64": "0.21.5", "@esbuild/android-x64": "0.21.5", "@esbuild/darwin-arm64": "0.21.5", "@esbuild/darwin-x64": "0.21.5", "@esbuild/freebsd-arm64": "0.21.5", "@esbuild/freebsd-x64": "0.21.5", "@esbuild/linux-arm": "0.21.5", "@esbuild/linux-arm64": "0.21.5", "@esbuild/linux-ia32": "0.21.5", "@esbuild/linux-loong64": "0.21.5", "@esbuild/linux-mips64el": "0.21.5", "@esbuild/linux-ppc64": "0.21.5", "@esbuild/linux-riscv64": "0.21.5", "@esbuild/linux-s390x": "0.21.5", "@esbuild/linux-x64": "0.21.5", "@esbuild/netbsd-x64": "0.21.5", "@esbuild/openbsd-x64": "0.21.5", "@esbuild/sunos-x64": "0.21.5", "@esbuild/win32-arm64": "0.21.5", "@esbuild/win32-ia32": "0.21.5", "@esbuild/win32-x64": "0.21.5" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw=="], "@builder.io/vite-plugin-jsx-loc/vite/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - "@floating-ui/react/@floating-ui/react-dom/@floating-ui/dom": ["@floating-ui/dom@1.7.6", "", { "dependencies": { "@floating-ui/core": "^1.7.5", "@floating-ui/utils": "^0.2.11" } }, "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ=="], - "@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], "@lobehub/ui/@shikijs/core/@shikijs/types": ["@shikijs/types@4.0.2", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-qzbeRooUTPnLE+sHD/Z8DStmaDgnbbc/pMrU203950aRqjX/6AFHeDYT+j00y2lPdz0ywJKx7o/7qnqTivtlXg=="], @@ -4035,16 +4037,40 @@ "@pierre/diffs/@shikijs/transformers/@shikijs/types": ["@shikijs/types@3.23.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="], - "@radix-ui/react-accordion/@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-accordion/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], "@radix-ui/react-accordion/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-accordion/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + "@radix-ui/react-accordion/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="], + + "@radix-ui/react-aspect-ratio/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="], + + "@radix-ui/react-avatar/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="], + + "@radix-ui/react-checkbox/@radix-ui/react-presence/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-checkbox/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-checkbox/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + "@radix-ui/react-checkbox/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-collapsible/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-collapsible/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], @@ -4053,59 +4079,109 @@ "@radix-ui/react-context-menu/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - "@radix-ui/react-dialog/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + "@radix-ui/react-context-menu/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], - "@radix-ui/react-dismissable-layer/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-dropdown-menu/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], "@radix-ui/react-dropdown-menu/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-dropdown-menu/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - "@radix-ui/react-focus-scope/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-dropdown-menu/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], - "@radix-ui/react-form/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], + "@radix-ui/react-hover-card/@radix-ui/react-dismissable-layer/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], + + "@radix-ui/react-hover-card/@radix-ui/react-dismissable-layer/@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="], + + "@radix-ui/react-hover-card/@radix-ui/react-popper/@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.6", "", { "dependencies": { "@floating-ui/dom": "^1.7.4" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw=="], + + "@radix-ui/react-hover-card/@radix-ui/react-popper/@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="], + + "@radix-ui/react-hover-card/@radix-ui/react-popper/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], + + "@radix-ui/react-hover-card/@radix-ui/react-popper/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-hover-card/@radix-ui/react-popper/@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.1", "", { "dependencies": { "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w=="], + + "@radix-ui/react-hover-card/@radix-ui/react-popper/@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="], + + "@radix-ui/react-hover-card/@radix-ui/react-portal/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-hover-card/@radix-ui/react-presence/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], "@radix-ui/react-hover-card/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-hover-card/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - "@radix-ui/react-menubar/@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-hover-card/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-label/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="], + + "@radix-ui/react-menu/@radix-ui/react-dismissable-layer/@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="], + + "@radix-ui/react-menu/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-menu/@radix-ui/react-popper/@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.6", "", { "dependencies": { "@floating-ui/dom": "^1.7.4" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw=="], + + "@radix-ui/react-menu/@radix-ui/react-popper/@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="], + + "@radix-ui/react-menu/@radix-ui/react-popper/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-menu/@radix-ui/react-popper/@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.1", "", { "dependencies": { "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w=="], + + "@radix-ui/react-menu/@radix-ui/react-popper/@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="], + + "@radix-ui/react-menu/@radix-ui/react-portal/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-menu/@radix-ui/react-presence/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-menubar/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], "@radix-ui/react-menubar/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-menubar/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - "@radix-ui/react-navigation-menu/@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-menubar/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-navigation-menu/@radix-ui/react-dismissable-layer/@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="], "@radix-ui/react-navigation-menu/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-navigation-menu/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - "@radix-ui/react-one-time-password-field/@radix-ui/react-roving-focus/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], + "@radix-ui/react-progress/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="], - "@radix-ui/react-password-toggle-field/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], - - "@radix-ui/react-popover/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - - "@radix-ui/react-popper/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], - - "@radix-ui/react-portal/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-radio-group/@radix-ui/react-presence/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], "@radix-ui/react-radio-group/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-radio-group/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - "@radix-ui/react-roving-focus/@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-radio-group/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-roving-focus/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], "@radix-ui/react-roving-focus/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-roving-focus/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + "@radix-ui/react-roving-focus/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-scroll-area/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-select/@radix-ui/react-dismissable-layer/@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="], + + "@radix-ui/react-select/@radix-ui/react-popper/@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.6", "", { "dependencies": { "@floating-ui/dom": "^1.7.4" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw=="], + + "@radix-ui/react-select/@radix-ui/react-popper/@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="], + + "@radix-ui/react-select/@radix-ui/react-popper/@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.1", "", { "dependencies": { "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w=="], + + "@radix-ui/react-select/@radix-ui/react-popper/@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="], + "@radix-ui/react-select/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - "@radix-ui/react-slider/@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], + "@radix-ui/react-separator/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="], "@radix-ui/react-slider/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], @@ -4115,28 +4191,64 @@ "@radix-ui/react-switch/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + "@radix-ui/react-switch/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-tabs/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-tabs/@radix-ui/react-presence/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + + "@radix-ui/react-tabs/@radix-ui/react-presence/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-tabs/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-tabs/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + "@radix-ui/react-tabs/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-toggle-group/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-toggle-group/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + "@radix-ui/react-toggle-group/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@radix-ui/react-toggle/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], - "@radix-ui/react-toolbar/@radix-ui/react-roving-focus/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], + "@radix-ui/react-toggle/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-toolbar/@radix-ui/react-roving-focus/@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.15", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA=="], "@radix-ui/react-toolbar/@radix-ui/react-roving-focus/@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw=="], - "@radix-ui/react-toolbar/@radix-ui/react-roving-focus/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], - "@radix-ui/react-toolbar/@radix-ui/react-toggle-group/@radix-ui/react-toggle": ["@radix-ui/react-toggle@1.1.18", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-7lonPlKfSacd20GlOBx2ltuVKz9oqWYZz+oMQyOltw6t1y2nyftj2ZmwwUHYn49kqfDWcp8dNZm5NgV+5Z+mug=="], + "@radix-ui/react-tooltip/@radix-ui/react-dismissable-layer/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], + + "@radix-ui/react-tooltip/@radix-ui/react-dismissable-layer/@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="], + + "@radix-ui/react-tooltip/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-tooltip/@radix-ui/react-popper/@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.6", "", { "dependencies": { "@floating-ui/dom": "^1.7.4" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw=="], + + "@radix-ui/react-tooltip/@radix-ui/react-popper/@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="], + + "@radix-ui/react-tooltip/@radix-ui/react-popper/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], + + "@radix-ui/react-tooltip/@radix-ui/react-popper/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-tooltip/@radix-ui/react-popper/@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.1", "", { "dependencies": { "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w=="], + + "@radix-ui/react-tooltip/@radix-ui/react-popper/@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="], + + "@radix-ui/react-tooltip/@radix-ui/react-portal/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-tooltip/@radix-ui/react-presence/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-tooltip/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + "@radix-ui/react-tooltip/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "@radix-ui/react-visually-hidden/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "@rollup/plugin-babel/rollup/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -4165,6 +4277,10 @@ "cliui/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + "cmdk/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "cmdk/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="], + "cytoscape-fcose/cose-base/layout-base": ["layout-base@2.0.1", "", {}, "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg=="], "d3-sankey/d3-array/internmap": ["internmap@1.0.1", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="], @@ -4177,6 +4293,8 @@ "form-data/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], + "hapi-web/@playwright/test/playwright": ["playwright@1.60.0", "", { "dependencies": { "playwright-core": "1.60.0" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA=="], + "hapi-website/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="], "hapi-website/vitest/@vitest/expect": ["@vitest/expect@2.1.9", "", { "dependencies": { "@vitest/spy": "2.1.9", "@vitest/utils": "2.1.9", "chai": "^5.1.2", "tinyrainbow": "^1.2.0" } }, "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw=="], @@ -4203,6 +4321,10 @@ "jsdom/https-proxy-agent/agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + "leva/@radix-ui/react-portal/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], + + "leva/@radix-ui/react-portal/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + "motion/framer-motion/motion-dom": ["motion-dom@12.38.0", "", { "dependencies": { "motion-utils": "^12.36.0" } }, "sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA=="], "motion/framer-motion/motion-utils": ["motion-utils@12.36.0", "", {}, "sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg=="], @@ -4211,48 +4333,18 @@ "node-fetch/whatwg-url/webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], - "radix-ui/@radix-ui/react-accordion/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - - "radix-ui/@radix-ui/react-collapsible/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - - "radix-ui/@radix-ui/react-dialog/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - - "radix-ui/@radix-ui/react-dropdown-menu/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - - "radix-ui/@radix-ui/react-menu/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - - "radix-ui/@radix-ui/react-menubar/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - - "radix-ui/@radix-ui/react-navigation-menu/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - "radix-ui/@radix-ui/react-navigation-menu/@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg=="], - "radix-ui/@radix-ui/react-popover/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - - "radix-ui/@radix-ui/react-popper/@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.8", "", { "dependencies": { "@floating-ui/dom": "^1.7.6" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A=="], - - "radix-ui/@radix-ui/react-popper/@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.4", "", { "dependencies": { "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ=="], - - "radix-ui/@radix-ui/react-popper/@radix-ui/rect": ["@radix-ui/rect@1.1.3", "", {}, "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw=="], - - "radix-ui/@radix-ui/react-roving-focus/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - "radix-ui/@radix-ui/react-scroll-area/@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="], "radix-ui/@radix-ui/react-select/@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="], - "radix-ui/@radix-ui/react-select/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - "radix-ui/@radix-ui/react-select/@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg=="], "radix-ui/@radix-ui/react-slider/@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="], "radix-ui/@radix-ui/react-slider/@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg=="], - "radix-ui/@radix-ui/react-tabs/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - - "radix-ui/@radix-ui/react-tooltip/@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - "send/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], "shiki-stream/@shikijs/core/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="], @@ -4409,6 +4501,8 @@ "yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + "@base-ui/react/@floating-ui/react-dom/@floating-ui/dom/@floating-ui/core": ["@floating-ui/core@1.7.3", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w=="], + "@builder.io/vite-plugin-jsx-loc/vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="], "@builder.io/vite-plugin-jsx-loc/vite/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.21.5", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="], @@ -4455,8 +4549,6 @@ "@builder.io/vite-plugin-jsx-loc/vite/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="], - "@floating-ui/react/@floating-ui/react-dom/@floating-ui/dom/@floating-ui/core": ["@floating-ui/core@1.7.5", "", { "dependencies": { "@floating-ui/utils": "^0.2.11" } }, "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ=="], - "@lobehub/ui/remark-cjk-friendly/micromark-extension-cjk-friendly/micromark-extension-cjk-friendly-util": ["micromark-extension-cjk-friendly-util@3.0.1", "", { "dependencies": { "get-east-asian-width": "^1.4.0", "micromark-util-character": "^2.1.1", "micromark-util-symbol": "^2.0.1" } }, "sha512-GcbXqTTHOsiZHyF753oIddP/J2eH8j9zpyQPhkof6B2JNxfEJabnQqxbCgzJNuNes0Y2jTNJ3LiYPSXr6eJA8w=="], "@modelcontextprotocol/sdk/express/accepts/negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], @@ -4467,9 +4559,39 @@ "@modelcontextprotocol/sdk/express/type-is/mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-dismissable-layer/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-dismissable-layer/@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-focus-scope/@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-id/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-portal/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-presence/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-use-controllable-state/@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="], + + "@radix-ui/react-alert-dialog/@radix-ui/react-dialog/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="], + + "@radix-ui/react-aspect-ratio/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + + "@radix-ui/react-avatar/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + "@radix-ui/react-context-menu/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], - "@radix-ui/react-portal/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + "@radix-ui/react-hover-card/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom": ["@floating-ui/dom@1.7.4", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="], + + "@radix-ui/react-label/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + + "@radix-ui/react-menu/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom": ["@floating-ui/dom@1.7.4", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="], + + "@radix-ui/react-progress/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + + "@radix-ui/react-select/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom": ["@floating-ui/dom@1.7.4", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="], + + "@radix-ui/react-separator/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@radix-ui/react-tabs/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], @@ -4477,6 +4599,8 @@ "@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], + "@radix-ui/react-tooltip/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom": ["@floating-ui/dom@1.7.4", "", { "dependencies": { "@floating-ui/core": "^1.7.3", "@floating-ui/utils": "^0.2.10" } }, "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA=="], + "@radix-ui/react-visually-hidden/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "@vitejs/plugin-vue/vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="], @@ -4525,11 +4649,13 @@ "@vitejs/plugin-vue/vite/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="], + "hapi-web/@playwright/test/playwright/playwright-core": ["playwright-core@1.60.0", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA=="], + "hapi-website/vitest/vite/esbuild": ["esbuild@0.21.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.21.5", "@esbuild/android-arm": "0.21.5", "@esbuild/android-arm64": "0.21.5", "@esbuild/android-x64": "0.21.5", "@esbuild/darwin-arm64": "0.21.5", "@esbuild/darwin-x64": "0.21.5", "@esbuild/freebsd-arm64": "0.21.5", "@esbuild/freebsd-x64": "0.21.5", "@esbuild/linux-arm": "0.21.5", "@esbuild/linux-arm64": "0.21.5", "@esbuild/linux-ia32": "0.21.5", "@esbuild/linux-loong64": "0.21.5", "@esbuild/linux-mips64el": "0.21.5", "@esbuild/linux-ppc64": "0.21.5", "@esbuild/linux-riscv64": "0.21.5", "@esbuild/linux-s390x": "0.21.5", "@esbuild/linux-x64": "0.21.5", "@esbuild/netbsd-x64": "0.21.5", "@esbuild/openbsd-x64": "0.21.5", "@esbuild/sunos-x64": "0.21.5", "@esbuild/win32-arm64": "0.21.5", "@esbuild/win32-ia32": "0.21.5", "@esbuild/win32-x64": "0.21.5" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw=="], "hapi-website/vitest/vite/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - "radix-ui/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom": ["@floating-ui/dom@1.7.6", "", { "dependencies": { "@floating-ui/core": "^1.7.5", "@floating-ui/utils": "^0.2.11" } }, "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ=="], + "leva/@radix-ui/react-portal/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="], "streamdown/mermaid/@mermaid-js/parser/langium": ["langium@3.3.1", "", { "dependencies": { "chevrotain": "~11.0.3", "chevrotain-allstar": "~0.3.0", "vscode-languageserver": "~9.0.1", "vscode-languageserver-textdocument": "~1.0.11", "vscode-uri": "~3.0.8" } }, "sha512-QJv/h939gDpvT+9SiLVlY7tZC3xB2qK57v0J04Sh9wpMb6MP1q8gB21L3WIo8T5P1MSMg3Ep14L7KkDCFG3y4w=="], @@ -4629,6 +4755,14 @@ "yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + "@radix-ui/react-hover-card/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom/@floating-ui/core": ["@floating-ui/core@1.7.3", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w=="], + + "@radix-ui/react-menu/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom/@floating-ui/core": ["@floating-ui/core@1.7.3", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w=="], + + "@radix-ui/react-select/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom/@floating-ui/core": ["@floating-ui/core@1.7.3", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w=="], + + "@radix-ui/react-tooltip/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom/@floating-ui/core": ["@floating-ui/core@1.7.3", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w=="], + "hapi-website/vitest/vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="], "hapi-website/vitest/vite/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.21.5", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="], @@ -4675,9 +4809,7 @@ "hapi-website/vitest/vite/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="], - "radix-ui/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom/@floating-ui/core": ["@floating-ui/core@1.7.5", "", { "dependencies": { "@floating-ui/utils": "^0.2.11" } }, "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ=="], - - "radix-ui/@radix-ui/react-popper/@floating-ui/react-dom/@floating-ui/dom/@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="], + "leva/@radix-ui/react-portal/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="], "streamdown/mermaid/@mermaid-js/parser/langium/chevrotain": ["chevrotain@11.0.3", "", { "dependencies": { "@chevrotain/cst-dts-gen": "11.0.3", "@chevrotain/gast": "11.0.3", "@chevrotain/regexp-to-ast": "11.0.3", "@chevrotain/types": "11.0.3", "@chevrotain/utils": "11.0.3", "lodash-es": "4.17.21" } }, "sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw=="], diff --git a/e2e/history-load.spec.ts b/e2e/history-load.spec.ts index a4d0939e..6cbdb56d 100644 --- a/e2e/history-load.spec.ts +++ b/e2e/history-load.spec.ts @@ -1,4 +1,8 @@ -import { expect, test } from '@playwright/test' +import { expect as baseExpect, test } from '@playwright/test' + +// The capped-window cases render 800 real messages, including on small runners. +test.setTimeout(90_000) +const expect = baseExpect.configure({ timeout: 20_000 }) test('cached re-entry keeps the cache visible while refreshing a small latest tail', async ({ page }) => { await page.goto('/e2e-fixtures/history-load-fixture.html?cachedReentry=1&holdLatest=1') @@ -198,6 +202,7 @@ test('reversing toward newer history cancels a prepend at the row cap', async ({ }) } + await page.evaluate(() => window.__probe.holdBefore()) await approachTop() await expect.poll(async () => await page.evaluate(() => window.__probe.requests.filter((request) => request.direction === 'before').length @@ -223,8 +228,8 @@ test('reversing toward newer history cancels a prepend at the row cap', async ({ const anchorSequence = Number(newerAnchor.id.match(/m-(\d+)/)?.[1]) expect(anchorSequence).toBeGreaterThan(1000) - // Wait beyond the fixture's 500ms response delay. The invalidated response - // must not apply or trim the capped window. + await page.evaluate(() => window.__probe.releaseBefore()) + // The invalidated response must not apply or trim the capped window. await page.waitForTimeout(1000) const afterCancelledLoad = await page.evaluate((anchorId) => { const viewport = document.querySelector('.app-scroll-y') as HTMLElement @@ -277,14 +282,9 @@ test('capped prepend has no post-apply stale-DOM reversal window', async ({ page await page.evaluate(() => { delete document.documentElement.dataset.historyStoreDomGap - const deadline = Date.now() + 1500 const timer = window.setInterval(() => { const state = window.__probe.windowState() if (state.oldestSeq !== 201) { - if (Date.now() >= deadline) { - document.documentElement.dataset.historyStoreDomGap = 'timeout' - window.clearInterval(timer) - } return } @@ -321,6 +321,7 @@ test('ordinary tail synchronization re-arms covered history loading', async ({ p await expect(viewport).toBeVisible() await page.waitForTimeout(3500) + await page.evaluate(() => window.__probe.holdBefore()) await page.evaluate(() => { (document.querySelector('.app-scroll-y') as HTMLElement).scrollTop = 0 }) @@ -330,6 +331,7 @@ test('ordinary tail synchronization re-arms covered history loading', async ({ p await page.evaluate(async () => { await window.__probe.refetch() + window.__probe.releaseBefore() }) await expect.poll(async () => await page.evaluate(() => ({ @@ -451,8 +453,11 @@ test('wheel-up at the top loads older after automatic retries are exhausted', as // those events must share the active backoff run. (document.querySelector('.app-scroll-y') as HTMLElement).scrollTop = 50 }) - // Initial attempt + 3 bounded backoff retries (1s/2s/3s) all fail. - await page.waitForTimeout(8000) + // Wait for the initial attempt + 3 retries, not a rendering speed estimate. + await expect.poll(async () => await page.evaluate(() => ({ + requests: window.__probe.requests.filter((r) => r.direction === 'before').length, + loading: window.__probe.windowState().isLoadingMore + }))).toEqual({ requests: 4, loading: false }) const stuck = await page.evaluate(() => ({ childCount: document.querySelector('.happy-thread-messages')?.childElementCount ?? 0, beforeReqs: window.__probe.requests.filter((r) => r.direction === 'before').length @@ -464,7 +469,11 @@ test('wheel-up at the top loads older after automatic retries are exhausted', as (document.querySelector('.app-scroll-y') as HTMLElement).scrollTop = 0 }) await page.mouse.wheel(0, -300) - await page.waitForTimeout(2000) + await expect.poll(async () => await page.evaluate(() => ({ + requests: window.__probe.requests.filter((r) => r.direction === 'before').length, + rows: document.querySelector('.happy-thread-messages')?.childElementCount, + restored: (document.querySelector('.app-scroll-y') as HTMLElement).scrollTop > 1000 + }))).toEqual({ requests: 5, rows: 400, restored: true }) const recovered = await page.evaluate(() => ({ scrollTop: Math.round((document.querySelector('.app-scroll-y') as HTMLElement).scrollTop), childCount: document.querySelector('.happy-thread-messages')?.childElementCount ?? 0, @@ -626,25 +635,33 @@ test('touch pull shows staged feedback and loads older on release', async ({ pag window.__probe.requests.filter((request) => request.direction === 'before').length )).toBe(1) + await page.evaluate(() => window.__probe.holdBefore()) await dispatchTouch('touchend', 164) await expect.poll(async () => await page.evaluate(() => window.__probe.requests.filter((request) => request.direction === 'before').length )).toBe(2) await expect(page.getByText('Loading…', { exact: true })).toBeVisible() + await page.evaluate(() => window.__probe.releaseBefore()) + await expect(page.getByText('Loading…', { exact: true })).toBeHidden() }) // Regression: scroll/resize signals emitted while a failed page is in backoff // must join the same logical load. The delayed retry may discover an epoch // reset, which then stops the run without a third request. test('scroll events cannot bypass backoff before an epoch-reset stop', async ({ page }) => { + await page.clock.install({ time: new Date('2026-01-01T08:00:00Z') }) await page.goto('/e2e-fixtures/history-load-fixture.html?failBefore=1&epochBump=1') const viewport = page.locator('.app-scroll-y') await expect(viewport).toBeVisible() await page.waitForTimeout(3500) + await page.clock.pauseAt(new Date('2026-01-01T08:10:00Z')) await page.evaluate(() => { - (document.querySelector('.app-scroll-y') as HTMLElement).scrollTop = 0 + const viewport = document.querySelector('.app-scroll-y') as HTMLElement + viewport.scrollTop = 0 + viewport.dispatchEvent(new Event('scroll')) }) + await page.clock.runFor(250) await expect(page.getByText('fixture: forced before-page failure')).toBeVisible() // Programmatic/browser scroll signals during backoff must not start an @@ -654,13 +671,14 @@ test('scroll events cannot bypass backoff before an epoch-reset stop', async ({ viewport?.dispatchEvent(new Event('scroll')) viewport?.dispatchEvent(new Event('scroll')) }) - await page.waitForTimeout(400) + await page.clock.runFor(400) const duringBackoff = await page.evaluate(() => window.__probe.requests.filter((r) => r.direction === 'before').length ) expect(duringBackoff).toBe(1) // The controller-owned 1s retry returns the deliberate epoch-reset stop. + await page.clock.resume() await expect.poll(async () => await page.evaluate(() => window.__probe.requests.filter((r) => r.direction === 'before').length )).toBe(2) diff --git a/web/e2e-fixtures/history-load-fixture.tsx b/web/e2e-fixtures/history-load-fixture.tsx index d91df9be..fe229d1b 100644 --- a/web/e2e-fixtures/history-load-fixture.tsx +++ b/web/e2e-fixtures/history-load-fixture.tsx @@ -31,7 +31,14 @@ type Probe = { loadMore: () => Promise refetch: () => Promise releaseLatest: () => void - windowState: () => { messageCount: number; oldestSeq: number | null; newestSeq: number | null } + holdBefore: () => void + releaseBefore: () => void + windowState: () => { + messageCount: number + oldestSeq: number | null + newestSeq: number | null + isLoadingMore: boolean + } } declare global { @@ -42,18 +49,30 @@ declare global { let releaseLatestResponse = () => {} let latestResponseGate: Promise | null = null +let beforeResponseGate: Promise | null = null +let releaseBeforeResponse = () => {} window.__probe = { requests: [], loadMore: async () => {}, refetch: async () => {}, releaseLatest: () => releaseLatestResponse(), + holdBefore: () => { + beforeResponseGate = new Promise((resolve) => { + releaseBeforeResponse = resolve + }) + }, + releaseBefore: () => { + beforeResponseGate = null + releaseBeforeResponse() + }, windowState: () => { const state = getMessageWindowState(SESSION_ID) return { messageCount: state.messages.length, oldestSeq: state.oldestSeq, - newestSeq: state.newestSeq + newestSeq: state.newestSeq, + isLoadingMore: state.isLoadingMore } } } @@ -72,8 +91,8 @@ window.__probe = { // (reset + tail resync, typed terminal stop). // - ?coldInitial=1 — honor the production cold-open latest-page size instead // of returning the legacy full 200-row page used by this fixture by default. -// - ?slowBefore=1 — delay older-page responses long enough for a normal tail -// synchronization to invalidate an in-flight request. +// - ?slowBefore=1 — add latency to older-page responses. Use holdBefore / +// releaseBefore for tests that require a request to remain in flight. // - ?cachedReentry=1 — hydrate one cached message before activation, so the // latest-tail refresh path can be tested independently from a cold window. // - ?holdLatest=1 — hold the latest response until `window.__probe.releaseLatest` @@ -165,6 +184,7 @@ const fakeApi = { if (query.beforeSeq != null || query.beforeAt != null) direction = 'before' else if (query.afterSeq != null || query.afterAt != null) direction = 'after' const limit = direction === 'latest' && !coldInitial && !cachedReentry ? 200 : requestedLimit + const responseGate = direction === 'before' ? beforeResponseGate : null window.__probe.requests.push({ direction, beforeSeq: query.beforeSeq ?? null, @@ -177,6 +197,7 @@ const fakeApi = { resolve, direction === 'before' && slowBefore ? 500 : 50 )) + if (responseGate) await responseGate if (direction === 'latest' && latestResponseGate) { await latestResponseGate diff --git a/web/package.json b/web/package.json index e43113bb..1922dbe5 100644 --- a/web/package.json +++ b/web/package.json @@ -13,9 +13,9 @@ "test:mermaid-lightbox:e2e": "playwright test e2e/mermaid-lightbox.spec.ts" }, "dependencies": { - "@assistant-ui/react": "^0.14.29", - "@assistant-ui/react-markdown": "^0.14.7", - "@assistant-ui/tap": "^0.9.8", + "@assistant-ui/react": "^0.15.21", + "@assistant-ui/react-markdown": "^0.14.16", + "@assistant-ui/tap": "^0.9.18", "@elevenlabs/react": "^0.13.0", "@hapi/protocol": "workspace:*", "@lobehub/icons": "^5.14.0", diff --git a/web/src/components/AssistantChat/AttachmentItem.test.tsx b/web/src/components/AssistantChat/AttachmentItem.test.tsx index 7bad21b2..faa20fe3 100644 --- a/web/src/components/AssistantChat/AttachmentItem.test.tsx +++ b/web/src/components/AssistantChat/AttachmentItem.test.tsx @@ -12,7 +12,8 @@ const mocks = vi.hoisted(() => ({ })) vi.mock('@assistant-ui/react', () => ({ - useThreadComposerAttachment: () => mocks.attachment, + useAuiState: (selector: (state: { attachment: typeof mocks.attachment }) => unknown) => + selector({ attachment: mocks.attachment }), AttachmentPrimitive: { Root: ({ children, ...props }: ComponentProps<'div'>) =>
{children}
, Remove: ({ children, ...props }: ComponentProps<'button'> & { children?: ReactNode }) => ( diff --git a/web/src/components/AssistantChat/AttachmentItem.tsx b/web/src/components/AssistantChat/AttachmentItem.tsx index e42af739..c2419c58 100644 --- a/web/src/components/AssistantChat/AttachmentItem.tsx +++ b/web/src/components/AssistantChat/AttachmentItem.tsx @@ -1,4 +1,4 @@ -import { AttachmentPrimitive, useThreadComposerAttachment } from '@assistant-ui/react' +import { AttachmentPrimitive, useAuiState } from '@assistant-ui/react' import type { PendingAttachment } from '@assistant-ui/react' import type { KeyboardEventHandler, MouseEventHandler, PointerEventHandler, PointerEvent as ReactPointerEvent } from 'react' import { ImagePreview } from '@/components/ImagePreview' @@ -95,7 +95,7 @@ function DragHandle(props: AttachmentDragHandleProps & { isFile?: boolean }) { } export function AttachmentItem(props: { dragHandleProps?: AttachmentDragHandleProps } = {}) { - const { name, status, previewUrl } = useThreadComposerAttachment() as ComposerAttachmentWithPreview + const { name, status, previewUrl } = useAuiState((s) => s.attachment) as ComposerAttachmentWithPreview const isParking = useComposerParking() const isUploading = status.type === 'running' const isError = status.type === 'incomplete' diff --git a/web/src/components/AssistantChat/HappyThread.mobile-scroll.test.tsx b/web/src/components/AssistantChat/HappyThread.mobile-scroll.test.tsx index 915dd1cf..b186126d 100644 --- a/web/src/components/AssistantChat/HappyThread.mobile-scroll.test.tsx +++ b/web/src/components/AssistantChat/HappyThread.mobile-scroll.test.tsx @@ -140,6 +140,50 @@ afterEach(() => { }) describe('mobile initial scroll settling', () => { + it('checks the final keyboard position before clearing intent at scrollend', () => { + const { container, viewport } = renderThread() + const sentinel = container.querySelector('.chat-scroll-content > [aria-hidden="true"]')! + vi.spyOn(sentinel, 'getBoundingClientRect').mockImplementation(() => ({ + top: -viewport.scrollTop, + bottom: 1 - viewport.scrollTop + } as DOMRect)) + fireEvent.keyDown(viewport, { key: 'Home' }) + fireEvent.keyUp(viewport, { key: 'Home' }) + act(() => { + vi.advanceTimersByTime(1_000) + }) + viewport.scrollTop = 0 + fireEvent(viewport, new Event('scrollend')) + act(() => { + vi.advanceTimersByTime(1_800) + }) + expect(viewport.scrollTop).toBe(0) + }) + + it.each([false, true])('keeps delayed keyboard intent only until scrollend (ended=%s)', (ended) => { + const { container, viewport, onViewModeChange } = renderThread() + const sentinel = container.querySelector('.chat-scroll-content > [aria-hidden="true"]')! + vi.spyOn(sentinel, 'getBoundingClientRect').mockImplementation(() => ({ + top: -viewport.scrollTop, + bottom: 1 - viewport.scrollTop + } as DOMRect)) + + fireEvent.keyDown(viewport, { key: 'Home' }) + fireEvent.keyUp(viewport, { key: 'Home' }) + act(() => { + vi.advanceTimersByTime(1_000) + }) + if (ended) fireEvent(viewport, new Event('scrollend')) + viewport.scrollTop = 520 + fireEvent.scroll(viewport) + act(() => { + vi.advanceTimersByTime(1_800) + }) + + expect(viewport.scrollTop).toBe(ended ? 702 : 520) + if (!ended) expect(onViewModeChange).toHaveBeenLastCalledWith('history') + }) + it('does not snap back after pointer cancellation ends a touch swipe', () => { const { viewport, onViewModeChange } = renderThread() expect(viewport.scrollTop).toBe(702) diff --git a/web/src/components/AssistantChat/HappyThread.tsx b/web/src/components/AssistantChat/HappyThread.tsx index 388cae21..6337c139 100644 --- a/web/src/components/AssistantChat/HappyThread.tsx +++ b/web/src/components/AssistantChat/HappyThread.tsx @@ -141,7 +141,6 @@ const TOP_PULL_TRIGGER_PX = 64 // Trackpads emit a burst per swipe; one signal is enough to restart a paused // run after its bounded retry budget is exhausted. const WHEEL_GESTURE_GAP_MS = 250 -const KEYBOARD_SCROLL_INTENT_WINDOW_MS = 750 const POINTER_CANCEL_INTENT_WINDOW_MS = 750 const UPWARD_SCROLL_KEYS = new Set(['ArrowUp', 'PageUp', 'Home']) @@ -692,6 +691,9 @@ export function HappyThread(props: { useEffect(() => { isSyncingTailRef.current = props.isSyncingTail }, [props.isSyncingTail]) + useLayoutEffect(() => { + isLoadingMoreRef.current = props.isLoadingMoreMessages + }, [props.isLoadingMoreMessages]) useEffect(() => { onLoadMoreRef.current = props.onLoadMore }, [props.onLoadMore]) @@ -787,7 +789,7 @@ export function HappyThread(props: { let pointerResumeActive = false let pointerResumeUntil = 0 let pointerResumeLatched = false - let keyboardResumeUntil = 0 + let keyboardResumeActive = false let lastWheelAt = 0 let wheelIntentUntil = 0 let wheelLatched = false @@ -796,7 +798,7 @@ export function HappyThread(props: { return intent.isScrollingUp && ( pointerResumeActive || pointerResumeUntil >= Date.now() - || keyboardResumeUntil >= Date.now() + || keyboardResumeActive || wheelIntentUntil >= Date.now() ) } @@ -809,8 +811,8 @@ export function HappyThread(props: { pointerResumeLatched = true return true } - if (keyboardResumeUntil >= Date.now()) { - keyboardResumeUntil = 0 + if (keyboardResumeActive) { + keyboardResumeActive = false return true } if (wheelIntentUntil >= Date.now() && !wheelLatched) { @@ -821,6 +823,9 @@ export function HappyThread(props: { } const handleScroll = () => { + if (viewport.scrollTop > lastScrollTopRef.current) { + keyboardResumeActive = false + } const intent = getScrollIntent({ scrollTop: viewport.scrollTop, scrollHeight: viewport.scrollHeight, @@ -920,6 +925,9 @@ export function HappyThread(props: { const handleKeyDown = (event: KeyboardEvent) => { if (isNestedScrollEvent(event)) return + if (!UPWARD_SCROLL_KEYS.has(event.key)) { + keyboardResumeActive = false + } const target = event.target if ( event.defaultPrevented @@ -934,14 +942,17 @@ export function HappyThread(props: { ) { return } - keyboardResumeUntil = Date.now() + KEYBOARD_SCROLL_INTENT_WINDOW_MS + // Native keyboard scrolling can outlive a fixed intent timeout. + // Keep this gesture armed until consumed, completed, or cancelled. + keyboardResumeActive = true if (needsViewportCoverageRef.current()) { - keyboardResumeUntil = 0 + keyboardResumeActive = false void requestOlderRef.current('user') } } const armPointerIntent = () => { + keyboardResumeActive = false pointerResumeActive = true pointerResumeUntil = 0 pointerResumeLatched = false @@ -1002,6 +1013,7 @@ export function HappyThread(props: { const handleWheel = (event: WheelEvent) => { if (isNestedScrollEvent(event)) return + keyboardResumeActive = false if (event.deltaY >= 0) { wheelIntentUntil = 0 return @@ -1025,6 +1037,7 @@ export function HappyThread(props: { const handleTouchStart = (event: TouchEvent) => { if (isNestedScrollEvent(event)) return + keyboardResumeActive = false updatePullToLoadState('idle') pullStartY = ( viewport.scrollTop <= 0 @@ -1071,7 +1084,21 @@ export function HappyThread(props: { updatePullToLoadState('idle') } + const clearKeyboardIntent = () => { + keyboardResumeActive = false + } + const handleScrollEnd = (event: Event) => { + if (event.target !== viewport) return + // Recheck the final geometry before retiring unconsumed demand. + if (keyboardResumeActive && needsViewportCoverageRef.current()) { + void requestOlderRef.current('user') + } + clearKeyboardIntent() + } + viewport.addEventListener('scroll', handleScroll, { passive: true }) + viewport.addEventListener('scrollend', handleScrollEnd) + viewport.addEventListener('focusout', clearKeyboardIntent) viewport.addEventListener('keydown', handleKeyDown) viewport.addEventListener('pointerdown', handlePointerDown, { passive: true }) viewport.addEventListener('wheel', handleWheel, { passive: true }) @@ -1085,8 +1112,11 @@ export function HappyThread(props: { window.addEventListener('mouseup', clearPointerIntent, { passive: true }) window.addEventListener('pointercancel', handlePointerCancel, { passive: true }) window.addEventListener('blur', clearPointerIntent) + window.addEventListener('blur', clearKeyboardIntent) return () => { viewport.removeEventListener('scroll', handleScroll) + viewport.removeEventListener('scrollend', handleScrollEnd) + viewport.removeEventListener('focusout', clearKeyboardIntent) viewport.removeEventListener('keydown', handleKeyDown) viewport.removeEventListener('pointerdown', handlePointerDown) viewport.removeEventListener('wheel', handleWheel) @@ -1100,6 +1130,7 @@ export function HappyThread(props: { window.removeEventListener('mouseup', clearPointerIntent) window.removeEventListener('pointercancel', handlePointerCancel) window.removeEventListener('blur', clearPointerIntent) + window.removeEventListener('blur', clearKeyboardIntent) } }, []) // Stable: no dependencies, reads from refs @@ -1623,10 +1654,6 @@ export function HappyThread(props: { clearFailureRetryTimer ]) - useEffect(() => { - isLoadingMoreRef.current = props.isLoadingMoreMessages - }, [props.isLoadingMoreMessages]) - const showSkeleton = props.isSyncingTail && props.rawMessagesCount === 0 const handleShareTurn = useCallback(( messageTarget: HTMLElement | string | null, diff --git a/web/src/lib/assistant-runtime.snapshots.test.tsx b/web/src/lib/assistant-runtime.snapshots.test.tsx new file mode 100644 index 00000000..cdb9f900 --- /dev/null +++ b/web/src/lib/assistant-runtime.snapshots.test.tsx @@ -0,0 +1,47 @@ +import { StrictMode, useSyncExternalStore } from 'react' +import { act, renderHook } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import type { Session } from '@/types/api' +import { useHappyRuntime } from './assistant-runtime' + +describe('assistant-ui composer snapshots', () => { + it('keeps snapshots stable and updates running state without a composer edit', async () => { + const onSendMessage = vi.fn() + const onAbort = vi.fn(async () => {}) + const session = { id: 'snapshot-test', active: true, thinking: false } as Session + const { result, rerender } = renderHook(({ isRunning }) => { + const runtime = useHappyRuntime({ + session, + blocks: [], + messagesVersion: 0, + historyVersion: 0, + isSending: false, + isRunning, + onSendMessage, + onAbort, + }) + const composer = runtime.thread.composer + const snapshot = useSyncExternalStore(composer.subscribe, composer.getState) + return { composer, snapshot } + }, { initialProps: { isRunning: false }, wrapper: StrictMode }) + + expect(result.current.snapshot.canCancel).toBe(false) + expect(result.current.composer.getState()).toBe(result.current.snapshot) + + // Dictation and draft restoration both write through setText. + act(() => result.current.composer.setText('dictated words')) + expect(result.current.snapshot.text).toBe('dictated words') + expect(result.current.composer.getState()).toBe(result.current.snapshot) + + rerender({ isRunning: true }) + expect(result.current.snapshot.canCancel).toBe(true) + expect(result.current.snapshot.text).toBe('dictated words') + rerender({ isRunning: false }) + expect(result.current.snapshot.canCancel).toBe(false) + + await act(async () => result.current.composer.send()) + expect(onSendMessage).toHaveBeenCalledExactlyOnceWith('dictated words', undefined, null, 'default') + expect(result.current.snapshot.text).toBe('') + expect(result.current.composer.getState()).toBe(result.current.snapshot) + }) +}) From b6a27bdc6877c25794c050e709fe808457a5ec97 Mon Sep 17 00:00:00 2001 From: Miro Date: Mon, 21 Sep 2026 07:58:59 +0200 Subject: [PATCH 15/34] fix(kimi): discover configured models dynamically (#1873) * fix(kimi): discover configured models dynamically * fix(kimi): address dynamic model review findings Probe settlement (Major): parse `kimi provider list --json` on the child's 'close' event instead of 'exit', so stdio is fully drained first, and run the parse inside a guarded settle() helper. A parser throw previously escaped the promise from an async event callback and reached the runner's uncaughtException shutdown handler instead of listKimiModelsForCwd's catch. The helper also settles the promise exactly once across timeout, spawn error and close, names the terminating signal when there is no exit code, and tolerates a kill() that throws. Running-session discovery (Minor): add a session-scoped Kimi catalog. The shared RPC method `listKimiModels`, a CLI handler registered on the session connection with the probe cwd taken from the session metadata (never from RPC arguments), hub rpcGateway/syncEngine pass-throughs, and GET /api/sessions/:id/kimi-models gated on an active session of flavor `kimi`. SessionChat now reads the catalog from that endpoint, so an active session advertises its models even when no background runner holds the machine socket. New Session keeps the machine-scoped discovery unchanged, and model switching still goes through the existing ACP set_model path. * fix(kimi): register session model discovery before the local/remote loop The session catalog handler was registered inside the remote launcher, after ACP initialization. A session started with `hapi kimi` in local mode therefore answered the web picker's request with an unregistered-handler error, and the failed query was not retried or invalidated when remote control was taken over. The catalog is backend independent, so it is now registered in runKimi session setup alongside the other session-level handlers, using the session's working directory, and the late registration in the remote launcher is removed. This covers local, remote and resumed sessions on the same session connection. Adds cli/src/kimi/runKimi.test.ts asserting the handler is registered after bootstrap and before the loop, and that the probe cwd is the session's working directory. The launcher wiring assertion moves out of kimiRemoteLauncher.test.ts with the registration. --- cli/src/api/apiMachine.test.ts | 72 ++++++ cli/src/api/apiMachine.ts | 20 ++ cli/src/kimi/runKimi.test.ts | 105 +++++++++ cli/src/kimi/runKimi.ts | 5 + .../common/handlers/kimiModels.test.ts | 135 +++++++++++ cli/src/modules/common/handlers/kimiModels.ts | 46 ++++ cli/src/modules/common/kimiModels.test.ts | 168 +++++++++++++ cli/src/modules/common/kimiModels.ts | 223 ++++++++++++++++++ .../modules/common/kimiModelsProbe.test.ts | 175 ++++++++++++++ .../modules/common/registerCommonHandlers.ts | 2 + docs/api/client-contract/rest.md | 4 +- hub/src/sync/rpcGateway.ts | 24 ++ hub/src/sync/syncEngine.ts | 10 + hub/src/web/routes/machines.ts | 25 ++ hub/src/web/routes/sessions.test.ts | 46 ++++ hub/src/web/routes/sessions.ts | 18 ++ shared/src/agentConfig.ts | 2 +- shared/src/apiTypes.ts | 16 ++ shared/src/rpcMethods.ts | 2 + web/src/api/client.test.ts | 30 +++ web/src/api/client.ts | 13 + .../AssistantChat/modelOptions.test.ts | 18 ++ .../components/NewSession/grokModels.test.ts | 69 +++++- web/src/components/NewSession/grokModels.ts | 48 +++- web/src/components/NewSession/index.test.tsx | 100 ++++++++ web/src/components/NewSession/index.tsx | 59 ++++- .../components/NewSession/preferences.test.ts | 18 ++ web/src/components/NewSession/preferences.ts | 5 +- web/src/components/SessionChat.tsx | 21 +- web/src/hooks/queries/useKimiModelsForCwd.ts | 48 ++++ .../queries/useKimiModelsForSession.test.tsx | 108 +++++++++ .../hooks/queries/useKimiModelsForSession.ts | 38 +++ web/src/lib/query-keys.ts | 2 + web/src/types/api.ts | 2 + 34 files changed, 1664 insertions(+), 13 deletions(-) create mode 100644 cli/src/kimi/runKimi.test.ts create mode 100644 cli/src/modules/common/handlers/kimiModels.test.ts create mode 100644 cli/src/modules/common/handlers/kimiModels.ts create mode 100644 cli/src/modules/common/kimiModels.test.ts create mode 100644 cli/src/modules/common/kimiModels.ts create mode 100644 cli/src/modules/common/kimiModelsProbe.test.ts create mode 100644 web/src/hooks/queries/useKimiModelsForCwd.ts create mode 100644 web/src/hooks/queries/useKimiModelsForSession.test.tsx create mode 100644 web/src/hooks/queries/useKimiModelsForSession.ts diff --git a/cli/src/api/apiMachine.test.ts b/cli/src/api/apiMachine.test.ts index fecf5672..ccc48662 100644 --- a/cli/src/api/apiMachine.test.ts +++ b/cli/src/api/apiMachine.test.ts @@ -8,6 +8,7 @@ const listOpencodeModelsForCwdMock = vi.hoisted(() => vi.fn()) const listOpencodeModelVariantsMock = vi.hoisted(() => vi.fn()) const listGrokModelsForCwdMock = vi.hoisted(() => vi.fn()) const listCopilotModelsForCwdMock = vi.hoisted(() => vi.fn()) +const listKimiModelsForCwdMock = vi.hoisted(() => vi.fn()) const inspectCursorChatStoreMock = vi.hoisted(() => vi.fn()) vi.mock('socket.io-client', () => ({ @@ -34,6 +35,10 @@ vi.mock('../modules/common/copilotModels', () => ({ listCopilotModelsForCwd: listCopilotModelsForCwdMock })) +vi.mock('../modules/common/kimiModels', () => ({ + listKimiModelsForCwd: listKimiModelsForCwdMock +})) + vi.mock('@/cursor/cursorChatStoreStatus', () => ({ inspectCursorChatStore: inspectCursorChatStoreMock })) @@ -107,6 +112,15 @@ async function callListCopilotModels(client: ApiMachineClient, machineId: string return JSON.parse(raw) as unknown } +async function callListKimiModels(client: ApiMachineClient, machineId: string, cwd: string): Promise { + const manager = (client as unknown as { rpcHandlerManager: { handleRequest: (req: { method: string; params: string }) => Promise } }).rpcHandlerManager + const raw = await manager.handleRequest({ + method: `${machineId}:listKimiModelsForCwd`, + params: JSON.stringify({ cwd }) + }) + return JSON.parse(raw) as unknown +} + async function callCursorChatStoreStatus( client: ApiMachineClient, machineId: string, @@ -479,6 +493,64 @@ describe('ApiMachineClient listGrokModelsForCwd handler', () => { }) }) +describe('ApiMachineClient listKimiModelsForCwd handler', () => { + let workspaceRoot: string + + beforeEach(() => { + ioMock.mockReset() + listKimiModelsForCwdMock.mockReset() + workspaceRoot = mkdtempSync(join(tmpdir(), 'hapi-kimi-machine-ws-')) + }) + + afterEach(() => { + rmSync(workspaceRoot, { recursive: true, force: true }) + }) + + it('rejects cwd outside workspace roots before running the Kimi model probe', async () => { + const machine = makeMachine('kimi-machine-1') + const client = new ApiMachineClient('cli-token', machine, [workspaceRoot]) + const outsideCwd = mkdtempSync(join(tmpdir(), 'hapi-kimi-outside-')) + + try { + expect(await callListKimiModels(client, machine.id, outsideCwd)).toEqual({ + success: false, + error: 'Path is outside workspace roots' + }) + expect(listKimiModelsForCwdMock).not.toHaveBeenCalled() + } finally { + rmSync(outsideCwd, { recursive: true, force: true }) + client.shutdown() + } + }) + + it('forwards a resolved workspace cwd to the Kimi model probe', async () => { + const machine = makeMachine('kimi-machine-2') + const client = new ApiMachineClient('cli-token', machine, [workspaceRoot]) + listKimiModelsForCwdMock.mockResolvedValueOnce({ + success: true, + availableModels: [ + { modelId: 'GLM-5.3-flash', name: 'thehive / GLM-5.3-flash', provider: 'thehive' }, + { modelId: 'hyper-glm-5.3-flash', name: 'charm-hyper / Hyper · GLM-5.3-Flash', provider: 'charm-hyper' } + ], + currentModelId: 'GLM-5.3-flash' + }) + + try { + expect(await callListKimiModels(client, machine.id, workspaceRoot)).toEqual({ + success: true, + availableModels: [ + { modelId: 'GLM-5.3-flash', name: 'thehive / GLM-5.3-flash', provider: 'thehive' }, + { modelId: 'hyper-glm-5.3-flash', name: 'charm-hyper / Hyper · GLM-5.3-Flash', provider: 'charm-hyper' } + ], + currentModelId: 'GLM-5.3-flash' + }) + expect(listKimiModelsForCwdMock).toHaveBeenCalledWith(realpathSync.native(workspaceRoot)) + } finally { + client.shutdown() + } + }) +}) + describe('ApiMachineClient Codex transcript handlers', () => { const originalCodexHome = process.env.CODEX_HOME let workspaceRoot: string diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index c1ae191a..b342e4e8 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -49,6 +49,11 @@ import { type ListCopilotModelsForCwdRequest, type ListCopilotModelsForCwdResponse } from '../modules/common/copilotModels' +import { + listKimiModelsForCwd, + type ListKimiModelsForCwdRequest, + type ListKimiModelsForCwdResponse +} from '../modules/common/kimiModels' import type { SpawnSessionOptions, SpawnSessionResult } from '../modules/common/rpcTypes' import { applyVersionedAck } from './versionedUpdate' import { archiveLocalCodexSession, listLocalCodexSessionSummaries, listLocalCodexSessionsWithMessagesByIds } from '../modules/common/codexSessions' @@ -306,6 +311,21 @@ export class ApiMachineClient { } ) + this.rpcHandlerManager.registerHandler( + RPC_METHODS.ListKimiModelsForCwd, + async (params) => { + const rawCwd = typeof params?.cwd === 'string' ? params.cwd.trim() : '' + if (!rawCwd) return { success: false, error: 'cwd is required' } + + const resolvedCwd = await this.pathPolicy.resolveForCheck(rawCwd) + if (!this.pathPolicy.isWithinSpawnRoots(resolvedCwd)) { + return { success: false, error: 'Path is outside workspace roots' } + } + + return await listKimiModelsForCwd(resolvedCwd) + } + ) + this.rpcHandlerManager.registerHandler( RPC_METHODS.ListCodexSessions, async (params) => { diff --git a/cli/src/kimi/runKimi.test.ts b/cli/src/kimi/runKimi.test.ts new file mode 100644 index 00000000..e971be34 --- /dev/null +++ b/cli/src/kimi/runKimi.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it, vi } from 'vitest' + +const harness = vi.hoisted(() => ({ + order: [] as string[], + registered: [] as Array<{ manager: unknown; getCwd: () => string }>, + loopOptions: null as Record | null, + createSession: () => ({ + rpcHandlerManager: { registerHandler: vi.fn() }, + onUserMessage: vi.fn(), + onCancelQueuedMessage: vi.fn() + }) +})) + +vi.mock('@/modules/common/handlers/kimiModels', () => ({ + registerKimiSessionModelHandlers: (manager: unknown, getCwd: () => string) => { + harness.order.push('register-kimi-models') + harness.registered.push({ manager, getCwd }) + } +})) + +vi.mock('@/agent/sessionFactory', () => ({ + bootstrapSession: async () => { + harness.order.push('bootstrap') + return { + api: {}, + session: harness.createSession(), + sessionInfo: {}, + metadata: {}, + machineId: 'machine-1', + startedBy: 'terminal', + workingDirectory: '/work/project' + } + }, + bootstrapExistingSession: async () => { + harness.order.push('bootstrap') + return { + api: {}, + session: harness.createSession(), + sessionInfo: {}, + metadata: {}, + machineId: 'machine-1', + startedBy: 'terminal', + workingDirectory: '/work/project' + } + } +})) + +vi.mock('./loop', () => ({ + kimiLoop: async (options: Record) => { + harness.order.push('loop') + harness.loopOptions = options + } +})) + +vi.mock('@/agent/runnerLifecycle', () => ({ + createRunnerLifecycle: () => ({ + registerProcessHandlers: vi.fn(), + markCrash: vi.fn(), + setExitCode: vi.fn(), + setArchiveReason: vi.fn(), + setSessionEndReason: vi.fn(), + cleanupAndExit: async () => {} + }), + createModeChangeHandler: () => vi.fn(), + setControlledByUser: vi.fn() +})) + +vi.mock('@/claude/registerKillSessionHandler', () => ({ + registerKillSessionHandler: vi.fn() +})) +vi.mock('@/agent/localHandoff', () => ({ + registerLocalHandoffHandler: vi.fn() +})) +vi.mock('./utils/config', () => ({ + resolveKimiRuntimeConfig: () => ({ model: undefined, modelSource: 'default' }) +})) + +import { runKimi } from './runKimi' + +describe('runKimi session model discovery', () => { + it('registers the session catalog before the local/remote loop starts', async () => { + harness.order = [] + harness.registered = [] + harness.loopOptions = null + + await runKimi({ workingDirectory: '/work/project', startingMode: 'local' }) + + // A locally running session must answer the picker's request even + // though no remote launcher (and no ACP backend) exists yet. + expect(harness.order).toEqual(['bootstrap', 'register-kimi-models', 'loop']) + expect(harness.registered).toHaveLength(1) + }) + + it('probes the working directory the session was started in', async () => { + harness.order = [] + harness.registered = [] + harness.loopOptions = null + + await runKimi({ workingDirectory: '/work/other-project', startingMode: 'local' }) + + const loopOptions = harness.loopOptions as Record | null + expect(harness.registered[0]?.getCwd()).toBe('/work/other-project') + expect(loopOptions?.path).toBe('/work/other-project') + }) +}) diff --git a/cli/src/kimi/runKimi.ts b/cli/src/kimi/runKimi.ts index f148b880..e30857e0 100644 --- a/cli/src/kimi/runKimi.ts +++ b/cli/src/kimi/runKimi.ts @@ -14,6 +14,7 @@ import { PermissionModeSchema } from '@hapi/protocol/schemas'; import { formatMessageWithAttachments } from '@/utils/attachmentFormatter'; import { getInvokedCwd } from '@/utils/invokedCwd'; import { resolveKimiRuntimeConfig } from './utils/config'; +import { registerKimiSessionModelHandlers } from '@/modules/common/handlers/kimiModels'; export async function runKimi(opts: { startedBy?: 'runner' | 'terminal'; @@ -84,6 +85,10 @@ export async function runKimi(opts: { lifecycle.registerProcessHandlers(); registerKillSessionHandler(session.rpcHandlerManager, lifecycle); registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle); + // Registered here, not in the remote launcher: the catalog is backend + // independent, and a session running in local mode must answer the web + // picker's request before remote control is taken over. + registerKimiSessionModelHandlers(session.rpcHandlerManager, () => workingDirectory); const syncSessionMode = () => { const sessionInstance = sessionWrapperRef.current; diff --git a/cli/src/modules/common/handlers/kimiModels.test.ts b/cli/src/modules/common/handlers/kimiModels.test.ts new file mode 100644 index 00000000..8af2c140 --- /dev/null +++ b/cli/src/modules/common/handlers/kimiModels.test.ts @@ -0,0 +1,135 @@ +import { EventEmitter } from 'node:events' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { RPC_METHODS } from '@hapi/protocol/rpcMethods' +import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager' + +const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })) + +vi.mock('node:child_process', () => ({ spawn: spawnMock })) +vi.mock('@/ui/logger', () => ({ + logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() } +})) +vi.mock('@/kimi/utils/config', () => ({ + readKimiLocalConfig: () => ({ model: 'GLM-5.3-flash' }) +})) + +import { _resetKimiModelsCacheForTests } from '../kimiModels' +import { registerKimiSessionModelHandlers } from './kimiModels' + +class FakeChild extends EventEmitter { + stdout = new EventEmitter() + stderr = new EventEmitter() + kill = vi.fn() +} + +/** Real `kimi provider list --json` shape, including fields HAPI must strip. */ +const PROVIDER_PAYLOAD = JSON.stringify({ + providers: { + thehive: { + baseUrl: 'https://api.thehive.example/v1', + type: 'openai', + apiKey: 'sk-secret-thehive-key' + } + }, + models: { + 'GLM-5.3-flash': { + provider: 'thehive', + model: 'zai-org/glm-5.3-flash', + displayName: 'thehive / GLM-5.3-flash', + capabilities: ['tool_use'] + } + } +}) + +function registerSessionHandlers(cwd: string): (params: unknown) => Promise { + const handlers = new Map Promise>() + const rpcHandlerManager = { + registerHandler: (method: string, handler: (params: unknown) => Promise) => { + handlers.set(method, handler) + } + } as unknown as RpcHandlerManager + + registerKimiSessionModelHandlers(rpcHandlerManager, () => cwd) + + const handler = handlers.get(RPC_METHODS.ListKimiModels) + if (!handler) { + throw new Error(`session handler ${RPC_METHODS.ListKimiModels} was not registered`) + } + return handler +} + +beforeEach(() => { + spawnMock.mockReset() + _resetKimiModelsCacheForTests() +}) + +describe('registerKimiSessionModelHandlers', () => { + it('answers the catalog over the session connection without a runner', async () => { + const handler = registerSessionHandlers('/work/project') + const child = new FakeChild() + spawnMock.mockImplementation(() => child) + + const pending = handler(undefined) + child.stdout.emit('data', PROVIDER_PAYLOAD) + child.emit('close', 0, null) + + await expect(pending).resolves.toEqual({ + success: true, + availableModels: [{ + modelId: 'GLM-5.3-flash', + name: 'thehive / GLM-5.3-flash', + provider: 'thehive' + }], + currentModelId: 'GLM-5.3-flash' + }) + expect(spawnMock).toHaveBeenCalledWith( + 'kimi', + ['provider', 'list', '--json'], + expect.any(Object) + ) + }) + + it('returns only modelId, name and provider — never provider credentials', async () => { + const handler = registerSessionHandlers('/work/project') + const child = new FakeChild() + spawnMock.mockImplementation(() => child) + + const pending = handler(undefined) + child.stdout.emit('data', PROVIDER_PAYLOAD) + child.emit('close', 0, null) + + const response = await pending + const serialized = JSON.stringify(response) + expect(serialized).not.toContain('sk-secret-thehive-key') + expect(serialized).not.toContain('api.thehive.example') + expect(serialized).not.toContain('baseUrl') + expect(serialized).not.toContain('capabilities') + expect(serialized).not.toContain('zai-org/glm-5.3-flash') + expect(Object.keys((response as { availableModels: Array }).availableModels[0]!).sort()) + .toEqual(['modelId', 'name', 'provider']) + }) + + it('reports a malformed probe as a failed response instead of throwing', async () => { + const handler = registerSessionHandlers('/work/project') + const child = new FakeChild() + spawnMock.mockImplementation(() => child) + + const pending = handler(undefined) + child.stdout.emit('data', '{"models":') + child.emit('close', 0, null) + await expect(pending).resolves.toEqual({ + success: false, + error: 'kimi provider list produced invalid JSON output' + }) + }) + + it('scopes the probe to the session cwd and ignores cwd sent by the caller', async () => { + const handler = registerSessionHandlers('') + + await expect(handler({ cwd: '/etc' })).resolves.toEqual({ + success: false, + error: 'cwd is required' + }) + expect(spawnMock).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/modules/common/handlers/kimiModels.ts b/cli/src/modules/common/handlers/kimiModels.ts new file mode 100644 index 00000000..97d2e9f3 --- /dev/null +++ b/cli/src/modules/common/handlers/kimiModels.ts @@ -0,0 +1,46 @@ +import { logger } from '@/ui/logger' +import { RPC_METHODS } from '@hapi/protocol/rpcMethods' +import type { ListKimiModelsResponse } from '@hapi/protocol/apiTypes' +import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager' +import { + listKimiModelsForCwd, + type ListKimiModelsForCwdRequest, + type ListKimiModelsForCwdResponse +} from '../kimiModels' +import { getErrorMessage, rpcError } from '../rpcResponses' + +export function registerKimiModelHandlers(rpcHandlerManager: RpcHandlerManager): void { + rpcHandlerManager.registerHandler( + RPC_METHODS.ListKimiModelsForCwd, + async (data) => { + try { + return await listKimiModelsForCwd(typeof data?.cwd === 'string' ? data.cwd : '') + } catch (error) { + logger.debug('Failed to list Kimi models:', error) + return rpcError(getErrorMessage(error, 'Failed to list Kimi models')) + } + } + ) +} + +/** + * Session-scoped discovery for a running Kimi session. The probe cwd is the + * session's own metadata, never an RPC argument, so this cannot be pointed at + * an arbitrary directory. + */ +export function registerKimiSessionModelHandlers( + rpcHandlerManager: RpcHandlerManager, + getCwd: () => string +): void { + rpcHandlerManager.registerHandler( + RPC_METHODS.ListKimiModels, + async () => { + try { + return await listKimiModelsForCwd(getCwd()) + } catch (error) { + logger.debug('Failed to list Kimi models:', error) + return rpcError(getErrorMessage(error, 'Failed to list Kimi models')) + } + } + ) +} diff --git a/cli/src/modules/common/kimiModels.test.ts b/cli/src/modules/common/kimiModels.test.ts new file mode 100644 index 00000000..b7b142ec --- /dev/null +++ b/cli/src/modules/common/kimiModels.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from 'vitest' +import { buildKimiProviderListArgs, parseKimiProviderListOutput } from './kimiModels' + +const PROVIDER_LIST_OUTPUT = JSON.stringify({ + providers: { + thehive: { + baseUrl: 'https://api.thehive.example/v1', + type: 'openai', + apiKey: 'sk-secret-thehive-key' + }, + 'charm-hyper': { + baseUrl: 'https://api.charm-hyper.example', + type: 'openai', + apiKey: 'sk-secret-charm-key' + }, + openrouter: { + baseUrl: 'https://openrouter.example/api', + type: 'openai', + apiKey: 'sk-secret-openrouter-key' + } + }, + models: { + 'GLM-5.3-flash': { + provider: 'thehive', + model: 'zai-org/glm-5.3-flash', + displayName: 'thehive / GLM-5.3-flash', + capabilities: ['tool_use', 'image_in'] + }, + 'deepseek-v4.1-flash': { + provider: 'thehive', + model: 'deepseek-ai/deepseek-v4.1-flash', + displayName: 'thehive / hive-deepseek' + }, + 'hyper-glm-5.3-flash': { + provider: 'charm-hyper', + model: 'glm-5.3-flash', + displayName: 'charm-hyper / Hyper · GLM-5.3-Flash' + }, + 'openrouter-union-alpha': { + provider: 'openrouter', + model: 'stealth/union-alpha', + displayName: 'openrouter / Union Alpha' + } + } +}) + +describe('buildKimiProviderListArgs', () => { + it('uses the provider list command in json mode', () => { + expect(buildKimiProviderListArgs()).toEqual(['provider', 'list', '--json']) + }) +}) + +describe('parseKimiProviderListOutput', () => { + it('parses the real provider list format with multiple providers', () => { + const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT) + expect(parsed.availableModels.map((model) => model.modelId)).toEqual([ + 'hyper-glm-5.3-flash', + 'openrouter-union-alpha', + 'deepseek-v4.1-flash', + 'GLM-5.3-flash' + ]) + expect(parsed.currentModelId).toBeNull() + }) + + it('keeps several models of the same provider distinct', () => { + const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT) + const thehiveModels = parsed.availableModels.filter((model) => model.provider === 'thehive') + expect(thehiveModels.map((model) => model.modelId).sort()).toEqual([ + 'GLM-5.3-flash', + 'deepseek-v4.1-flash' + ]) + }) + + it('carries provider and display name for UI labels', () => { + const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT) + const hyper = parsed.availableModels.find((model) => model.modelId === 'hyper-glm-5.3-flash') + expect(hyper).toEqual({ + modelId: 'hyper-glm-5.3-flash', + name: 'charm-hyper / Hyper · GLM-5.3-Flash', + provider: 'charm-hyper' + }) + }) + + it('never transmits secrets from the provider payload', () => { + const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT) + const serialized = JSON.stringify(parsed) + expect(serialized).not.toContain('sk-secret-thehive-key') + expect(serialized).not.toContain('sk-secret-charm-key') + expect(serialized).not.toContain('sk-secret-openrouter-key') + expect(serialized).not.toContain('api.thehive.example') + expect(serialized).not.toContain('openrouter.example') + for (const model of parsed.availableModels) { + expect(Object.keys(model).sort()).toEqual(['modelId', 'name', 'provider'].sort()) + } + }) + + it('reports the local default model as current', () => { + const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT, 'GLM-5.3-flash') + expect(parsed.currentModelId).toBe('GLM-5.3-flash') + }) + + it('parses a bare models map', () => { + const output = JSON.stringify({ + models: { + 'alias-a': { provider: 'p1', displayName: 'Model A' }, + 'alias-b': { provider: 'p2' } + } + }) + const parsed = parseKimiProviderListOutput(output) + expect(parsed.availableModels.map((model) => model.modelId).sort()).toEqual(['alias-a', 'alias-b']) + }) + + it('parses an array of model entries', () => { + const output = JSON.stringify([ + { alias: 'alias-a', displayName: 'Model A', provider: 'p1', apiKey: 'should-not-leak' }, + { modelId: 'alias-b', name: 'Model B' } + ]) + const parsed = parseKimiProviderListOutput(output) + expect(parsed.availableModels).toEqual([ + { modelId: 'alias-b', name: 'Model B' }, + { modelId: 'alias-a', name: 'Model A', provider: 'p1' } + ]) + expect(JSON.stringify(parsed)).not.toContain('should-not-leak') + }) + + it('parses providers with nested models', () => { + const output = JSON.stringify({ + providers: { + p1: { apiKey: 'secret', models: { 'alias-a': { displayName: 'Model A' } } } + } + }) + const parsed = parseKimiProviderListOutput(output) + expect(parsed.availableModels).toEqual([ + { modelId: 'alias-a', name: 'Model A', provider: undefined } + ]) + expect(JSON.stringify(parsed)).not.toContain('secret') + }) + + it('tolerates leading non-JSON output', () => { + const parsed = parseKimiProviderListOutput(`some banner\n${PROVIDER_LIST_OUTPUT}`) + expect(parsed.availableModels).toHaveLength(4) + }) + + it('falls back to the object key when no alias field exists', () => { + const output = JSON.stringify({ models: { 'key-alias': { model: 'upstream/id' } } }) + const parsed = parseKimiProviderListOutput(output) + expect(parsed.availableModels[0]?.modelId).toBe('key-alias') + // The upstream provider model id is not the alias and must not be used as value. + expect(parsed.availableModels[0]).not.toHaveProperty('modelId', 'upstream/id') + }) + + it('throws on output without JSON', () => { + expect(() => parseKimiProviderListOutput('no json here')).toThrow('no JSON output') + }) + + it('throws on invalid JSON', () => { + expect(() => parseKimiProviderListOutput('{"models":')).toThrow('invalid JSON output') + }) + + it('deduplicates models across shapes', () => { + const output = JSON.stringify({ + models: { 'alias-a': { provider: 'p1' } }, + providers: { p1: { models: { 'alias-a': { displayName: 'dup' } } } } + }) + const parsed = parseKimiProviderListOutput(output) + expect(parsed.availableModels).toHaveLength(1) + }) +}) diff --git a/cli/src/modules/common/kimiModels.ts b/cli/src/modules/common/kimiModels.ts new file mode 100644 index 00000000..9de7a6bf --- /dev/null +++ b/cli/src/modules/common/kimiModels.ts @@ -0,0 +1,223 @@ +import { spawn } from 'node:child_process' +import { getAgentLaunchCommand } from '@/agent/agentLaunchCommand' +import { asString, isObject } from '@hapi/protocol' +import type { KimiModelSummary, KimiModelsResponse } from '@hapi/protocol/apiTypes' +import { readKimiLocalConfig } from '@/kimi/utils/config' +import { logger } from '@/ui/logger' +import { getErrorMessage } from './rpcResponses' + +export interface ListKimiModelsForCwdRequest { + cwd?: string +} + +export type ListKimiModelsForCwdResponse = KimiModelsResponse + +interface CacheEntry { + expiresAt: number + response: ListKimiModelsForCwdResponse +} + +const CACHE_TTL_MS = 60_000 +const PROBE_TIMEOUT_MS = 15_000 +const cache = new Map() +const inflight = new Map>() + +export function buildKimiProviderListArgs(): string[] { + return ['provider', 'list', '--json'] +} + +/** + * Extract only the fields HAPI is allowed to transmit. Everything else in the + * `kimi provider list --json` output (api keys, base urls, upstream model ids, + * context sizes) stays on the machine. + */ +function normalizeModelEntry(entry: Record, keyAlias: string | null): KimiModelSummary | null { + const modelId = asString(entry.modelId) + ?? asString(entry.alias) + ?? asString(entry.id) + ?? keyAlias + if (!modelId) return null + const name = asString(entry.displayName) ?? asString(entry.name) ?? undefined + const provider = asString(entry.provider) ?? undefined + return { + modelId, + ...(name ? { name } : {}), + ...(provider ? { provider } : {}) + } +} + +/** + * Parse `kimi provider list --json`. Handles the real shape + * `{ providers: {...}, models: { "": { provider, displayName, ... } } }` + * plus tolerant variants: a bare `models` map, an array of model entries, and + * a `providers` map whose entries carry nested `models`. Only whitelisted + * fields are returned, so secrets in the payload can never leak through. + */ +export function parseKimiProviderListOutput( + output: string, + defaultModel?: string +): { + availableModels: KimiModelSummary[] + currentModelId: string | null +} { + const availableModels: KimiModelSummary[] = [] + const seen = new Set() + + const push = (entry: Record, keyAlias: string | null) => { + const model = normalizeModelEntry(entry, keyAlias) + if (!model || seen.has(model.modelId)) return + seen.add(model.modelId) + availableModels.push(model) + } + + const jsonStart = output.indexOf('{') + const arrayStart = output.indexOf('[') + const start = jsonStart === -1 + ? arrayStart + : arrayStart !== -1 && arrayStart < jsonStart ? arrayStart : jsonStart + if (start === -1) { + throw new Error('kimi provider list produced no JSON output') + } + let data: unknown + try { + data = JSON.parse(output.slice(start)) + } catch { + throw new Error('kimi provider list produced invalid JSON output') + } + + const collectModelMap = (value: unknown) => { + if (!isObject(value)) return + for (const [alias, entry] of Object.entries(value)) { + if (isObject(entry)) push(entry, alias) + } + } + + if (Array.isArray(data)) { + for (const entry of data) { + if (isObject(entry)) push(entry, null) + } + } else if (isObject(data)) { + collectModelMap(data.models) + if (availableModels.length === 0 && isObject(data.providers)) { + for (const providerEntry of Object.values(data.providers)) { + if (!isObject(providerEntry)) continue + if (isObject(providerEntry.models)) { + collectModelMap(providerEntry.models) + } else { + push(providerEntry, null) + } + } + } + } + + availableModels.sort((a, b) => { + const providerOrder = (a.provider ?? '').localeCompare(b.provider ?? '') + return providerOrder !== 0 ? providerOrder : a.modelId.localeCompare(b.modelId) + }) + + const currentModelId = defaultModel?.trim() || null + return { availableModels, currentModelId } +} + +function describeProbeExit(code: number | null, signal: NodeJS.Signals | null): string { + if (signal) return `kimi provider list was terminated by ${signal}` + return `kimi provider list exited with code ${code}` +} + +async function runKimiProviderListProbe(): Promise { + return await new Promise((resolve, reject) => { + const child = spawn(getAgentLaunchCommand('kimi'), buildKimiProviderListArgs(), { + env: process.env, + stdio: ['ignore', 'pipe', 'pipe'], + shell: process.platform === 'win32', + windowsHide: process.platform === 'win32' + }) + let stdout = '' + let stderr = '' + let settled = false + + // Exactly one of timeout / spawn error / close settles the probe, and + // the settling work is wrapped: a throw from an event callback would + // otherwise escape this promise and reach the runner's + // uncaughtException shutdown handler instead of the caller's catch. + const settle = (outcome: () => void) => { + if (settled) return + settled = true + clearTimeout(timeout) + try { + outcome() + } catch (error) { + reject(error) + } + } + + const timeout = setTimeout(() => { + settle(() => { + try { + child.kill('SIGTERM') + } catch (error) { + logger.debug('Failed to kill the Kimi model discovery probe:', error) + } + reject(new Error('Kimi model discovery timed out')) + }) + }, PROBE_TIMEOUT_MS) + + child.stdout?.on('data', (chunk) => { + stdout += chunk.toString() + }) + child.stderr?.on('data', (chunk) => { + stderr += chunk.toString() + }) + child.on('error', (error) => { + settle(() => reject(error)) + }) + // Parse on 'close', not 'exit': stdio must be drained first, and the + // parser runs inside settle() so malformed output rejects the probe. + child.on('close', (code, signal) => { + settle(() => { + if (code !== 0) { + reject(new Error(stderr.trim() || describeProbeExit(code, signal))) + return + } + const defaultModel = readKimiLocalConfig().model + resolve({ success: true, ...parseKimiProviderListOutput(stdout, defaultModel) }) + }) + }) + }) +} + +export async function listKimiModelsForCwd(cwd: string): Promise { + const trimmed = cwd?.trim() + if (!trimmed) return { success: false, error: 'cwd is required' } + + const cached = cache.get(trimmed) + if (cached && cached.expiresAt > Date.now()) return cached.response + + const running = inflight.get(trimmed) + if (running) return running + + const promise = (async () => { + try { + const response = await runKimiProviderListProbe() + if (response.success) { + cache.set(trimmed, { expiresAt: Date.now() + CACHE_TTL_MS, response }) + } + return response + } catch (error) { + return { + success: false, + error: getErrorMessage(error, 'Failed to discover Kimi models') + } + } finally { + inflight.delete(trimmed) + } + })() + + inflight.set(trimmed, promise) + return promise +} + +export function _resetKimiModelsCacheForTests(): void { + cache.clear() + inflight.clear() +} diff --git a/cli/src/modules/common/kimiModelsProbe.test.ts b/cli/src/modules/common/kimiModelsProbe.test.ts new file mode 100644 index 00000000..3fa9d00d --- /dev/null +++ b/cli/src/modules/common/kimiModelsProbe.test.ts @@ -0,0 +1,175 @@ +import { EventEmitter } from 'node:events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { spawnMock, configState } = vi.hoisted(() => ({ + spawnMock: vi.fn(), + configState: { read: (() => ({ model: 'GLM-5.3-flash' })) as () => { model?: string } } +})) + +vi.mock('node:child_process', () => ({ spawn: spawnMock })) +vi.mock('@/ui/logger', () => ({ + logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() } +})) +vi.mock('@/kimi/utils/config', () => ({ + readKimiLocalConfig: () => configState.read() +})) + +import { _resetKimiModelsCacheForTests, listKimiModelsForCwd } from './kimiModels' + +class FakeChild extends EventEmitter { + stdout = new EventEmitter() + stderr = new EventEmitter() + kill = vi.fn() +} + +const MALFORMED_OUTPUT = '{"models":' + +function startProbe(cwd: string) { + const child = new FakeChild() + spawnMock.mockImplementation(() => child) + return { child, pending: listKimiModelsForCwd(cwd) } +} + +beforeEach(() => { + spawnMock.mockReset() + configState.read = () => ({ model: 'GLM-5.3-flash' }) + _resetKimiModelsCacheForTests() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('Kimi provider list probe settlement', () => { + it('reports malformed JSON at exit code 0 as a failure instead of throwing out of the callback', async () => { + const { child, pending } = startProbe('/tmp/kimi-probe-malformed') + + child.stdout.emit('data', MALFORMED_OUTPUT) + child.emit('exit', 0, null) + child.emit('close', 0, null) + + await expect(pending).resolves.toEqual({ + success: false, + error: 'kimi provider list produced invalid JSON output' + }) + }) + + it('reports missing JSON output as a failure', async () => { + const { child, pending } = startProbe('/tmp/kimi-probe-no-json') + + child.stdout.emit('data', 'no json here') + child.emit('close', 0, null) + + await expect(pending).resolves.toEqual({ + success: false, + error: 'kimi provider list produced no JSON output' + }) + }) + + it('contains a throwing local-config read inside the probe promise', async () => { + configState.read = () => { + throw new Error('kimi config unreadable') + } + const { child, pending } = startProbe('/tmp/kimi-probe-config-throws') + + child.stdout.emit('data', JSON.stringify({ models: { 'alias-a': {} } })) + child.emit('close', 0, null) + + await expect(pending).resolves.toEqual({ + success: false, + error: 'kimi config unreadable' + }) + }) + + it('parses stdout that arrives after exit but before close', async () => { + const { child, pending } = startProbe('/tmp/kimi-probe-late-stdout') + + child.emit('exit', 0, null) + child.stdout.emit('data', JSON.stringify({ + models: { + 'late-alias': { provider: 'p1', displayName: 'Late Model' } + } + })) + child.emit('close', 0, null) + + await expect(pending).resolves.toEqual({ + success: true, + availableModels: [{ modelId: 'late-alias', name: 'Late Model', provider: 'p1' }], + currentModelId: 'GLM-5.3-flash' + }) + }) + + it('keeps a non-zero exit a failure and prefers stderr', async () => { + const { child, pending } = startProbe('/tmp/kimi-probe-exit-1') + + child.stderr.emit('data', 'provider list unavailable\n') + child.emit('close', 1, null) + + await expect(pending).resolves.toEqual({ + success: false, + error: 'provider list unavailable' + }) + }) + + it('keeps a non-zero exit a failure when stderr is empty', async () => { + const { child, pending } = startProbe('/tmp/kimi-probe-exit-2') + + child.emit('close', 2, null) + + await expect(pending).resolves.toEqual({ + success: false, + error: 'kimi provider list exited with code 2' + }) + }) + + it('names the terminating signal when the probe dies without an exit code', async () => { + const { child, pending } = startProbe('/tmp/kimi-probe-signaled') + + child.emit('close', null, 'SIGKILL') + + await expect(pending).resolves.toEqual({ + success: false, + error: 'kimi provider list was terminated by SIGKILL' + }) + }) + + it('times the probe out and kills the child', async () => { + vi.useFakeTimers() + const { child, pending } = startProbe('/tmp/kimi-probe-timeout') + + await vi.advanceTimersByTimeAsync(15_000) + + await expect(pending).resolves.toEqual({ + success: false, + error: 'Kimi model discovery timed out' + }) + expect(child.kill).toHaveBeenCalledWith('SIGTERM') + }) + + it('lets the first settlement win when an error is followed by a successful close', async () => { + const { child, pending } = startProbe('/tmp/kimi-probe-error-then-close') + + child.emit('error', new Error('spawn kimi ENOENT')) + child.stdout.emit('data', JSON.stringify({ models: { 'alias-a': {} } })) + child.emit('close', 0, null) + + await expect(pending).resolves.toEqual({ + success: false, + error: 'spawn kimi ENOENT' + }) + }) + + it('ignores a second close after the probe already settled', async () => { + const { child, pending } = startProbe('/tmp/kimi-probe-double-close') + + child.stdout.emit('data', JSON.stringify({ models: { 'alias-a': { displayName: 'A' } } })) + child.emit('close', 0, null) + child.emit('close', 1, null) + + await expect(pending).resolves.toEqual({ + success: true, + availableModels: [{ modelId: 'alias-a', name: 'A' }], + currentModelId: 'GLM-5.3-flash' + }) + }) +}) diff --git a/cli/src/modules/common/registerCommonHandlers.ts b/cli/src/modules/common/registerCommonHandlers.ts index 88f4ee2e..d00826b8 100644 --- a/cli/src/modules/common/registerCommonHandlers.ts +++ b/cli/src/modules/common/registerCommonHandlers.ts @@ -8,6 +8,7 @@ import { registerOpencodeModelVariantsHandlers } from './handlers/opencodeModelV import { registerPiModelHandlers } from './handlers/piModels' import { registerGrokModelHandlers } from './handlers/grokModels' import { registerCopilotModelHandlers } from './handlers/copilotModels' +import { registerKimiModelHandlers } from './handlers/kimiModels' import { registerDirectoryHandlers } from './handlers/directories' import { registerDifftasticHandlers } from './handlers/difftastic' import { registerFileHandlers } from './handlers/files' @@ -27,6 +28,7 @@ export function registerCommonHandlers(rpcHandlerManager: RpcHandlerManager, wor registerPiModelHandlers(rpcHandlerManager) registerGrokModelHandlers(rpcHandlerManager) registerCopilotModelHandlers(rpcHandlerManager) + registerKimiModelHandlers(rpcHandlerManager) registerFileHandlers(rpcHandlerManager, workingDirectory) registerDirectoryHandlers(rpcHandlerManager, workingDirectory) registerRipgrepHandlers(rpcHandlerManager, workingDirectory) diff --git a/docs/api/client-contract/rest.md b/docs/api/client-contract/rest.md index 247e63be..188ba740 100644 --- a/docs/api/client-contract/rest.md +++ b/docs/api/client-contract/rest.md @@ -138,10 +138,10 @@ The configuration routes in the table above respond `{ok: true}`; apply-failures | Method & path | Notes | |---|---| -| `GET /api/sessions/:id/codex-models`, `/opencode-models`, `/cursor-models`, `/grok-models`, `/copilot-models`, `/pi-models` | Active session of the matching flavor; 400 otherwise | +| `GET /api/sessions/:id/codex-models`, `/opencode-models`, `/cursor-models`, `/grok-models`, `/copilot-models`, `/kimi-models`, `/pi-models` | Active session of the matching flavor; 400 otherwise | | `GET /api/sessions/:id/opencode-reasoning-effort-options`, `/grok-reasoning-effort-options` | Same pattern | | `GET /api/machines/:id/agy-models`, `/pi-models`, `/codex-models`, `/cursor-models` | Machine-level (pre-spawn pickers). `agy-models` takes `?refresh=true` to skip the machine's cached catalog, and may answer `success: true` with an advisory `error` (see [Errors](./errors.md#rpc-wrapped-endpoints)) | -| `GET /api/machines/:id/opencode-models?cwd=`, `/grok-models?cwd=`, `/copilot-models?cwd=` | `cwd` query required (400 without) | +| `GET /api/machines/:id/opencode-models?cwd=`, `/grok-models?cwd=`, `/copilot-models?cwd=`, `/kimi-models?cwd=` | `cwd` query required (400 without) | ### Machines & spawning diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index fc4112ba..f8e74e13 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -23,6 +23,7 @@ import type { ImplementCodexPlanResult, CopilotModelsResponse, GrokModelsResponse, + KimiModelsResponse, GrokReasoningEffortResponse, ListDirectoryResponse, ListCodexSessionsRpcResponse, @@ -113,6 +114,7 @@ export type RpcListOpencodeModelsResponse = OpencodeModelsResponse export type RpcListOpencodeModelVariantsResponse = OpencodeModelVariantsResponse export type RpcListGrokModelsResponse = GrokModelsResponse export type RpcListCopilotModelsResponse = CopilotModelsResponse +export type RpcListKimiModelsResponse = KimiModelsResponse export type RpcListGrokReasoningEffortOptionsResponse = GrokReasoningEffortResponse export type RpcListOpencodeReasoningEffortOptionsResponse = OpencodeReasoningEffortResponse export type RpcListAgyModelsResponse = AgyModelsResponse @@ -484,6 +486,28 @@ export class RpcGateway { ) as RpcListCopilotModelsResponse } + async listKimiModelsForCwd(machineId: string, cwd: string): Promise { + return await this.machineRpc( + machineId, + RPC_METHODS.ListKimiModelsForCwd, + { cwd }, + MODEL_LIST_RPC_TIMEOUT_MS + ) as RpcListKimiModelsResponse + } + + /** + * Active-session Kimi discovery. The probe runs in the CLI that owns the + * session, so it works without a background runner on the machine. + */ + async listKimiModelsForSession(sessionId: string): Promise { + return await this.sessionRpc( + sessionId, + RPC_METHODS.ListKimiModels, + {}, + MODEL_LIST_RPC_TIMEOUT_MS + ) as RpcListKimiModelsResponse + } + /** Generic Pi RPC call — routes all Pi-specific session RPCs through * a single entry point instead of per-method wrappers. */ async callPiRpc(sessionId: string, method: string, params?: Record, timeoutMs?: number): Promise { diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 607c26e6..56552ed8 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -52,6 +52,7 @@ import { type RpcListOpencodeModelVariantsResponse, type RpcListGrokModelsResponse, type RpcListCopilotModelsResponse, + type RpcListKimiModelsResponse, type RpcListGrokReasoningEffortOptionsResponse, type RpcListOpencodeReasoningEffortOptionsResponse, type RpcCursorModel, @@ -86,6 +87,7 @@ export type { RpcListOpencodeModelVariantsResponse, RpcListGrokModelsResponse, RpcListCopilotModelsResponse, + RpcListKimiModelsResponse, RpcListGrokReasoningEffortOptionsResponse, RpcListOpencodeReasoningEffortOptionsResponse, RpcCursorModel, @@ -4067,6 +4069,14 @@ export class SyncEngine { return await this.rpcGateway.listCopilotModelsForSession(sessionId) } + async listKimiModelsForCwd(machineId: string, cwd: string): Promise { + return await this.rpcGateway.listKimiModelsForCwd(machineId, cwd) + } + + async listKimiModelsForSession(sessionId: string): Promise { + return await this.rpcGateway.listKimiModelsForSession(sessionId) + } + /** Generic Pi RPC — delegates to rpcGateway.callPiRpc. */ async callPiRpc(sessionId: string, method: string, params?: Record, timeoutMs?: number): Promise { return await this.rpcGateway.callPiRpc(sessionId, method, params, timeoutMs) diff --git a/hub/src/web/routes/machines.ts b/hub/src/web/routes/machines.ts index 5a98356a..b300f0a4 100644 --- a/hub/src/web/routes/machines.ts +++ b/hub/src/web/routes/machines.ts @@ -366,6 +366,31 @@ export function createMachinesRoutes(getSyncEngine: () => SyncEngine | null): Ho } }) + app.get('/machines/:id/kimi-models', async (c) => { + const engine = getSyncEngine() + if (!engine) { + return c.json({ success: false, error: 'Not connected' }, 503) + } + + const machineId = c.req.param('id') + const machine = requireMachine(c, engine, machineId) + if (machine instanceof Response) return machine + + const cwd = (c.req.query('cwd') ?? '').trim() + if (!cwd) { + return c.json({ success: false, error: 'cwd query parameter is required' }, 400) + } + + try { + return c.json(await engine.listKimiModelsForCwd(machineId, cwd)) + } catch (error) { + return c.json({ + success: false, + error: error instanceof Error ? error.message : 'Failed to list Kimi models' + }, 500) + } + }) + app.get('/machines/:id/copilot-models', async (c) => { const engine = getSyncEngine() if (!engine) { diff --git a/hub/src/web/routes/sessions.test.ts b/hub/src/web/routes/sessions.test.ts index 8e6afbf7..f82520f7 100644 --- a/hub/src/web/routes/sessions.test.ts +++ b/hub/src/web/routes/sessions.test.ts @@ -118,6 +118,17 @@ function createApp(session: Session, opts?: { options: [{ value: 'low', name: 'Low' }], currentValue: 'low' }) + const listKimiModelsForSession = async () => ({ + success: true, + availableModels: [ + { + modelId: 'GLM-5.3-flash', + name: 'thehive / GLM-5.3-flash', + provider: 'thehive' + } + ], + currentModelId: 'GLM-5.3-flash' + }) const resumeSession = opts?.resumeSession ?? (async (sessionId: string) => ({ type: 'success', sessionId })) const reopenSession = opts?.reopenSession ?? (async (sessionId: string) => ({ type: 'success' as const, @@ -140,6 +151,7 @@ function createApp(session: Session, opts?: { listOpencodeReasoningEffortOptionsForSession, listGrokModelsForSession, listGrokReasoningEffortOptionsForSession, + listKimiModelsForSession, resumeSession, reopenSession, getCursorChatStoreStatus: opts?.getCursorChatStoreStatus ?? (async () => ({ @@ -999,6 +1011,40 @@ describe('sessions routes', () => { }) }) + it('returns the Kimi catalog for an active Kimi session over its own connection', async () => { + const session = createSession({ + metadata: { path: '/tmp/project', host: 'localhost', flavor: 'kimi' } + }) + const { app } = createApp(session) + + const response = await app.request('/api/sessions/session-1/kimi-models') + + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ + success: true, + availableModels: [ + { + modelId: 'GLM-5.3-flash', + name: 'thehive / GLM-5.3-flash', + provider: 'thehive' + } + ], + currentModelId: 'GLM-5.3-flash' + }) + }) + + it('rejects kimi-models for non-Kimi sessions', async () => { + const { app } = createApp(createSession()) + + const response = await app.request('/api/sessions/session-1/kimi-models') + + expect(response.status).toBe(400) + expect(await response.json()).toEqual({ + success: false, + error: 'Kimi models are only available for Kimi sessions' + }) + }) + it('rejects opencode-reasoning-effort-options for non-OpenCode sessions', async () => { const { app } = createApp(createSession()) diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index dfb21d44..4fc91066 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -1510,6 +1510,24 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho } }) + app.get('/sessions/:id/kimi-models', async (c) => { + const engine = requireSyncEngine(c, getSyncEngine) + if (engine instanceof Response) return engine + const sessionResult = requireSessionFromParam(c, engine, { requireActive: true }) + if (sessionResult instanceof Response) return sessionResult + if (sessionResult.session.metadata?.flavor !== 'kimi') { + return c.json({ success: false, error: 'Kimi models are only available for Kimi sessions' }, 400) + } + try { + return c.json(await engine.listKimiModelsForSession(sessionResult.sessionId)) + } catch (error) { + return c.json({ + success: false, + error: error instanceof Error ? error.message : 'Failed to list Kimi models' + }, 500) + } + }) + app.get('/sessions/:id/cursor-models', async (c) => { const engine = requireSyncEngine(c, getSyncEngine) if (engine instanceof Response) { diff --git a/shared/src/agentConfig.ts b/shared/src/agentConfig.ts index a5d2ce83..4db886a8 100644 --- a/shared/src/agentConfig.ts +++ b/shared/src/agentConfig.ts @@ -75,7 +75,7 @@ const BUILTIN_DESCRIPTORS: Record = { { id: 'effort', section: 'effort', kind: 'select', optionSource: 'model', availability: 'both' }, PERMISSION ), - kimi: fields(MODEL, PERMISSION), + kimi: fields({ ...MODEL, optionSource: 'directory' }, PERMISSION), opencode: fields( { ...MODEL, optionSource: 'directory' }, { id: 'effort', section: 'effort', kind: 'select', optionSource: 'model', availability: 'both' }, diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index d45fd7e4..50a707db 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -838,6 +838,22 @@ export type CopilotModelsResponse = { export type ListCopilotModelsResponse = CopilotModelsResponse +export type KimiModelSummary = { + /** Kimi model alias as used by `--model` / `session/set_model`. */ + modelId: string + name?: string + provider?: string +} + +export type KimiModelsResponse = { + success: boolean + availableModels?: KimiModelSummary[] + currentModelId?: string | null + error?: string +} + +export type ListKimiModelsResponse = KimiModelsResponse + export type GrokReasoningEffortResponse = { success: boolean options?: GrokReasoningEffortOption[] diff --git a/shared/src/rpcMethods.ts b/shared/src/rpcMethods.ts index 1ad52370..9bdb63bd 100644 --- a/shared/src/rpcMethods.ts +++ b/shared/src/rpcMethods.ts @@ -43,6 +43,8 @@ export const RPC_METHODS = { ListGrokReasoningEffortOptions: 'listGrokReasoningEffortOptions', ListCopilotModelsForCwd: 'listCopilotModelsForCwd', ListCopilotModels: 'listCopilotModels', + ListKimiModelsForCwd: 'listKimiModelsForCwd', + ListKimiModels: 'listKimiModels', ListOpencodeReasoningEffortOptions: 'listOpencodeReasoningEffortOptions', ListAgyModels: 'listAgyModels', /** Deliver one queued message into the active Pi turn (native steer). */ diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts index 22802f26..b84d17df 100644 --- a/web/src/api/client.test.ts +++ b/web/src/api/client.test.ts @@ -329,3 +329,33 @@ describe('ApiClient error mapping', () => { expect(init?.body).toBe(JSON.stringify({ openai: 'sk-test' })) }) }) + +describe('ApiClient Kimi session model discovery', () => { + let originalFetch: typeof globalThis.fetch + let fetchMock: ReturnType + + beforeEach(() => { + originalFetch = globalThis.fetch + fetchMock = vi.fn() + globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch + }) + + afterEach(() => { + globalThis.fetch = originalFetch + }) + + it('requests the running session instead of the machine kimi-models endpoint', async () => { + const catalog = { + success: true, + availableModels: [ + { modelId: 'GLM-5.3-flash', name: 'thehive / GLM-5.3-flash', provider: 'thehive' } + ], + currentModelId: 'GLM-5.3-flash' + } + fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(catalog), { status: 200 })) + + const api = new ApiClient('test-token') + await expect(api.getSessionKimiModels('session/1')).resolves.toEqual(catalog) + expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/sessions/session%2F1/kimi-models') + }) +}) diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 625aec75..5010d101 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -42,6 +42,7 @@ import type { FileReadResponse, GitCommandResponse, GrokModelsResponse, + KimiModelsResponse, CopilotModelsResponse, GrokReasoningEffortResponse, ListDirectoryResponse, @@ -953,6 +954,18 @@ export class ApiClient { ) } + async getMachineKimiModelsForCwd(machineId: string, cwd: string): Promise { + return await this.request( + `/api/machines/${encodeURIComponent(machineId)}/kimi-models?cwd=${encodeURIComponent(cwd)}` + ) + } + + async getSessionKimiModels(sessionId: string): Promise { + return await this.request( + `/api/sessions/${encodeURIComponent(sessionId)}/kimi-models` + ) + } + async getSessionGrokModels(sessionId: string): Promise { return await this.request( `/api/sessions/${encodeURIComponent(sessionId)}/grok-models` diff --git a/web/src/components/AssistantChat/modelOptions.test.ts b/web/src/components/AssistantChat/modelOptions.test.ts index e4cb4410..1360f04a 100644 --- a/web/src/components/AssistantChat/modelOptions.test.ts +++ b/web/src/components/AssistantChat/modelOptions.test.ts @@ -353,6 +353,24 @@ describe('getNextModelForFlavor', () => { expect(getNextModelForFlavor('kimi', null)).toBeNull() }) + it('serves dynamic Kimi options to a running session with Default and aliases', () => { + const options = getModelOptionsForFlavor('kimi', 'GLM-5.3-flash', [ + { value: null, label: 'Default' }, + { value: 'GLM-5.3-flash', label: 'thehive — thehive / GLM-5.3-flash' }, + { value: 'deepseek-v4.1-flash', label: 'thehive — thehive / hive-deepseek' } + ]) + + expect(options[0]).toEqual({ value: null, label: 'Default' }) + expect(options.map((option) => option.value)).toEqual([null, 'GLM-5.3-flash', 'deepseek-v4.1-flash']) + + // Cycling with a dynamic catalog moves through the discovered aliases. + expect(getNextModelForFlavor('kimi', 'GLM-5.3-flash', [ + { value: null, label: 'Default' }, + { value: 'GLM-5.3-flash', label: 'thehive — GLM-5.3-flash' }, + { value: 'deepseek-v4.1-flash', label: 'thehive — deepseek-v4.1-flash' } + ])).toBe('deepseek-v4.1-flash') + }) + it('keeps a cursor current model on cycle (no Claude fallback)', () => { expect(getNextModelForFlavor('cursor', 'composer-2.5')).toBe('composer-2.5') expect(getNextModelForFlavor('cursor', null)).toBeNull() diff --git a/web/src/components/NewSession/grokModels.test.ts b/web/src/components/NewSession/grokModels.test.ts index 175f1837..ae3a2037 100644 --- a/web/src/components/NewSession/grokModels.test.ts +++ b/web/src/components/NewSession/grokModels.test.ts @@ -1,5 +1,12 @@ import { describe, expect, it } from 'vitest' -import { buildGrokEffortOptions, buildGrokModelOptions, shouldEnableGrokModelDiscovery } from './grokModels' +import { + buildGrokEffortOptions, + buildGrokModelOptions, + shouldEnableGrokModelDiscovery, + buildKimiModelOptions, + buildKimiSessionModelOptions, + shouldEnableKimiModelDiscovery +} from './grokModels' describe('Grok Create-session options', () => { it('enables model discovery only for an existing cwd on the target machine', () => { @@ -40,3 +47,63 @@ describe('Grok Create-session options', () => { ]) }) }) + +describe('Kimi Create-session options', () => { + it('enables model discovery only for an existing cwd on the target machine', () => { + const args = { + agent: 'kimi' as const, + machineId: 'machine-1', + cwd: '/home/user/project', + cwdExists: true, + } + + expect(shouldEnableKimiModelDiscovery(args)).toBe(true) + expect(shouldEnableKimiModelDiscovery({ ...args, cwdExists: undefined })).toBe(false) + expect(shouldEnableKimiModelDiscovery({ ...args, agent: 'claude' })).toBe(false) + }) + + it('keeps Default and appends every discovered Kimi model with the real alias as value', () => { + const options = buildKimiModelOptions([ + { modelId: 'GLM-5.3-flash', name: 'thehive / GLM-5.3-flash', provider: 'thehive' }, + { modelId: 'deepseek-v4.1-flash', name: 'thehive / hive-deepseek', provider: 'thehive' }, + { modelId: 'hyper-glm-5.3-flash', name: 'charm-hyper / Hyper · GLM-5.3-Flash', provider: 'charm-hyper' }, + { modelId: 'openrouter-union-alpha', provider: 'openrouter' } + ]) + + expect(options[0]).toEqual({ value: 'auto', label: 'Default' }) + expect(options.map((option) => option.value)).toEqual([ + 'auto', + 'GLM-5.3-flash', + 'deepseek-v4.1-flash', + 'hyper-glm-5.3-flash', + 'openrouter-union-alpha' + ]) + }) + + it('makes providers recognizable in labels', () => { + const options = buildKimiModelOptions([ + { modelId: 'GLM-5.3-flash', name: 'thehive / GLM-5.3-flash', provider: 'thehive' }, + { modelId: 'openrouter-union-alpha', provider: 'openrouter' } + ]) + + expect(options[1]).toEqual({ value: 'GLM-5.3-flash', label: 'thehive — thehive / GLM-5.3-flash' }) + expect(options[2]).toEqual({ value: 'openrouter-union-alpha', label: 'openrouter — openrouter-union-alpha' }) + }) + + it('falls back to the alias when a model has no display name or provider', () => { + expect(buildKimiModelOptions([{ modelId: 'alias-only' }])).toEqual([ + { value: 'auto', label: 'Default' }, + { value: 'alias-only', label: 'alias-only' } + ]) + }) + + it('running-session options keep Default as null and aliases as values', () => { + const options = buildKimiSessionModelOptions([ + { modelId: 'GLM-5.3-flash', provider: 'thehive' }, + { modelId: 'deepseek-v4.1-flash', provider: 'thehive' } + ]) + + expect(options[0]).toEqual({ value: null, label: 'Default' }) + expect(options.map((option) => option.value)).toEqual([null, 'GLM-5.3-flash', 'deepseek-v4.1-flash']) + }) +}) diff --git a/web/src/components/NewSession/grokModels.ts b/web/src/components/NewSession/grokModels.ts index 5b800a9c..67806201 100644 --- a/web/src/components/NewSession/grokModels.ts +++ b/web/src/components/NewSession/grokModels.ts @@ -1,4 +1,4 @@ -import type { GrokModelSummary } from '@/types/api' +import type { GrokModelSummary, KimiModelSummary } from '@/types/api' import type { AgentType } from './types' export function shouldEnableGrokModelDiscovery(args: { @@ -48,3 +48,49 @@ export function buildGrokEffortOptions( })) ] } + +export function shouldEnableKimiModelDiscovery(args: { + agent: AgentType + machineId: string | null + cwd: string + cwdExists: boolean | undefined +}): boolean { + return args.agent === 'kimi' + && Boolean(args.machineId) + && args.cwd.length > 0 + && args.cwdExists === true +} + +/** + * Kimi options for the create-session selector: Default plus one entry per + * discovered provider model. `value` is always the real Kimi alias; the label + * makes the provider recognizable ("TheHive — GLM-5.3-flash"). + */ +export function buildKimiModelOptions( + availableModels: KimiModelSummary[] +): Array<{ value: string; label: string }> { + return [ + { value: 'auto', label: 'Default' }, + ...availableModels.map((model) => ({ + value: model.modelId, + label: model.provider ? `${model.provider} — ${model.name ?? model.modelId}` : (model.name ?? model.modelId) + })) + ] +} + +/** + * Options for a running Kimi session's model picker: Default (null value, + * cleared via session/set_model) plus the dynamically discovered models. + * Labels match buildKimiModelOptions so both pickers read the same. + */ +export function buildKimiSessionModelOptions( + availableModels: KimiModelSummary[] +): Array<{ value: string | null; label: string }> { + return [ + { value: null, label: 'Default' }, + ...availableModels.map((model) => ({ + value: model.modelId, + label: model.provider ? `${model.provider} — ${model.name ?? model.modelId}` : (model.name ?? model.modelId) + })) + ] +} diff --git a/web/src/components/NewSession/index.test.tsx b/web/src/components/NewSession/index.test.tsx index b5cce30e..e6d0c2ed 100644 --- a/web/src/components/NewSession/index.test.tsx +++ b/web/src/components/NewSession/index.test.tsx @@ -24,6 +24,9 @@ const mocks = vi.hoisted(() => ({ directoryExists: undefined as boolean | undefined, copilotModels: [] as Array<{ modelId: string; name?: string }>, copilotModelsLoading: false, + kimiModels: [] as Array<{ modelId: string; name?: string; provider?: string }>, + kimiModelsLoading: false, + kimiModelsError: null as string | null, opencodeModels: [] as Array<{ modelId: string; name?: string }>, opencodeCurrentModelId: null as string | null, opencodeModelsLoading: false, @@ -163,6 +166,14 @@ vi.mock('@/hooks/queries/useCopilotModelsForCwd', () => ({ error: null }) })) +vi.mock('@/hooks/queries/useKimiModelsForCwd', () => ({ + useKimiModelsForCwd: () => ({ + availableModels: mocks.kimiModels, + currentModelId: null, + isLoading: mocks.kimiModelsLoading, + error: mocks.kimiModelsError + }) +})) vi.mock('@/hooks/queries/usePiModelsForMachine', () => ({ usePiModelsForMachine: () => ({ availableModels: mocks.piModels, @@ -300,6 +311,9 @@ describe('NewSession launch preferences', () => { mocks.directoryExists = true mocks.copilotModels = [] mocks.copilotModelsLoading = false + mocks.kimiModels = [] + mocks.kimiModelsLoading = false + mocks.kimiModelsError = null mocks.opencodeModels = [{ modelId: 'provider/current', name: 'Current' }] mocks.opencodeCurrentModelId = 'provider/current' mocks.opencodeModelsLoading = false @@ -482,6 +496,92 @@ describe('NewSession launch preferences', () => { await waitFor(() => expect(screen.getByTestId('create')).toBeDisabled()) }) + it('shows dynamic Kimi models with Default for the selected directory', async () => { + mocks.kimiModels = [ + { modelId: 'GLM-5.3-flash', name: 'thehive / GLM-5.3-flash', provider: 'thehive' }, + { modelId: 'deepseek-v4.1-flash', name: 'thehive / hive-deepseek', provider: 'thehive' }, + { modelId: 'hyper-glm-5.3-flash', name: 'charm-hyper / Hyper · GLM-5.3-Flash', provider: 'charm-hyper' }, + { modelId: 'openrouter-union-alpha', provider: 'openrouter' } + ] + + render( + {}} + /> + ) + + fireEvent.click(screen.getByDisplayValue('kimi')) + + await waitFor(() => { + expect(screen.getByTestId('model-options')).toHaveTextContent( + 'Default,thehive — thehive / GLM-5.3-flash,thehive — thehive / hive-deepseek,charm-hyper — charm-hyper / Hyper · GLM-5.3-Flash,openrouter — openrouter-union-alpha' + ) + }) + }) + + it('restores a remembered Kimi alias instead of resetting it to Default', async () => { + mocks.kimiModels = [ + { modelId: 'GLM-5.3-flash', provider: 'thehive' } + ] + savePreferredAgent('kimi') + savePreferredLaunchSettings('machine-1', 'kimi', { + model: 'GLM-5.3-flash', + cursorSelectedBase: 'auto', + effort: 'auto', + modelReasoningEffort: 'default' + }) + + render( + {}} + /> + ) + + await waitFor(() => { + expect(screen.getByTestId('model')).toHaveTextContent('GLM-5.3-flash') + expect(screen.getByTestId('create')).toBeEnabled() + }) + }) + + it('resets a remembered Kimi alias that the dynamic catalog no longer lists', async () => { + mocks.kimiModels = [ + { modelId: 'GLM-5.3-flash', provider: 'thehive' } + ] + savePreferredAgent('kimi') + savePreferredLaunchSettings('machine-1', 'kimi', { + model: 'retired-alias', + cursorSelectedBase: 'auto', + effort: 'auto', + modelReasoningEffort: 'default' + }) + + render( + {}} + /> + ) + + await waitFor(() => { + expect(screen.getByTestId('model')).toHaveTextContent('auto') + }) + expect(screen.getByTestId('create')).toBeEnabled() + }) + it.each([ ['model', 'gpt-5.6-sol', 'default'], ['reasoning effort', 'auto', 'xhigh'] diff --git a/web/src/components/NewSession/index.tsx b/web/src/components/NewSession/index.tsx index 0a9dbeec..4b80f7c5 100644 --- a/web/src/components/NewSession/index.tsx +++ b/web/src/components/NewSession/index.tsx @@ -13,6 +13,7 @@ import { useOpencodeModelsForCwd } from '@/hooks/queries/useOpencodeModelsForCwd import { useOpencodeModelVariants } from '@/hooks/queries/useOpencodeModelVariants' import { useGrokModelsForCwd } from '@/hooks/queries/useGrokModelsForCwd' import { useCopilotModelsForCwd } from '@/hooks/queries/useCopilotModelsForCwd' +import { useKimiModelsForCwd } from '@/hooks/queries/useKimiModelsForCwd' import { usePiModelsForMachine } from '@/hooks/queries/usePiModelsForMachine' import { useAgentAvailability } from '@/hooks/queries/useAgentAvailability' import { useSessions } from '@/hooks/queries/useSessions' @@ -57,6 +58,7 @@ import { OpencodeModelSelector } from './OpencodeModelSelector' import { EffortField } from './EffortField' import { shouldEnableOpencodeModelDiscovery } from './opencodeModelsGate' import { buildGrokEffortOptions, buildGrokModelOptions, shouldEnableGrokModelDiscovery } from './grokModels' +import { buildKimiModelOptions, shouldEnableKimiModelDiscovery } from './grokModels' import { groupModelsByProvider } from '@/components/AssistantChat/piModelGroups' import { isThinkingLevelSupported } from '@/components/AssistantChat/piThinkingLevelOptions' import { @@ -639,6 +641,21 @@ export function NewSession(props: { cwd: deferredDirectory, enabled: agent === 'copilot' && deferredDirectoryExists === true }) + const kimiModelsState = useKimiModelsForCwd({ + api: props.api, + machineId, + cwd: deferredDirectory, + enabled: shouldEnableKimiModelDiscovery({ + agent, + machineId, + cwd: deferredDirectory, + cwdExists: deferredDirectoryExists, + }) + }) + const kimiModelOptions = useMemo( + () => buildKimiModelOptions(kimiModelsState.availableModels), + [kimiModelsState.availableModels] + ) const copilotModelOptions = useMemo( () => [ { value: 'auto', label: 'Auto' }, @@ -929,6 +946,25 @@ export function NewSession(props: { deferredDirectoryExists, model ]) + useEffect(() => { + if ( + agent === 'kimi' + && deferredDirectoryExists === true + && !kimiModelsState.isLoading + && !kimiModelsState.error + && model !== 'auto' + && !kimiModelsState.availableModels.some((candidate) => candidate.modelId === model) + ) { + setModel('auto') + } + }, [ + agent, + kimiModelsState.availableModels, + kimiModelsState.error, + kimiModelsState.isLoading, + deferredDirectoryExists, + model + ]) const currentDirectoryExists = trimmedDirectory ? pathExistence[trimmedDirectory] : undefined const directoryOutsideWorkspaceRoots = trimmedDirectory @@ -1701,6 +1737,13 @@ export function NewSession(props: { deferredDirectoryExists === undefined || (deferredDirectoryExists === true && copilotModelsState.isLoading) )) + || (agent === 'kimi' + && deferredDirectory !== '' + && model !== 'auto' + && ( + deferredDirectoryExists === undefined + || (deferredDirectoryExists === true && kimiModelsState.isLoading) + )) || (agent === 'pi' && model !== 'auto' && piModelsState.isLoading) @@ -1888,20 +1931,24 @@ export function NewSession(props: { ? grokModelOptions : agent === 'copilot' ? copilotModelOptions - : agent === 'pi' - ? (showPiLaunchConfig ? piModelOptions : undefined) - : undefined + : agent === 'kimi' + ? kimiModelOptions + : agent === 'pi' + ? (showPiLaunchConfig ? piModelOptions : undefined) + : undefined } isDisabled={ isFormDisabled || (agent === 'codex' && Boolean(codexModelsState.error)) || (agent === 'grok' && Boolean(grokModelsState.error)) || (agent === 'copilot' && Boolean(copilotModelsState.error)) + || (agent === 'kimi' && Boolean(kimiModelsState.error)) || (agent === 'pi' && Boolean(piModelsState.error)) } isLoading={(agent === 'codex' && codexModelsState.isLoading) || (agent === 'grok' && grokModelsState.isLoading) || (agent === 'copilot' && copilotModelsState.isLoading) + || (agent === 'kimi' && kimiModelsState.isLoading) || (agent === 'pi' && piModelsState.isLoading)} error={agent === 'codex' && codexModelsState.error ? `${t('newSession.model.loadFailed')}: ${codexModelsState.error}` @@ -1909,8 +1956,10 @@ export function NewSession(props: { ? `${t('newSession.model.loadFailed')}: ${grokModelsState.error}` : agent === 'copilot' && copilotModelsState.error ? `${t('newSession.model.loadFailed')}: ${copilotModelsState.error}` - : agent === 'pi' && piModelsState.error - ? `${t('newSession.model.loadFailed')}: ${piModelsState.error}` + : agent === 'kimi' && kimiModelsState.error + ? `${t('newSession.model.loadFailed')}: ${kimiModelsState.error}` + : agent === 'pi' && piModelsState.error + ? `${t('newSession.model.loadFailed')}: ${piModelsState.error}` : null} onModelChange={setModel} /> diff --git a/web/src/components/NewSession/preferences.test.ts b/web/src/components/NewSession/preferences.test.ts index bf592a0f..147517f4 100644 --- a/web/src/components/NewSession/preferences.test.ts +++ b/web/src/components/NewSession/preferences.test.ts @@ -164,6 +164,24 @@ describe('NewSession preferences', () => { }) }) + it('does not reset a remembered Kimi alias against the static Default-only list', () => { + // Kimi's catalog is dynamic; validating against MODEL_OPTIONS.kimi + // (only 'auto') must not turn a saved alias back into Default before + // the real catalog arrives. + expect(resolvePreferredLaunchSettings('kimi', { + model: 'GLM-5.3-flash', + cursorSelectedBase: 'auto', + effort: 'auto', + modelReasoningEffort: 'default' + })).toEqual({ + model: 'GLM-5.3-flash', + cursorSelectedBase: 'auto', + effort: 'auto', + modelReasoningEffort: 'default', + permissionMode: 'default' + }) + }) + it('falls back when a remembered permission mode is invalid for the agent', () => { expect(resolvePreferredLaunchSettings('codex', { model: 'auto', diff --git a/web/src/components/NewSession/preferences.ts b/web/src/components/NewSession/preferences.ts index 1d308ff0..05a770a1 100644 --- a/web/src/components/NewSession/preferences.ts +++ b/web/src/components/NewSession/preferences.ts @@ -134,7 +134,10 @@ export function resolvePreferredLaunchSettings( ): PreferredLaunchSettings { const preferredModel = preferred?.model ?? 'auto' const staticModelValues = MODEL_OPTIONS[agent].map((option) => option.value) - const model = staticModelValues.length > 0 && agent !== 'codex' && agent !== 'copilot' + // Kimi's catalog is dynamic (machine discovery); validating a saved alias + // against the static list would reset it to 'auto'. The settled-catalog + // effect in NewSession validates it once the real catalog has arrived. + const model = staticModelValues.length > 0 && agent !== 'codex' && agent !== 'copilot' && agent !== 'kimi' ? resolvePreferredOptionValue(preferredModel, staticModelValues, 'auto') : preferredModel const effort = agent === 'claude' diff --git a/web/src/components/SessionChat.tsx b/web/src/components/SessionChat.tsx index 14f9ffae..e8dd5e77 100644 --- a/web/src/components/SessionChat.tsx +++ b/web/src/components/SessionChat.tsx @@ -109,6 +109,8 @@ import { buildCursorEffortPickerOptionsWithDefaultFirst } from '@/lib/cursorMode import { useOpencodeModels } from '@/hooks/queries/useOpencodeModels' import { useGrokModels } from '@/hooks/queries/useGrokModels' import { useCopilotModels } from '@/hooks/queries/useCopilotModels' +import { useKimiModelsForSession } from '@/hooks/queries/useKimiModelsForSession' +import { buildKimiSessionModelOptions } from '@/components/NewSession/grokModels' import { useGrokReasoningEffortOptions } from '@/hooks/queries/useGrokReasoningEffortOptions' import { usePiModels } from '@/hooks/queries/usePiModels' import { useOpencodeReasoningEffortOptions } from '@/hooks/queries/useOpencodeReasoningEffortOptions' @@ -1071,6 +1073,19 @@ function SessionChatInner(props: SessionChatProps) { enabled: agentFlavor === 'cursor' && props.session.active }) const sessionMachineId = props.session.metadata?.machineId ?? null + // A running session discovers its models over its own connection (kimi + // provider list --json), so this works without a background runner; + // switching itself still goes through the existing ACP setModel path. + const kimiModelsState = useKimiModelsForSession({ + api: props.api, + sessionId: props.session.id, + enabled: agentFlavor === 'kimi' && props.session.active + }) + const kimiModelOptions = useMemo(() => ( + agentFlavor === 'kimi' && kimiModelsState.availableModels.length > 0 + ? buildKimiSessionModelOptions(kimiModelsState.availableModels) + : undefined + ), [agentFlavor, kimiModelsState.availableModels]) const machineCursorModelsState = useCursorModelsForMachine({ api: props.api, machineId: sessionMachineId, @@ -2047,8 +2062,10 @@ function SessionChatInner(props: SessionChatProps) { ? grokModelOptions : agentFlavor === 'copilot' ? copilotModelOptions - : agentFlavor === 'agy' - ? agyModelOptions + : agentFlavor === 'kimi' + ? kimiModelOptions + : agentFlavor === 'agy' + ? agyModelOptions // Pi gets its provider-qualified model list from the piModels prop; // feeding piModelOptions here would make the generic Ctrl/Cmd+M // cycler (getNextModelForFlavor) post a bare modelId string, diff --git a/web/src/hooks/queries/useKimiModelsForCwd.ts b/web/src/hooks/queries/useKimiModelsForCwd.ts new file mode 100644 index 00000000..97e7ef01 --- /dev/null +++ b/web/src/hooks/queries/useKimiModelsForCwd.ts @@ -0,0 +1,48 @@ +import { useQuery } from '@tanstack/react-query' +import type { ApiClient } from '@/api/client' +import type { KimiModelSummary } from '@/types/api' +import { queryKeys } from '@/lib/query-keys' + +export function useKimiModelsForCwd(args: { + api: ApiClient | null + machineId?: string | null + cwd?: string | null + enabled?: boolean +}): { + availableModels: KimiModelSummary[] + currentModelId: string | null + isLoading: boolean + error: string | null +} { + const { api, machineId, cwd } = args + const trimmedCwd = typeof cwd === 'string' ? cwd.trim() : '' + const enabled = Boolean(args.enabled && api && machineId && trimmedCwd) + + const query = useQuery({ + queryKey: machineId && trimmedCwd + ? queryKeys.machineKimiModelsForCwd(machineId, trimmedCwd) + : ['machine-kimi-models', 'unknown', 'unknown'] as const, + queryFn: async () => { + if (!api || !machineId || !trimmedCwd) { + throw new Error('Kimi models target unavailable') + } + return await api.getMachineKimiModelsForCwd(machineId, trimmedCwd) + }, + enabled, + staleTime: 60_000, + retry: false, + }) + + return { + availableModels: query.data?.availableModels ?? [], + currentModelId: query.data?.currentModelId ?? null, + isLoading: query.isLoading, + error: query.data?.success === false + ? (query.data.error ?? 'Failed to load Kimi models') + : query.error instanceof Error + ? query.error.message + : query.error + ? 'Failed to load Kimi models' + : null, + } +} diff --git a/web/src/hooks/queries/useKimiModelsForSession.test.tsx b/web/src/hooks/queries/useKimiModelsForSession.test.tsx new file mode 100644 index 00000000..d60afa22 --- /dev/null +++ b/web/src/hooks/queries/useKimiModelsForSession.test.tsx @@ -0,0 +1,108 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { renderHook, waitFor } from '@testing-library/react' +import type { PropsWithChildren } from 'react' +import { describe, expect, it, vi } from 'vitest' +import type { ApiClient } from '@/api/client' +import { useKimiModelsForSession } from './useKimiModelsForSession' + +function wrapper(queryClient: QueryClient) { + return ({ children }: PropsWithChildren) => ( + {children} + ) +} + +function createQueryClient() { + return new QueryClient({ defaultOptions: { queries: { retry: false } } }) +} + +describe('useKimiModelsForSession', () => { + it('reads the catalog over the active session connection', async () => { + const getSessionKimiModels = vi.fn(async () => ({ + success: true, + availableModels: [ + { modelId: 'GLM-5.3-flash', name: 'thehive / GLM-5.3-flash', provider: 'thehive' } + ], + currentModelId: 'GLM-5.3-flash' + })) + const api = { getSessionKimiModels } as unknown as ApiClient + const queryClient = createQueryClient() + + const { result } = renderHook(() => useKimiModelsForSession({ + api, + sessionId: 'session-1', + enabled: true + }), { wrapper: wrapper(queryClient) }) + + await waitFor(() => expect(result.current.availableModels).toHaveLength(1)) + expect(getSessionKimiModels).toHaveBeenCalledWith('session-1') + expect(result.current.availableModels[0]).toEqual({ + modelId: 'GLM-5.3-flash', + name: 'thehive / GLM-5.3-flash', + provider: 'thehive' + }) + expect(result.current.currentModelId).toBe('GLM-5.3-flash') + expect(result.current.error).toBeNull() + }) + + it('surfaces a failed session probe as an error with no catalog', async () => { + const getSessionKimiModels = vi.fn(async () => ({ + success: false, + error: 'Kimi model discovery timed out' + })) + const api = { getSessionKimiModels } as unknown as ApiClient + const queryClient = createQueryClient() + + const { result } = renderHook(() => useKimiModelsForSession({ + api, + sessionId: 'session-1', + enabled: true + }), { wrapper: wrapper(queryClient) }) + + await waitFor(() => expect(result.current.error).toBe('Kimi model discovery timed out')) + expect(result.current.availableModels).toEqual([]) + expect(result.current.currentModelId).toBeNull() + }) + + it('does not probe without an active session', () => { + const getSessionKimiModels = vi.fn() + const api = { getSessionKimiModels } as unknown as ApiClient + const queryClient = createQueryClient() + + const disabled = renderHook(() => useKimiModelsForSession({ + api, + sessionId: 'session-1', + enabled: false + }), { wrapper: wrapper(queryClient) }) + const withoutSession = renderHook(() => useKimiModelsForSession({ + api, + sessionId: null, + enabled: true + }), { wrapper: wrapper(queryClient) }) + + expect(getSessionKimiModels).not.toHaveBeenCalled() + expect(disabled.result.current.availableModels).toEqual([]) + expect(withoutSession.result.current.availableModels).toEqual([]) + }) + + it('keys the cache per session', async () => { + const getSessionKimiModels = vi.fn(async (sessionId: string) => ({ + success: true, + availableModels: [{ modelId: `${sessionId}-alias` }], + currentModelId: null + })) + const api = { getSessionKimiModels } as unknown as ApiClient + const queryClient = createQueryClient() + const shared = wrapper(queryClient) + + const first = renderHook(() => useKimiModelsForSession({ + api, sessionId: 'session-1', enabled: true + }), { wrapper: shared }) + const second = renderHook(() => useKimiModelsForSession({ + api, sessionId: 'session-2', enabled: true + }), { wrapper: shared }) + + await waitFor(() => expect(first.result.current.availableModels[0]?.modelId).toBe('session-1-alias')) + await waitFor(() => expect(second.result.current.availableModels[0]?.modelId).toBe('session-2-alias')) + expect(getSessionKimiModels).toHaveBeenCalledTimes(2) + }) +}) diff --git a/web/src/hooks/queries/useKimiModelsForSession.ts b/web/src/hooks/queries/useKimiModelsForSession.ts new file mode 100644 index 00000000..017261a2 --- /dev/null +++ b/web/src/hooks/queries/useKimiModelsForSession.ts @@ -0,0 +1,38 @@ +import { useQuery } from '@tanstack/react-query' +import type { ApiClient } from '@/api/client' +import type { KimiModelSummary } from '@/types/api' +import { queryKeys } from '@/lib/query-keys' + +export function useKimiModelsForSession(args: { + api: ApiClient | null + sessionId?: string | null + enabled?: boolean +}): { + availableModels: KimiModelSummary[] + currentModelId: string | null + isLoading: boolean + error: string | null +} { + const enabled = Boolean(args.enabled && args.api && args.sessionId) + const query = useQuery({ + queryKey: args.sessionId + ? queryKeys.sessionKimiModels(args.sessionId) + : ['session-kimi-models', 'unknown'] as const, + queryFn: async () => { + if (!args.api || !args.sessionId) throw new Error('Kimi session unavailable') + return await args.api.getSessionKimiModels(args.sessionId) + }, + enabled, + staleTime: 30_000, + retry: false, + }) + + return { + availableModels: query.data?.availableModels ?? [], + currentModelId: query.data?.currentModelId ?? null, + isLoading: query.isLoading, + error: query.data?.success === false + ? (query.data.error ?? 'Failed to load Kimi models') + : query.error instanceof Error ? query.error.message : null, + } +} diff --git a/web/src/lib/query-keys.ts b/web/src/lib/query-keys.ts index 8b647432..4fff52af 100644 --- a/web/src/lib/query-keys.ts +++ b/web/src/lib/query-keys.ts @@ -32,6 +32,8 @@ export const queryKeys = { sessionGrokModels: (sessionId: string) => ['session-grok-models', sessionId] as const, sessionCopilotModels: (sessionId: string) => ['session-copilot-models', sessionId] as const, machineCopilotModelsForCwd: (machineId: string, cwd: string) => ['machine-copilot-models', machineId, cwd] as const, + machineKimiModelsForCwd: (machineId: string, cwd: string) => ['machine-kimi-models', machineId, cwd] as const, + sessionKimiModels: (sessionId: string) => ['session-kimi-models', sessionId] as const, sessionGrokReasoningEffortOptions: (sessionId: string) => ['session-grok-reasoning-effort-options', sessionId] as const, machineAgyModels: (machineId: string) => ['machine-agy-models', machineId] as const, machinePiModels: (machineId: string) => ['machine-pi-models', machineId] as const, diff --git a/web/src/types/api.ts b/web/src/types/api.ts index f94eb3f1..1b1c6610 100644 --- a/web/src/types/api.ts +++ b/web/src/types/api.ts @@ -27,6 +27,8 @@ export type { GitCommandResponse, GrokModelsResponse, GrokModelSummary, + KimiModelsResponse, + KimiModelSummary, CopilotModelsResponse, CopilotModelSummary, GrokReasoningEffortResponse, From a259ad31441a6cd07ee623d7a9434adf3d4cf17f Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 21 Sep 2026 13:49:53 +0100 Subject: [PATCH 16/34] fix(cli): change_title updates metadata.name for visible renames (#1896) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(cli): change_title updates metadata.name for visible renames Agent change_title was writing metadata.summary only, so spawn --name sessions kept showing the old title. Route explicit renames through metadata.name (web rename semantics) across MCP, Codex, and Pi. Co-authored-by: Cursor * fix(web): voice context prefers metadata.name for session title Voice bootstrap/full formatters only read summary.text, so after change_title sets name the spoken context kept a stale title. Use the same name→summary precedence as getSessionTitle. Co-authored-by: Cursor * chore: polish title rename tests after cold review Rename the Codex root title test to match last-writer-wins behavior, and skip the voice full-context summary header when no title signal exists (avoid literal undefined). Co-authored-by: Cursor --------- Co-authored-by: Cursor --- cli/src/agent/nativeSessionTitle.test.ts | 25 ++++ cli/src/agent/sessionDisplayRename.test.ts | 54 +++++++++ cli/src/agent/sessionDisplayRename.ts | 38 ++++++ cli/src/claude/utils/startHappyServer.test.ts | 112 ++++++++++++++++++ cli/src/claude/utils/startHappyServer.ts | 23 ++-- cli/src/codex/codexRemoteLauncher.test.ts | 21 +++- cli/src/codex/codexRemoteLauncher.ts | 9 +- cli/src/codex/shared/projection.title.test.ts | 41 +++++-- cli/src/codex/shared/projection.ts | 34 ++++-- cli/src/codex/shared/root.test.ts | 5 +- cli/src/pi/extensionUiHandler.test.ts | 24 ++++ cli/src/pi/extensionUiHandler.ts | 10 +- cli/src/pi/titleExtension.ts | 4 +- .../realtime/hooks/contextFormatters.test.ts | 40 ++++++- web/src/realtime/hooks/contextFormatters.ts | 11 +- .../realtime/hooks/voiceContextPlan.test.ts | 30 +++++ web/src/realtime/hooks/voiceContextPlan.ts | 5 +- 17 files changed, 432 insertions(+), 54 deletions(-) create mode 100644 cli/src/agent/nativeSessionTitle.test.ts create mode 100644 cli/src/agent/sessionDisplayRename.test.ts create mode 100644 cli/src/agent/sessionDisplayRename.ts diff --git a/cli/src/agent/nativeSessionTitle.test.ts b/cli/src/agent/nativeSessionTitle.test.ts new file mode 100644 index 00000000..609af95a --- /dev/null +++ b/cli/src/agent/nativeSessionTitle.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it, vi } from 'vitest' +import { createNativeSessionTitleMetadataSync } from './nativeSessionTitle' +import type { Metadata } from '@/api/types' + +describe('createNativeSessionTitleMetadataSync', () => { + it('writes summary without overwriting an intentional metadata.name', () => { + let metadata: Metadata = { + path: '/tmp', + host: 'localhost', + name: 'issue-triage-#54' + } + const client = { + getMetadata: () => metadata, + updateMetadata: vi.fn((handler: (current: Metadata) => Metadata) => { + metadata = handler(metadata) + }) + } + + const sync = createNativeSessionTitleMetadataSync(client) + sync('Native generated title') + + expect(metadata.name).toBe('issue-triage-#54') + expect(metadata.summary?.text).toBe('Native generated title') + }) +}) diff --git a/cli/src/agent/sessionDisplayRename.test.ts b/cli/src/agent/sessionDisplayRename.test.ts new file mode 100644 index 00000000..263f09a4 --- /dev/null +++ b/cli/src/agent/sessionDisplayRename.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from 'vitest' +import { applySessionDisplayRename, normalizeSessionDisplayTitle } from './sessionDisplayRename' +import type { Metadata } from '@/api/types' + +describe('sessionDisplayRename', () => { + it('normalizes whitespace and rejects empty titles', () => { + expect(normalizeSessionDisplayTitle(' Fix login bug ')).toBe('Fix login bug') + expect(normalizeSessionDisplayTitle('')).toBeNull() + expect(normalizeSessionDisplayTitle(' ')).toBeNull() + expect(normalizeSessionDisplayTitle(null)).toBeNull() + }) + + it('sets metadata.name even when a spawn name already exists', () => { + let metadata: Metadata = { + path: '/tmp/project', + host: 'localhost', + name: 'issue-triage-#54', + summary: { text: 'Old summary', updatedAt: 1 } + } + const client = { + updateMetadata: vi.fn((handler: (current: Metadata) => Metadata) => { + metadata = handler(metadata) + }) + } + + expect(applySessionDisplayRename(client, ' Renamed triage peer ')).toBe(true) + expect(metadata.name).toBe('Renamed triage peer') + expect(metadata.summary?.text).toBe('Old summary') + expect(client.updateMetadata).toHaveBeenCalledTimes(1) + }) + + it('sets metadata.name when only a summary exists', () => { + let metadata: Metadata = { + path: '/tmp/project', + host: 'localhost', + summary: { text: 'Generated summary', updatedAt: 1 } + } + const client = { + updateMetadata: vi.fn((handler: (current: Metadata) => Metadata) => { + metadata = handler(metadata) + }) + } + + expect(applySessionDisplayRename(client, 'Explicit rename')).toBe(true) + expect(metadata.name).toBe('Explicit rename') + expect(metadata.summary?.text).toBe('Generated summary') + }) + + it('returns false without writing when the title is empty', () => { + const client = { updateMetadata: vi.fn() } + expect(applySessionDisplayRename(client, ' ')).toBe(false) + expect(client.updateMetadata).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/agent/sessionDisplayRename.ts b/cli/src/agent/sessionDisplayRename.ts new file mode 100644 index 00000000..4eba5bd0 --- /dev/null +++ b/cli/src/agent/sessionDisplayRename.ts @@ -0,0 +1,38 @@ +import type { ApiSessionClient } from '@/api/apiSession'; +import type { Metadata } from '@/api/types'; + +type SessionDisplayRenameClient = Pick; + +/** + * Explicit agent/operator rename: set metadata.name (same field as web + * renameSession / PATCH /sessions/:id). Distinct from native/generated + * summaries, which must not overwrite an intentional name. + */ +export function normalizeSessionDisplayTitle(title: unknown): string | null { + if (typeof title !== 'string') { + return null; + } + const normalized = title.replace(/\s+/g, ' ').trim(); + return normalized.length > 0 ? normalized : null; +} + +export function applySessionDisplayRename( + client: SessionDisplayRenameClient, + title: unknown +): boolean { + const normalized = normalizeSessionDisplayTitle(title); + if (!normalized) { + return false; + } + + client.updateMetadata((metadata: Metadata) => { + if (metadata.name?.trim() === normalized) { + return metadata; + } + return { + ...metadata, + name: normalized + }; + }); + return true; +} diff --git a/cli/src/claude/utils/startHappyServer.test.ts b/cli/src/claude/utils/startHappyServer.test.ts index b507c1c4..8abb273f 100644 --- a/cli/src/claude/utils/startHappyServer.test.ts +++ b/cli/src/claude/utils/startHappyServer.test.ts @@ -195,6 +195,118 @@ describe('startHappyServer skill_lookup', () => { }) +describe('startHappyServer change_title', () => { + let stopServer: (() => void) | null + let client: Client | null + + afterEach(async () => { + await client?.close() + stopServer?.() + client = null + stopServer = null + }) + + async function connectChangeTitleServer(sessionClient: ApiSessionClient, options?: Parameters[1]) { + const server = await startHappyServer(sessionClient, options) + stopServer = server.stop + client = new Client( + { name: 'hapi-change-title-test', version: '1.0.0' }, + { capabilities: {} } + ) + await client.connect(new StreamableHTTPClientTransport(new URL(server.url))) + return client + } + + it('renames via metadata.name so spawn --name sessions update visibly', async () => { + const updateMetadata = vi.fn() + const sendClaudeSessionMessage = vi.fn() + const sessionClient = { + updateMetadata, + sendAgentMessage: vi.fn(), + sendClaudeSessionMessage + } as unknown as ApiSessionClient + + const mcp = await connectChangeTitleServer(sessionClient) + updateMetadata.mockClear() + sendClaudeSessionMessage.mockClear() + + const result = await mcp.callTool({ + name: 'change_title', + arguments: { title: ' Renamed triage peer ' } + }) as ToolResult + + expect(result.isError).toBe(false) + expect(result.content?.[0]?.text).toContain('Successfully changed chat title to: "Renamed triage peer"') + expect(updateMetadata).toHaveBeenCalledTimes(1) + const handler = updateMetadata.mock.calls[0]?.[0] as (metadata: { + path: string + host: string + name?: string + summary?: { text: string } + }) => { + path: string + host: string + name?: string + summary?: { text: string } + } + expect(handler({ + path: '/tmp', + host: 'localhost', + name: 'issue-triage-#54', + summary: { text: 'stale' } + })).toEqual({ + path: '/tmp', + host: 'localhost', + name: 'Renamed triage peer', + summary: { text: 'stale' } + }) + expect(sendClaudeSessionMessage).not.toHaveBeenCalled() + }) + + it('returns an error for blank titles instead of claiming success', async () => { + const updateMetadata = vi.fn() + const sessionClient = { + updateMetadata, + sendAgentMessage: vi.fn(), + sendClaudeSessionMessage: vi.fn() + } as unknown as ApiSessionClient + + const mcp = await connectChangeTitleServer(sessionClient) + updateMetadata.mockClear() + + const result = await mcp.callTool({ + name: 'change_title', + arguments: { title: ' ' } + }) as ToolResult + + expect(result.isError).toBe(true) + expect(result.content?.[0]?.text).toContain('Failed to change chat title') + expect(updateMetadata).not.toHaveBeenCalled() + }) + + it('does not write titles when emitTitleSummary is disabled (Codex child isolation)', async () => { + const updateMetadata = vi.fn() + const sendClaudeSessionMessage = vi.fn() + const sessionClient = { + updateMetadata, + sendAgentMessage: vi.fn(), + sendClaudeSessionMessage + } as unknown as ApiSessionClient + + const mcp = await connectChangeTitleServer(sessionClient, { emitTitleSummary: false }) + updateMetadata.mockClear() + sendClaudeSessionMessage.mockClear() + + const result = await mcp.callTool({ + name: 'change_title', + arguments: { title: 'Child Title' } + }) as ToolResult + + expect(result.isError).toBe(false) + expect(updateMetadata).not.toHaveBeenCalled() + expect(sendClaudeSessionMessage).not.toHaveBeenCalled() + }) +}) describe('toClaudeAllowedHapiMcpTools', () => { it('keeps local-path and peer tools registered but out of Claude --allowedTools', () => { expect(toClaudeAllowedHapiMcpTools([ diff --git a/cli/src/claude/utils/startHappyServer.ts b/cli/src/claude/utils/startHappyServer.ts index f14af6c0..10a2a02d 100644 --- a/cli/src/claude/utils/startHappyServer.ts +++ b/cli/src/claude/utils/startHappyServer.ts @@ -27,8 +27,14 @@ import { SESSION_ID_PREFIX_PARAM_DESCRIPTION, } from '@hapi/protocol/sessionCitation' import { PingPeerError, formatInspectPeerReport, formatPeerSessionsList, inspectPeer, listPeerSessions, peerListFetchLimit, pingPeer } from "@/modules/pingPeer/pingPeer"; +import { applySessionDisplayRename, normalizeSessionDisplayTitle } from "@/agent/sessionDisplayRename"; type StartHappyServerOptions = { + /** + * When true (default), change_title writes metadata.name (web rename + * semantics). Set false for Codex collab so child agents do not rename + * the parent HAPI session; the parent launcher applies the title later. + */ emitTitleSummary?: boolean; enableChangeTitle?: boolean; skillLookup?: { @@ -66,14 +72,14 @@ function createHapiMcpServer( const handler = async (title: string) => { logger.debug('[hapiMCP] Changing title to:', title); try { - if (emitTitleSummary) { - client.sendClaudeSessionMessage({ - type: 'summary', - summary: title, - leafUuid: randomUUID() - }); + if (!emitTitleSummary) { + // Codex collab: acknowledge the tool call without writing. + // Parent-thread mcp_tool_call_end applies the rename later. + return { success: true }; + } + if (!applySessionDisplayRename(client, title)) { + return { success: false, error: 'Title must not be empty' }; } - return { success: true }; } catch (error) { return { success: false, error: String(error) }; @@ -175,13 +181,14 @@ function createHapiMcpServer( }, async (args: { title: string }) => { const response = await handler(args.title); logger.debug('[hapiMCP] Response:', response); + const displayTitle = normalizeSessionDisplayTitle(args.title) ?? args.title; if (response.success) { return { content: [ { type: 'text' as const, - text: `Successfully changed chat title to: "${args.title}"`, + text: `Successfully changed chat title to: "${displayTitle}"`, }, ], isError: false, diff --git a/cli/src/codex/codexRemoteLauncher.test.ts b/cli/src/codex/codexRemoteLauncher.test.ts index 83a71a3a..9629d3ca 100644 --- a/cli/src/codex/codexRemoteLauncher.test.ts +++ b/cli/src/codex/codexRemoteLauncher.test.ts @@ -1144,6 +1144,7 @@ function createSessionStub( const sessionEvents: Array<{ type: string; [key: string]: unknown }> = []; const codexMessages: unknown[] = []; const summaryMessages: unknown[] = []; + const metadataUpdates: Array> = []; const thinkingChanges: boolean[] = []; const foundSessionIds: string[] = []; const resetThreadCalls: string[] = []; @@ -1156,6 +1157,11 @@ function createSessionStub( requests: {}, completedRequests: {} }; + let metadata: Record = { + path: '/tmp/hapi-update', + host: 'localhost', + name: 'issue-triage-#54' + }; const rpcHandlers = new Map unknown>(); const client = { @@ -1164,7 +1170,10 @@ function createSessionStub( rpcHandlers.set(method, handler); } }, - updateMetadata(_handler: (metadata: Record) => Record) {}, + updateMetadata(handler: (current: Record) => Record) { + metadata = handler(metadata); + metadataUpdates.push({ ...metadata }); + }, updateAgentState(handler: (state: FakeAgentState) => FakeAgentState) { agentState = handler(agentState); }, @@ -1239,6 +1248,8 @@ function createSessionStub( sessionEvents, codexMessages, summaryMessages, + metadataUpdates, + getMetadata: () => metadata, thinkingChanges, foundSessionIds, resetThreadCalls, @@ -3309,15 +3320,13 @@ describe('codexRemoteLauncher', () => { it('applies parent-thread hapi change_title after disabling MCP-side title writes', async () => { harness.emitParentTitleChange = true; - const { session, codexMessages, summaryMessages } = createSessionStub(); + const { session, codexMessages, summaryMessages, getMetadata } = createSessionStub(); await codexRemoteLauncher(session as never); expect(harness.bridgeOptions).toEqual([{ emitTitleSummary: false }]); - expect(summaryMessages).toContainEqual(expect.objectContaining({ - type: 'summary', - summary: 'Parent Title' - })); + expect(summaryMessages).toEqual([]); + expect(getMetadata().name).toBe('Parent Title'); expect(codexMessages).toContainEqual(expect.objectContaining({ type: 'tool-call', name: 'mcp__hapi__change_title', diff --git a/cli/src/codex/codexRemoteLauncher.ts b/cli/src/codex/codexRemoteLauncher.ts index f2290f38..299f8686 100644 --- a/cli/src/codex/codexRemoteLauncher.ts +++ b/cli/src/codex/codexRemoteLauncher.ts @@ -8,6 +8,7 @@ import { DiffProcessor } from './utils/diffProcessor'; import { logger } from '@/ui/logger'; import { CodexDisplay } from '@/ui/ink/CodexDisplay'; import { buildHapiMcpBridge } from './utils/buildHapiMcpBridge'; +import { applySessionDisplayRename } from '@/agent/sessionDisplayRename'; import { emitReadyIfIdle } from './utils/emitReadyIfIdle'; import type { CodexSession } from './session'; import type { EnhancedMode } from './loop'; @@ -473,11 +474,9 @@ class CodexRemoteLauncher extends RemoteLauncherBase { }; const sendTitleSummary = (title: string): void => { - session.client.sendClaudeSessionMessage({ - type: 'summary', - summary: title, - leafUuid: randomUUID() - }); + // Matches MCP change_title / web rename: set metadata.name so a + // prior spawn --name does not hide the agent rename. + applySessionDisplayRename(session.client, title); }; const formatOutputPreview = (value: unknown): string => { diff --git a/cli/src/codex/shared/projection.title.test.ts b/cli/src/codex/shared/projection.title.test.ts index dbe1e01c..f85985a4 100644 --- a/cli/src/codex/shared/projection.title.test.ts +++ b/cli/src/codex/shared/projection.title.test.ts @@ -31,14 +31,15 @@ function params(item: unknown, turnId = 'turn') { return { threadId: 'thread', t function history(...items: unknown[]) { return { turns: [{ id: 'turn', status: 'completed', items }] }; } describe('shared Codex titles', () => { - it('persists a successful root tool title while preserving the manual name and transcript', async () => { + it('renames via metadata.name so a spawn name does not hide change_title', async () => { const f = fixture(); const item = titleItem('title', ' Remote title '); await f.projection.notification('item/started', params(item)); expect(f.update).not.toHaveBeenCalled(); // Completion may omit the arguments already sent at start. await f.projection.notification('item/completed', params({ ...item, arguments: undefined })); - expect(f.metadata()).toMatchObject({ name: 'Manual name', summary: { text: 'Remote title', updatedAt: expect.any(Number) } }); + expect(f.metadata()).toMatchObject({ name: 'Remote title' }); + expect(f.metadata().summary).toBeUndefined(); expect(f.send.mock.calls.map(([body]) => body.type)).toEqual(['tool-call', 'tool-call-result']); expect(f.update).toHaveBeenCalledTimes(1); await f.projection.notification('item/completed', params(item)); @@ -50,10 +51,16 @@ describe('shared Codex titles', () => { it('handles a complete item without a start and orders successive titles across deferred writes', async () => { const f = fixture(undefined, true); + // Start without a spawn name so successive renames are visible on name. + f.update(metadata => { + const { name: _ignored, ...rest } = metadata; + return rest as Metadata; + }); + f.update.mockClear(); await f.projection.notification('item/completed', params(titleItem('first', 'First'))); await f.projection.notification('item/completed', params(titleItem('second', 'Second'))); f.flush(); - expect(f.metadata().summary?.text).toBe('Second'); + expect(f.metadata().name).toBe('Second'); }); it.each([ @@ -86,25 +93,31 @@ describe('shared Codex titles', () => { it('restores only the last successful historical title and does not replay earlier names', async () => { const f = fixture(); + f.update(metadata => { + const { name: _ignored, ...rest } = metadata; + return rest as Metadata; + }); + f.update.mockClear(); const first = titleItem('first', 'First'); const last = titleItem('last', 'Last'); const snapshot = history(first, last, { ...titleItem('failed', 'Failed'), result: { isError: true } }); await f.projection.history(snapshot); - expect(f.metadata().summary?.text).toBe('Last'); + expect(f.metadata().name).toBe('Last'); expect(f.update).toHaveBeenCalledTimes(1); f.projection.reset(); await f.projection.history(snapshot); await f.projection.notification('item/completed', params(first)); - expect(f.metadata().summary?.text).toBe('Last'); + expect(f.metadata().name).toBe('Last'); expect(f.update).toHaveBeenCalledTimes(1); }); - it('never overwrites an existing summary during a cold history replay', async () => { + it('never overwrites an existing display title during a cold history replay', async () => { const f = fixture(); f.update(metadata => ({ ...metadata, summary: { text: 'Existing', updatedAt: 123 } })); f.update.mockClear(); await f.projection.history(history(titleItem('old', 'Old'))); expect(f.update).not.toHaveBeenCalled(); + expect(f.metadata().name).toBe('Manual name'); expect(f.metadata().summary).toEqual({ text: 'Existing', updatedAt: 123 }); }); @@ -114,11 +127,16 @@ describe('shared Codex titles', () => { await f.projection.history({ turns: [{ id: 'turn', status: 'inProgress', items: [item] }] }); expect(f.update).not.toHaveBeenCalled(); await f.projection.notification('item/completed', params({ ...titleItem('title', 'unused'), arguments: undefined })); - expect(f.metadata().summary?.text).toBe('Resumed'); + expect(f.metadata().name).toBe('Resumed'); }); it('does not roll back a live title when a suspended replay or queued metadata callback resumes', async () => { const f = fixture(undefined, true); + f.update(metadata => { + const { name: _ignored, ...rest } = metadata; + return rest as Metadata; + }); + f.update.mockClear(); let release!: () => void; f.committed.mockImplementationOnce(() => new Promise(resolve => { release = resolve; })); const replay = f.projection.history(history( @@ -129,12 +147,17 @@ describe('shared Codex titles', () => { await f.projection.notification('item/completed', params(titleItem('live', 'Live'), 'next')); release(); await replay; f.flush(); - expect(f.metadata().summary?.text).toBe('Live'); + expect(f.metadata().name).toBe('Live'); const queued = fixture(undefined, true); + queued.update(metadata => { + const { name: _ignored, ...rest } = metadata; + return rest as Metadata; + }); + queued.update.mockClear(); await queued.projection.history(history(titleItem('old', 'Old'))); await queued.projection.notification('item/completed', params(titleItem('live', 'Live'), 'next')); queued.flush(); - expect(queued.metadata().summary?.text).toBe('Live'); + expect(queued.metadata().name).toBe('Live'); }); }); diff --git a/cli/src/codex/shared/projection.ts b/cli/src/codex/shared/projection.ts index c1e44e76..6c8c03eb 100644 --- a/cli/src/codex/shared/projection.ts +++ b/cli/src/codex/shared/projection.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto'; import type { ApiSessionClient } from '@/api/apiSession'; +import { normalizeSessionDisplayTitle } from '@/agent/sessionDisplayRename'; import { registerGeneratedImageFromPath } from '@/modules/common/generatedImages'; import { AppServerEventConverter } from '../utils/appServerEventConverter'; import { record, string } from './gateway'; @@ -16,7 +17,7 @@ export function inputText(input: unknown): string { function requestedTitle(item: Record): string | undefined { if (item.type !== 'mcpToolCall' || item.server !== 'hapi' || item.tool !== 'change_title') return; - return string(record(item.arguments).title)?.trim() || undefined; + return normalizeSessionDisplayTitle(string(record(item.arguments).title)) ?? undefined; } function successfulTitle(item: Record, pending?: string): string | undefined { @@ -27,6 +28,10 @@ function successfulTitle(item: Record, pending?: string): strin return requestedTitle(item) ?? pending; } +function metadataHasDisplayTitle(metadata: { name?: string; summary?: { text: string } } | null | undefined): boolean { + return Boolean(metadata?.name?.trim() || metadata?.summary?.text?.trim()); +} + /** Canonical V2 stream only. Stable message IDs also deduplicate snapshot replay at the hub. */ export class SharedCodexProjection { private converter = new AppServerEventConverter(); @@ -54,6 +59,15 @@ export class SharedCodexProjection { } : { ...body, id }, id); } + private applyDisplayRename(title: string, revision: number): void { + this.session.updateMetadata(metadata => { + if (revision !== this.titleRevision) return metadata; + const normalized = normalizeSessionDisplayTitle(title); + if (!normalized || metadata.name?.trim() === normalized) return metadata; + return { ...metadata, name: normalized }; + }); + } + async notification(method: string, params: unknown, modelAtReceipt?: string): Promise { const p = record(params); const item = record(p.item); @@ -68,9 +82,7 @@ export class SharedCodexProjection { if (completedTitle) { this.completedTitles.add(key); const revision = ++this.titleRevision; - this.session.updateMetadata(metadata => revision !== this.titleRevision ? metadata : { - ...metadata, summary: { text: completedTitle, updatedAt: Date.now() } - }); + this.applyDisplayRename(completedTitle, revision); } } } @@ -197,11 +209,17 @@ export class SharedCodexProjection { } // Repair sessions created while remote title projection was missing. // Recheck inside the metadata lock: live updates may still be queued, - // and a replay must never replace an existing or newer title. - if (latestTitle && titleRevision === this.titleRevision && !this.session.getMetadata()?.summary?.text?.trim()) { + // and a replay must never replace an existing or newer display title. + if (latestTitle && titleRevision === this.titleRevision && !metadataHasDisplayTitle(this.session.getMetadata())) { const title = latestTitle; - this.session.updateMetadata(metadata => titleRevision !== this.titleRevision || metadata.summary?.text?.trim() - ? metadata : { ...metadata, summary: { text: title, updatedAt: Date.now() } }); + this.session.updateMetadata(metadata => { + if (titleRevision !== this.titleRevision || metadataHasDisplayTitle(metadata)) { + return metadata; + } + const normalized = normalizeSessionDisplayTitle(title); + if (!normalized) return metadata; + return { ...metadata, name: normalized }; + }); } } } diff --git a/cli/src/codex/shared/root.test.ts b/cli/src/codex/shared/root.test.ts index b72c7278..f4cc292c 100644 --- a/cli/src/codex/shared/root.test.ts +++ b/cli/src/codex/shared/root.test.ts @@ -104,16 +104,15 @@ async function completePlan(f: Awaited>, status = 'co } describe('shared plan actions', () => { - it('persists remote title tools while retaining native terminal rename events', async () => { + it('applies remote change_title as metadata.name then lets native terminal rename win', async () => { const f = await fixture(); const item = { id: 'title', type: 'mcpToolCall', server: 'hapi', tool: 'change_title', arguments: { title: 'Remote title' }, status: 'completed', result: { content: [], isError: false } }; f.native.notify('item/completed', { threadId: 'thread', turnId: 'turn', item }); - await vi.waitFor(() => expect(f.metadata().summary?.text).toBe('Remote title')); + await vi.waitFor(() => expect(f.metadata().name).toBe('Remote title')); f.native.notify('thread/name/updated', { threadId: 'thread', threadName: 'Terminal title' }); await vi.waitFor(() => expect(f.metadata().name).toBe('Terminal title')); await f.root.refresh(); - expect(f.metadata().summary?.text).toBe('Remote title'); expect(f.metadata().name).toBe('Terminal title'); }); diff --git a/cli/src/pi/extensionUiHandler.test.ts b/cli/src/pi/extensionUiHandler.test.ts index e475347e..a50c1aed 100644 --- a/cli/src/pi/extensionUiHandler.test.ts +++ b/cli/src/pi/extensionUiHandler.test.ts @@ -30,6 +30,30 @@ function createHarness() { describe('PiExtensionUiHandler', () => { beforeEach(() => vi.useRealTimers()); + it('applies setTitle as metadata.name rename (overrides spawn name)', () => { + let metadata = { + path: '/tmp', + host: 'localhost', + name: 'issue-triage-#54', + summary: { text: 'native summary', updatedAt: 1 } + }; + const harness = createHarness(); + harness.session.updateMetadata.mockImplementation((handler: (current: typeof metadata) => typeof metadata) => { + metadata = handler(metadata); + }); + + harness.handler.handle({ + type: 'extension_ui_request', + id: 'title-1', + method: 'setTitle', + title: ' Renamed via hapi_change_title ' + }); + + expect(metadata.name).toBe('Renamed via hapi_change_title'); + expect(metadata.summary.text).toBe('native summary'); + expect(harness.session.updateMetadata).toHaveBeenCalledTimes(1); + }); + it('maps select into request_user_input and returns its selected option', async () => { const harness = createHarness(); harness.handler.handle({ type: 'extension_ui_request', id: 'select-1', method: 'select', title: 'Pick', options: ['one', 'two'] }); diff --git a/cli/src/pi/extensionUiHandler.ts b/cli/src/pi/extensionUiHandler.ts index d1461341..33f827c8 100644 --- a/cli/src/pi/extensionUiHandler.ts +++ b/cli/src/pi/extensionUiHandler.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; import type { ApiSessionClient } from '@/api/apiSession'; import type { AgentState } from '@/api/types'; -import { createNativeSessionTitleMetadataSync } from '@/agent/nativeSessionTitle'; +import { applySessionDisplayRename } from '@/agent/sessionDisplayRename'; import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; import { logger } from '@/ui/logger'; import type { PiExtensionUiRequest, PiExtensionUiResponse } from './types'; @@ -136,10 +136,8 @@ function normalizeAnswers(answers: PiPermissionResponse['answers']): Record(); private readonly tombstonedIds = new Set(); - private readonly syncTitle: (title: unknown) => void; constructor(private readonly options: PiExtensionUiHandlerOptions) { - this.syncTitle = createNativeSessionTitleMetadataSync(options.session); options.session.rpcHandlerManager.registerHandler(RPC_METHODS.Permission, async (rawResponse) => { const parsed = PiPermissionResponseSchema.safeParse(rawResponse); if (!parsed.success) { @@ -159,7 +157,11 @@ export class PiExtensionUiHandler { }); return; case 'setTitle': - this.syncTitle(request.title); + // hapi_change_title → setTitle is an explicit agent rename, + // same as MCP change_title / web renameSession (metadata.name). + // Native Pi titles still sync via createNativeSessionTitleMetadataSync + // in loop.ts (summary only; name continues to win). + applySessionDisplayRename(this.options.session, request.title); return; case 'setStatus': case 'setWidget': diff --git a/cli/src/pi/titleExtension.ts b/cli/src/pi/titleExtension.ts index 2f3bde13..678fafba 100644 --- a/cli/src/pi/titleExtension.ts +++ b/cli/src/pi/titleExtension.ts @@ -9,8 +9,8 @@ import packageJson from '../../package.json'; * auto-titling capability the Claude/Codex/OpenCode launchers already have: * a `hapi_change_title` tool callable by the model plus a persistent * system-prompt instruction. The title is applied via `ctx.ui.setTitle()`, - * which the Pi extension UI bridge (`extensionUiHandler`) syncs into session - * metadata, so no extra title-provider round-trip is needed. + * which the Pi extension UI bridge (`extensionUiHandler`) renames via + * `metadata.name` (same field as web rename / MCP `change_title`). * * The source is kept as a string (plain JS, no template literals) so it can be * materialized to disk at launch time and passed to `pi --extension`, including diff --git a/web/src/realtime/hooks/contextFormatters.test.ts b/web/src/realtime/hooks/contextFormatters.test.ts index b1692edf..296a6f6b 100644 --- a/web/src/realtime/hooks/contextFormatters.test.ts +++ b/web/src/realtime/hooks/contextFormatters.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from 'vitest' -import type { DecryptedMessage } from '@/types/api' -import { extractLastAssistantSpeakable, formatMessage, formatNewMessages, formatReadyEvent } from './contextFormatters' +import type { DecryptedMessage, Session } from '@/types/api' +import { + extractLastAssistantSpeakable, + formatMessage, + formatNewMessages, + formatReadyEvent, + formatSessionFull +} from './contextFormatters' function msg(partial: Pick): DecryptedMessage { return { @@ -239,3 +245,33 @@ describe('formatNewMessages', () => { expect(update).not.toContain('Claude Code') }) }) + +describe('formatSessionFull title precedence', () => { + it('prefers metadata.name over a stale summary', () => { + const session = { + id: 'sess-1', + metadata: { + path: '/proj', + name: 'Renamed triage peer', + summary: { text: 'issue-triage-#54' } + } + } as Session + + const text = formatSessionFull(session, [], 'Codex') + + expect(text).toContain('Renamed triage peer') + expect(text).not.toContain('issue-triage-#54') + }) + + it('uses metadata.name when summary is absent', () => { + const session = { + id: 'sess-2', + metadata: { + path: '/proj', + name: 'spawned-peer' + } + } as Session + + expect(formatSessionFull(session, [], 'Codex')).toContain('spawned-peer') + }) +}) diff --git a/web/src/realtime/hooks/contextFormatters.ts b/web/src/realtime/hooks/contextFormatters.ts index 54443925..1cd1ce11 100644 --- a/web/src/realtime/hooks/contextFormatters.ts +++ b/web/src/realtime/hooks/contextFormatters.ts @@ -1,9 +1,11 @@ import { unwrapRoleWrappedRecordEnvelope } from '@hapi/protocol/messages' import { isObject } from '@hapi/protocol' import type { DecryptedMessage, Session } from '@/types/api' +import { getSessionTitle, hasSessionTitleSignal } from '@/lib/sessionTitle' import { VOICE_CONFIG } from '../voiceConfig' interface SessionMetadata { + name?: string summary?: { text?: string } path?: string machineId?: string @@ -253,17 +255,16 @@ export function formatSessionFull(session: Session | null, messages: DecryptedMe return 'Session not available' } - const sessionName = session.metadata?.summary?.text + const sessionTitle = hasSessionTitleSignal(session) ? getSessionTitle(session) : undefined const sessionPath = session.metadata?.path const lines: string[] = [] lines.push(`# Session ID: ${session.id}`) lines.push(`# Project path: ${sessionPath}`) - lines.push(`# Session summary:\n${sessionName}`) - - if (session.metadata?.summary?.text) { + if (sessionTitle) { + lines.push(`# Session summary:\n${sessionTitle}`) lines.push('## Session Summary') - lines.push(session.metadata.summary.text) + lines.push(sessionTitle) lines.push('') } diff --git a/web/src/realtime/hooks/voiceContextPlan.test.ts b/web/src/realtime/hooks/voiceContextPlan.test.ts index bd315d2a..0c325f8c 100644 --- a/web/src/realtime/hooks/voiceContextPlan.test.ts +++ b/web/src/realtime/hooks/voiceContextPlan.test.ts @@ -35,6 +35,36 @@ describe('buildSessionVoiceContextPlan', () => { expect(plan.bootstrap).not.toContain('Claude Code') }) + test('prefers metadata.name over a stale summary for the voice session header', () => { + const session = { + id: 'sess-named', + metadata: { + path: '/proj', + name: 'Renamed triage peer', + summary: { text: 'issue-triage-#54' } + } + } as Session + + const plan = buildSessionVoiceContextPlan(session, [], 'Codex') + + expect(plan.bootstrap).toContain('Renamed triage peer') + expect(plan.bootstrap).not.toContain('issue-triage-#54') + }) + + test('uses metadata.name alone when no summary exists', () => { + const session = { + id: 'sess-name-only', + metadata: { + path: '/proj', + name: 'spawned-peer' + } + } as Session + + const plan = buildSessionVoiceContextPlan(session, [], 'Codex') + + expect(plan.bootstrap).toContain('spawned-peer') + }) + test('handles missing session', () => { const plan = buildSessionVoiceContextPlan(null, [], 'Claude') expect(plan.bootstrap).toBe('Session not available') diff --git a/web/src/realtime/hooks/voiceContextPlan.ts b/web/src/realtime/hooks/voiceContextPlan.ts index fd160f4b..a969c002 100644 --- a/web/src/realtime/hooks/voiceContextPlan.ts +++ b/web/src/realtime/hooks/voiceContextPlan.ts @@ -5,6 +5,7 @@ import { utf8ByteLength } from '@hapi/protocol/voice-personality' import type { DecryptedMessage, Session } from '@/types/api' +import { getSessionTitle, hasSessionTitleSignal } from '@/lib/sessionTitle' import { formatMessage } from './contextFormatters' import { VOICE_CONFIG } from '../voiceConfig' @@ -21,13 +22,13 @@ export interface SessionVoiceContextPlan { } function formatSessionHeader(session: Session): string { - const summary = session.metadata?.summary?.text?.trim() const path = session.metadata?.path + const title = hasSessionTitleSignal(session) ? getSessionTitle(session) : null const lines = [ 'THIS IS AN ACTIVE SESSION.', `# Session ID: ${session.id}`, path ? `# Project path: ${path}` : '', - summary ? `# Session summary:\n${summary}` : '' + title ? `# Session summary:\n${title}` : '' ].filter(Boolean) return lines.join('\n\n') } From b6849c1d355157853f13a420b6c67e6bf836e054 Mon Sep 17 00:00:00 2001 From: tiborsekera <34183854+tiborsekera@users.noreply.github.com> Date: Thu, 24 Sep 2026 01:24:42 +0200 Subject: [PATCH 17/34] fix(codex): reject history sync for active sessions (#1895) * fix(codex): guard transcript sync for active sessions * test(codex): exercise divergent transcript prefix --- hub/src/web/routes/codexDesktop.test.ts | 39 ++++++++++++++++++++ hub/src/web/routes/codexDesktop.ts | 12 +++++++ web/src/components/SessionHeader.test.tsx | 44 +++++++++++++++++++++++ web/src/components/SessionHeader.tsx | 4 +-- 4 files changed, 97 insertions(+), 2 deletions(-) diff --git a/hub/src/web/routes/codexDesktop.test.ts b/hub/src/web/routes/codexDesktop.test.ts index ddfbd3f4..65c81ed4 100644 --- a/hub/src/web/routes/codexDesktop.test.ts +++ b/hub/src/web/routes/codexDesktop.test.ts @@ -437,6 +437,45 @@ describe('Codex Desktop import routes', () => { } }) + it('refuses a transcript import for an active Codex thread when stored messages do not match its prefix', async () => { + const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-active-sync-test-')) + const store = new Store(':memory:') + const codexSessionId = '10101010-1010-4010-8010-101010101010' + process.env.CODEX_HOME = codexHome + + try { + createTranscript(codexHome, codexSessionId) + const liveSession = store.sessions.getOrCreateSession('live-session', { + path: 'C:\\work\\project', + flavor: 'codex', + codexSessionId + }, {}, 'default') + store.messages.addMessage(liveSession.id, { + role: 'user', + content: { type: 'text', text: 'different from the transcript' } + }, 'live-1') + const engine = { + getSessionsByNamespace: () => [{ ...liveSession, active: true }] + } as unknown as SyncEngine + + const result = await importSelectedCodexSessions({ + codexSessionIds: [codexSessionId], + store, + namespace: 'default', + getSyncEngine: () => engine + }) + + expect(result.success).toBe(false) + if (result.success) throw new Error('Expected active-session transcript import to fail') + expect(result.error).toContain('matching HAPI session is active') + expect(store.sessions.getSessionsByNamespace('default')).toHaveLength(1) + expect(store.messages.getAllMessages(liveSession.id)).toHaveLength(1) + } finally { + store.close() + rmSync(codexHome, { recursive: true, force: true }) + } + }) + it('updates an existing forked import when syncing the original Codex session id', async () => { const codexHome = mkdtempSync(join(tmpdir(), 'hapi-codex-home-source-test-')) const store = new Store(':memory:') diff --git a/hub/src/web/routes/codexDesktop.ts b/hub/src/web/routes/codexDesktop.ts index fb54b67f..05913d41 100644 --- a/hub/src/web/routes/codexDesktop.ts +++ b/hub/src/web/routes/codexDesktop.ts @@ -2013,6 +2013,18 @@ function importSingleCodexSession(options: { try { const candidates = collectImportCandidates(options.store, options.namespace, options.getSyncEngine) + const activeCandidate = candidates.find((candidate) => ( + candidate.active + && getCodexImportIds(candidate.metadata).includes(options.codexSessionId) + && ( + !options.machineId + || typeof candidate.metadata?.machineId !== 'string' + || candidate.metadata.machineId === options.machineId + ) + )) + if (activeCandidate) { + throw new Error('Cannot sync Codex transcript while the matching HAPI session is active') + } const target = selectImportTargetSession( options.store, candidates, diff --git a/web/src/components/SessionHeader.test.tsx b/web/src/components/SessionHeader.test.tsx index de968259..a78780af 100644 --- a/web/src/components/SessionHeader.test.tsx +++ b/web/src/components/SessionHeader.test.tsx @@ -58,6 +58,18 @@ function renderHeader(session: Session, extra?: { serviceTier?: string | null; t ) } +function renderHeaderWithApi(session: Session, api: ApiClient) { + return render( + + + + + + + + ) +} + describe('resolveSessionHeaderMachineLabel', () => { it('prefers cached/display labels, then host, then short machine id', () => { expect(resolveSessionHeaderMachineLabel( @@ -83,6 +95,38 @@ describe('resolveSessionHeaderMachineLabel', () => { }) describe('SessionHeader', () => { + it('does not offer manual Codex sync while the HAPI session is active', () => { + const api = { + getMachines: vi.fn().mockResolvedValue({ machines: [] }), + getScratchlist: vi.fn().mockResolvedValue({ entries: [] }), + syncCodexSession: vi.fn() + } as unknown as ApiClient + + renderHeaderWithApi(baseSession({ + active: true, + metadata: { flavor: 'codex', path: '/repo', host: 'machine', codexSessionId: 'codex-thread-1' } + }), api) + + fireEvent.click(screen.getByRole('button', { name: /More/ })) + expect(screen.queryByRole('menuitem', { name: /Sync Codex/ })).toBeNull() + }) + + it('keeps manual Codex sync available for an inactive imported thread', () => { + const api = { + getMachines: vi.fn().mockResolvedValue({ machines: [] }), + getScratchlist: vi.fn().mockResolvedValue({ entries: [] }), + syncCodexSession: vi.fn() + } as unknown as ApiClient + + renderHeaderWithApi(baseSession({ + active: false, + metadata: { flavor: 'codex', path: '/repo', host: 'machine', codexSessionId: 'codex-thread-1' } + }), api) + + fireEvent.click(screen.getByRole('button', { name: /More/ })) + expect(screen.getByRole('menuitem', { name: /Sync Codex/ })).toBeInTheDocument() + }) + it('hides title generation when the Hub does not advertise the capability', () => { const api = { getMachines: vi.fn().mockResolvedValue({ machines: [] }), diff --git a/web/src/components/SessionHeader.tsx b/web/src/components/SessionHeader.tsx index f42ac39f..1939300f 100644 --- a/web/src/components/SessionHeader.tsx +++ b/web/src/components/SessionHeader.tsx @@ -268,7 +268,7 @@ export function SessionHeader(props: { } const handleSyncCodex = async () => { - if (!api || !codexSessionId || isSyncingCodex) return + if (!api || !codexSessionId || isSyncingCodex || session.active) return setIsSyncingCodex(true) try { @@ -523,7 +523,7 @@ export function SessionHeader(props: { onMarkUnread={() => markSessionUnread(session.id, session.updatedAt)} onSetPinMode={api ? (mode) => void handleSetPinMode(mode) : undefined} onExport={() => setExportOpen(true)} - onSyncCodex={api && codexSessionId ? handleSyncCodex : undefined} + onSyncCodex={api && codexSessionId && !session.active ? handleSyncCodex : undefined} onSyncPi={api && piSessionId && !session.active ? handleSyncPi : undefined} onArchive={() => setArchiveOpen(true)} onReopen={props.canReopen === false ? undefined : handleReopen} From 97cf69bb5989e64569514a58de959e7c5f06e693 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Thu, 24 Sep 2026 00:25:17 +0100 Subject: [PATCH 18/34] feat(web): dictate keyboard shortcut (Ctrl/Cmd+Shift+D) (#1902) * feat(web): add Ctrl/Cmd+Shift+D dictate keyboard shortcut Toggle composer dictation or voice assistant via the same path as the mic buttons, with dialog/input guards and tooltip documentation. Fixes tiann/hapi#1900 Co-authored-by: Cursor * fix(web): address dictate hotkey bot findings on PR 1902 Ignore key repeat on the session listener and align assistant-mode invoke guards with UnifiedButton send mode (canSend). Co-authored-by: Cursor --------- Co-authored-by: Cursor --- .../AssistantChat/ComposerButtons.test.tsx | 2 +- .../AssistantChat/HappyComposer.tsx | 35 +++++++ web/src/components/SessionChat.tsx | 26 +++++ web/src/lib/composerDictateShortcut.test.ts | 99 +++++++++++++++++++ web/src/lib/composerDictateShortcut.ts | 62 ++++++++++++ web/src/lib/locales/en.ts | 2 +- web/src/lib/locales/zh-CN.ts | 2 +- 7 files changed, 225 insertions(+), 3 deletions(-) create mode 100644 web/src/lib/composerDictateShortcut.test.ts create mode 100644 web/src/lib/composerDictateShortcut.ts diff --git a/web/src/components/AssistantChat/ComposerButtons.test.tsx b/web/src/components/AssistantChat/ComposerButtons.test.tsx index d6ac051b..3b7df015 100644 --- a/web/src/components/AssistantChat/ComposerButtons.test.tsx +++ b/web/src/components/AssistantChat/ComposerButtons.test.tsx @@ -177,7 +177,7 @@ describe('DictationButton', () => { />, ) - fireEvent.click(getButton('Dictate')) + fireEvent.click(getButton(/^Dictate/)) expect(onVoiceToggle).toHaveBeenCalledOnce() }) }) diff --git a/web/src/components/AssistantChat/HappyComposer.tsx b/web/src/components/AssistantChat/HappyComposer.tsx index 78ddb242..5be36c39 100644 --- a/web/src/components/AssistantChat/HappyComposer.tsx +++ b/web/src/components/AssistantChat/HappyComposer.tsx @@ -21,6 +21,7 @@ import { useState } from 'react' import { useNarrowViewport } from '@/hooks/useNarrowViewport' +import { shouldInvokeComposerDictateShortcut } from '@/lib/composerDictateShortcut' import { isRichComposerMentionsEnabled, resolveComposerPlaceholderKey } from '@/lib/composerSegments' import type { SessionMentionResolveResult } from '@/components/AssistantChat/RichComposerInput' import { @@ -364,6 +365,8 @@ export function HappyComposer(props: { ) => Promise /** Parent disables DragDropZone / scratchlist promote while park is in flight. */ onScratchlistParkingChange?: (parking: boolean) => void + /** SessionChat binds Ctrl/Cmd+Shift+D; HappyComposer registers the effective voice toggle. */ + dictateHotkeyRef?: MutableRefObject<(() => void) | null> // Set when the most recent send failed (4xx/5xx/network). The composer // restores the original text once per `sendError.id` and renders an // inline error affordance until the user dismisses or starts editing. @@ -1623,6 +1626,38 @@ export function HappyComposer(props: { ) const showAbortButton = true const voiceEnabled = Boolean(effectiveVoiceToggle) + const routesToScratchlist = (props.scratchlistMode ?? false) && pendingSchedule == null + + const invokeDictateHotkey = useCallback(() => { + if (!shouldInvokeComposerDictateShortcut({ + controlsDisabled, + voiceEnabled, + dictationActive, + voiceStatus: effectiveVoiceStatus, + canSend, + routesToScratchlist, + })) { + return + } + effectiveVoiceToggle?.() + }, [ + controlsDisabled, + voiceEnabled, + dictationActive, + effectiveVoiceStatus, + canSend, + routesToScratchlist, + effectiveVoiceToggle, + ]) + + useEffect(() => { + const ref = props.dictateHotkeyRef + if (!ref) return + ref.current = invokeDictateHotkey + return () => { + ref.current = null + } + }, [props.dictateHotkeyRef, invokeDictateHotkey]) // Generic model/effort value buttons. The current value label doubles as // the button caption; clicking opens the settings sheet. Hidden on narrow diff --git a/web/src/components/SessionChat.tsx b/web/src/components/SessionChat.tsx index e8dd5e77..6a2a562f 100644 --- a/web/src/components/SessionChat.tsx +++ b/web/src/components/SessionChat.tsx @@ -35,6 +35,10 @@ import { } from '@/lib/codexModelCapabilities' import { createSerialAsyncQueue } from '@/lib/serialAsyncQueue' import { HappyComposer, type ComposerSendError } from '@/components/AssistantChat/HappyComposer' +import { + isDictateHotkeyBlockedTarget, + isDictateToggleHotkey, +} from '@/lib/composerDictateShortcut' import { codexModelAdvertisesFastTier, getEffectiveCodexServiceTier } from '@/components/AssistantChat/codexFastMode' import type { PendingSchedule } from '@/components/AssistantChat/ScheduleTimePicker' import { resolvePendingSchedule } from '@/components/AssistantChat/ScheduleTimePicker' @@ -767,6 +771,7 @@ function SessionChatInner(props: SessionChatProps) { if (isScratchlistParking) return setScratchlistMode((m) => !m) }, [isScratchlistParking]) + const dictateHotkeyRef = useRef<(() => void) | null>(null) /** * Global keyboard shortcut: Ctrl/Cmd + Shift + S toggles scratchlist * mode (open/close drawer + flip composer routing). @@ -800,6 +805,26 @@ function SessionChatInner(props: SessionChatProps) { window.addEventListener('keydown', onKeyDown) return () => window.removeEventListener('keydown', onKeyDown) }, [isScratchlistParking]) + /** + * Global keyboard shortcut: Ctrl/Cmd + Shift + D toggles composer + * dictation (Settings → Voice mode: dictation) or voice assistant, + * using the same effective toggle as the mic / dictate buttons in + * HappyComposer. Skipped for dialog / single-line input targets; + * rich composer input is allowed (see isDictateHotkeyBlockedTarget). + */ + useEffect(() => { + const onKeyDown = (e: globalThis.KeyboardEvent) => { + if (e.repeat) return + if (!isDictateToggleHotkey(e)) return + if (isDictateHotkeyBlockedTarget(e.target)) return + const invoke = dictateHotkeyRef.current + if (!invoke) return + e.preventDefault() + invoke() + } + window.addEventListener('keydown', onKeyDown) + return () => window.removeEventListener('keydown', onKeyDown) + }, []) /** * Global select-all takeover: see applyGlobalSelectAll. Bound at * window scope because the broken case is focus on the page body / @@ -2210,6 +2235,7 @@ function SessionChatInner(props: SessionChatProps) { onScratchlistToggle={handleScratchlistToggle} onParkScratchlist={onParkScratchlist} onScratchlistParkingChange={setIsScratchlistParking} + dictateHotkeyRef={dictateHotkeyRef} sendError={props.sendError ?? null} onClearSendError={handleClearSendError} onSuppressSendErrorRestore={props.onSuppressSendErrorRestore} diff --git a/web/src/lib/composerDictateShortcut.test.ts b/web/src/lib/composerDictateShortcut.test.ts new file mode 100644 index 00000000..817bf1e1 --- /dev/null +++ b/web/src/lib/composerDictateShortcut.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest' +import { + isDictateHotkeyBlockedTarget, + isDictateToggleHotkey, + shouldInvokeComposerDictateShortcut, +} from './composerDictateShortcut' + +describe('isDictateToggleHotkey', () => { + function k(over: Partial<{ + metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean; key: string + }>): { metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean; key: string } { + return { metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, key: '', ...over } + } + + it('matches Ctrl+Shift+D and Cmd+Shift+D', () => { + expect(isDictateToggleHotkey(k({ ctrlKey: true, shiftKey: true, key: 'D' }))).toBe(true) + expect(isDictateToggleHotkey(k({ metaKey: true, shiftKey: true, key: 'd' }))).toBe(true) + }) + + it('rejects bare D and Ctrl+D without shift', () => { + expect(isDictateToggleHotkey(k({ key: 'd' }))).toBe(false) + expect(isDictateToggleHotkey(k({ ctrlKey: true, key: 'd' }))).toBe(false) + }) + + it('rejects unrelated keys with the modifier chord', () => { + expect(isDictateToggleHotkey(k({ ctrlKey: true, shiftKey: true, key: 'S' }))).toBe(false) + }) +}) + +describe('isDictateHotkeyBlockedTarget', () => { + it('blocks single-line inputs and dialogs like scratchlist', () => { + const input = document.createElement('input') + expect(isDictateHotkeyBlockedTarget(input)).toBe(true) + }) + + it('allows the rich composer contentEditable host', () => { + const shell = document.createElement('div') + shell.setAttribute('data-testid', 'rich-composer-input') + const editor = document.createElement('div') + editor.setAttribute('contenteditable', 'plaintext-only') + shell.appendChild(editor) + document.body.appendChild(shell) + expect(isDictateHotkeyBlockedTarget(editor)).toBe(false) + document.body.removeChild(shell) + }) + + it('allows the fallback composer textarea', () => { + const textarea = document.createElement('textarea') + expect(isDictateHotkeyBlockedTarget(textarea)).toBe(false) + }) +}) + +describe('shouldInvokeComposerDictateShortcut', () => { + const base = { + controlsDisabled: false, + voiceEnabled: true, + dictationActive: false, + voiceStatus: 'disconnected' as const, + canSend: false, + routesToScratchlist: false, + } + + it('stops an active voice session', () => { + expect(shouldInvokeComposerDictateShortcut({ + ...base, + voiceStatus: 'connected', + })).toBe(true) + }) + + it('starts assistant voice on an empty composer', () => { + expect(shouldInvokeComposerDictateShortcut(base)).toBe(true) + }) + + it('does not start assistant voice when UnifiedButton is in send mode', () => { + expect(shouldInvokeComposerDictateShortcut({ ...base, canSend: true })).toBe(false) + }) + + it('starts dictation on an empty composer when scratchlist routing is off', () => { + expect(shouldInvokeComposerDictateShortcut({ + ...base, + dictationActive: true, + })).toBe(true) + }) + + it('allows dictation when a draft makes canSend true', () => { + expect(shouldInvokeComposerDictateShortcut({ + ...base, + dictationActive: true, + canSend: true, + })).toBe(true) + }) + + it('suppresses scratchlist-routed empty composer starts', () => { + expect(shouldInvokeComposerDictateShortcut({ + ...base, + routesToScratchlist: true, + })).toBe(false) + }) +}) diff --git a/web/src/lib/composerDictateShortcut.ts b/web/src/lib/composerDictateShortcut.ts new file mode 100644 index 00000000..44f8df27 --- /dev/null +++ b/web/src/lib/composerDictateShortcut.ts @@ -0,0 +1,62 @@ +import type { ConversationStatus } from '@/realtime/types' + +/** + * True if the keystroke matches the composer dictation / voice toggle shortcut + * (Ctrl/Cmd + Shift + D, no Alt). Pure for unit tests. + * + * Modifier shape matches scratchlist (Ctrl/Cmd+Shift+S) and model cycle + * (Ctrl/Cmd+M). Shift+D avoids browser bookmark / devtools clashes on bare D. + */ +export function isDictateToggleHotkey(e: { + metaKey: boolean + ctrlKey: boolean + shiftKey: boolean + altKey: boolean + key: string +}): boolean { + if (!(e.metaKey || e.ctrlKey)) return false + if (!e.shiftKey) return false + if (e.altKey) return false + return e.key === 'D' || e.key === 'd' +} + +/** + * True when the global dictate hotkey should be SKIPPED for the event target. + * + * Same dialog / single-line input guards as scratchlist + * (`isScratchlistHotkeyBlockedTarget`), but the rich composer (contentEditable) + * is allowed so the shortcut works while typing in the main input. + */ +export function isDictateHotkeyBlockedTarget(target: EventTarget | null): boolean { + if (!(target instanceof HTMLElement)) return false + if (target.closest('[data-testid="rich-composer-input"]') !== null) return false + if (target.closest('[role="dialog"]') !== null) return true + if (target instanceof HTMLInputElement) return true + if (target instanceof HTMLSelectElement) return true + if (target.isContentEditable === true) return true + return target.getAttribute('contenteditable') === 'true' +} + +/** + * Mirrors DictationButton + UnifiedButton voice-start/stop rules so the hotkey + * does not send chat text or start voice when the mic UI would not. + */ +export function shouldInvokeComposerDictateShortcut(args: { + controlsDisabled: boolean + voiceEnabled: boolean + dictationActive: boolean + voiceStatus: ConversationStatus + canSend: boolean + routesToScratchlist: boolean +}): boolean { + if (args.controlsDisabled || !args.voiceEnabled) return false + const isVoiceActive = args.voiceStatus === 'connecting' || args.voiceStatus === 'connected' + if (isVoiceActive) return true + if (args.dictationActive) { + if (args.canSend) return true + return !args.routesToScratchlist + } + // UnifiedButton treats canSend (text or attachments) as Send mode for assistant voice. + if (args.canSend) return false + return !args.routesToScratchlist +} diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index 647b8005..cfdc81fb 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -660,7 +660,7 @@ export default { 'composer.send': 'Send', 'composer.stop': 'Stop', 'composer.voice': 'Voice assistant', - 'composer.dictate': 'Dictate', + 'composer.dictate': 'Dictate (Ctrl/Cmd+Shift+D)', 'composer.scheduleSend': 'Schedule send', 'composer.scheduleRelativeTab': 'Relative', 'composer.scheduleSpecificTab': 'Specific', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 6886e3ae..2c3bf400 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -658,7 +658,7 @@ export default { 'composer.send': '发送', 'composer.stop': '停止', 'composer.voice': '语音助手', - 'composer.dictate': '语音输入', + 'composer.dictate': '语音输入 (Ctrl/Cmd+Shift+D)', 'composer.scheduleSend': '定时发送', 'composer.scheduleRelativeTab': '相对时间', 'composer.scheduleSpecificTab': '指定时间', From 86c88df93baf5d1f738dd4b202078bdf6dec376e Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Fri, 25 Sep 2026 09:15:08 +0100 Subject: [PATCH 19/34] fix(runner,hub): cross-platform orphan reap on archive / tracking loss (#1911) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(runner,hub): reap detached driver CLI on archive and tracking loss Archive always verifies via stopRunnerSession; runner stopSession scans argv orphans and awaits webhook-timeout tree-kill so PPID=1 children cannot accumulate after KillSession miss or map drop. Fixes #1910 Co-authored-by: Cursor * fix(cli): keep --hapi-session-id reap-only; test orphan kill path Claude/cursor swallow the stamp without bootstrap reuse, and reapRunnerSpawnedOrphans is unit-tested as the stopSession map-miss path. Co-authored-by: Cursor * fix(cli,hub): address #1911 CI and bot Majors Use Vitest in orphanReap tests, add Pi session.on mock, refuse archive when machine StopSession is unreachable, trust full tree-kill results, and argv-sweep orphans after every mapped stop. Co-authored-by: Cursor * fix(runner): gate late-webhook kill on timeout orphans; fail closed on scan error Track webhook-timeout PIDs separately so recovered shared roots are not killed, and treat ps-list failures as still_alive rather than empty. Co-authored-by: Cursor * fix(runner): keep shared Codex wrapper alive when archiving one root StopSession must detach a single shared root without tree-killing the wrapper PID while sibling roots remain, including after KillSession has already marked the runtime inactive. Co-authored-by: Cursor * fix(runner): keep shared Codex siblings after restart tracking loss Before persisted-PID or argv orphan kills, consult the durable runtime registry for active sibling roots on the same wrapper PID so archiving one root after a runner restart cannot tree-kill live shared sessions. Co-authored-by: Cursor * fix(hub,cli): deliver hub-authored archive metadata to reconnecting CLIs When KillSession misses and archive is written via markSessionArchivedFromHub, emit Socket.IO update-session to the session room. On reconnect, ApiSessionClient reconciles GET /cli/sessions/:id metadata so hub-archived still fires. Co-authored-by: Cursor * fix(runner): argv-scan orphans even when shared siblings remain Remove session-wide early returns that skipped orphan reaping whenever any shared wrapper had active siblings. Keep only the PID-specific filter so older untracked CLIs with the same HAPI id are still reaped. Co-authored-by: Cursor * fix(runner): protect tracked shared wrappers when runtime registry is empty Argv orphan sweeps must exclude in-memory shared wrapper PIDs that still host sibling roots, not only durable registry siblings — otherwise a missing runtime record lets the sweep tree-kill the wrapper while archiving one root. Co-authored-by: Cursor * fix(runner): adopt untracked nonshared CLIs after runner restart When a runner-spawned Claude webhook arrives with no TrackedSession (typical after restart mid-bootstrap), durably adopt the PID instead of ignoring it so StopSession can reap. Keep killing only nonshared timeout orphans; never kill shared Codex wrappers on late webhooks. Co-authored-by: Cursor * fix(runner): keep recovered shared wrappers for registry siblings After restart adoption tracks only a newly reported Codex root, archiving it must consult the durable registry before tree-killing the wrapper PID so older active sibling roots survive. Co-authored-by: Cursor * fix(hub): do not archive on KillSession ack when StopSession is unknown KillSession returns before cleanupAndExit finishes. When the runner cannot find the PID (unknown), wait for the session KillSession handler to drop before archiving; refuse if the CLI socket remains reachable. Co-authored-by: Cursor * fix(hub,cli): confirm KillSession pid via StopSession before archive KillSession now returns the CLI pid. When session-id StopSession is unknown, archive confirms that OS pid (without treating socket loss as exit) and still refuses when confirmation stays unknown or still_alive. Co-authored-by: Cursor * fix(runner,hub): tree-kill adopted CLIs and require PID start markers Adopted post-restart runner sessions now use killProcessTreeByPid when no ChildProcess handle exists. KillSession carries a process-start marker so raw PID confirmation cannot tree-kill a reused OS pid. Co-authored-by: Cursor * fix(runner,hub): verify adopted PID markers and hub-archive after stop Adopted sessions compare the persisted start marker before tree-kill and drop stale tracking on mismatch. After confirmed StopSession, hub-authors archive metadata when the CLI did not finish its flush. Co-authored-by: Cursor * fix(runner): refuse unconfirmed shared/adopted stops Keep shared wrappers when siblings remain, but return unknown unless runtimeControl already ended the root. Adopted PIDs without a start marker no longer tree-kill by tracked PID alone. Co-authored-by: Cursor * fix(runner): require inactive binding before sibling-kept archive Siblings alone must not flip StopSession to stopped on retry, while an acknowledged inactive Codex registry binding remains stop proof. Handle PID- markers before any tracked kill so reuse cannot nuke strangers. Co-authored-by: Cursor * fix(runner): distinguish orphan reap from unknown keep-wrapper base Pass unknown into finishWithOrphanSweep so a successful argv reap stays stopped instead of being overwritten by an absent registry binding. Co-authored-by: Cursor * fix(runner): honor orphan reap when adopted PID lacks a start marker finishWithOrphanSweep with an unknown base lets a successful argv kill report stopped instead of forcing unknown after the marker probe fails. Co-authored-by: Cursor * fix(hub): confirm archive via metadata.hostPid tombstone When StopSession(sessionId) is unknown and KillSession supplies no confirmable pid+marker, probe PID-. already_gone allows archive; still_alive/unknown still refuse (#1911 Peer #1820). Co-authored-by: Cursor * fix(cli): escalate Windows taskkill to /F like SIGTERM→SIGKILL Soft taskkill /T is refused on win32 console trees; orphanReap left orphans still_alive. waitForProcessToDie now force-escalates on both platforms so cross-platform reaping matches. Co-authored-by: Cursor * fix(cli): widen process.kill mock signal to string | number Match @types/node process.kill(pid, signal?: string | number) so the Windows taskkill escalation mocks typecheck on tip 54f141368. Co-authored-by: Cursor * fix(cli): tasklist liveness + immediate /F after soft taskkill refuse Windows orphan reap still failed in 5ms on Teemo: soft taskkill refused but escalate waited on an unreliable process.kill(0) probe. Prefer tasklist for win32 liveness and escalate to /F as soon as the PID is still live after soft kill. Co-authored-by: Cursor * fix(cli): coerce win32 ps-list PIDs and escalate soft taskkill to /F String PIDs from ps-list made Number.isFinite fail so orphan kill returned still_alive without calling taskkill. Coerce PIDs, prefer tasklist liveness, and escalate soft taskkill to /F like SIGTERM→SIGKILL. Co-authored-by: Cursor * fix(cli): Windows orphan scan via CIM CommandLine + taskkill /F escalate ps-list/fastlist is missing CommandLine and often missing from single-exe bundles, so Teemo orphan reap returned scan_failed (logged as live PIDs). List via Win32_Process CIM, coerce PIDs, escalate soft taskkill to /F. Co-authored-by: Cursor * fix(cli): grace-wait after successful soft taskkill before /F Escalate immediately only when soft taskkill is refused. When soft succeeds but the PID is still draining, honor the existing grace period before force (Codex Major on #1911). Co-authored-by: Cursor * fix(runner): re-verify start marker before orphan argv tree-kill Capture getProcessStartMarker after the argv match list, re-check immediately before killTree, and skip on mismatch/null-while-alive so PID reuse cannot tree-kill an unrelated process on the orphan fallback. Co-authored-by: Cursor * fix(hub): preallocate HAPI id before fresh machine spawn Fresh POST /machines/:id/spawn omitted existingSessionId, so argv never got a reap stamp. Preallocate the hub row (fork/clear pattern) and pass that id so a runner restart before the first webhook remains reapeable. Co-authored-by: Cursor * fix(cli,hub): close three post-prealloc unreapable paths Pass --hapi-session-id into Claude/cursor/kimi/copilot bootstrap so the preallocated hub row is used. Treat null marker re-check while alive as still_alive (not stopped). Keep the preallocated stub when spawn-fail StopSession cannot confirm the child is gone. Co-authored-by: Cursor * fix(cli): adopt-stub via reservedSessionId, not existingSessionId `--hapi-session-id` binds a fresh create bootstrap to a hub-preallocated UUID (getOrCreateSession id) without taking the reopen path. Non-UUID stamps stay reap-only to match hub create schema. Restores integration spawn invariants broken by mapping hapi→existingSessionId. Co-authored-by: Cursor * fix(cli,hub): close Opus cold-read B1–B3 for #1911 B1: capture start markers from the same process snapshot as argv match (POSIX ps lstart / Win32 CreationDate); re-check before kill. Continue other orphans when one target is unconfirmed. B2: Windows killProcessTreeByPid verifies every collected descendant, not root-only — taskkill /T exit 0 is signalled, not gone. B3: runner sets childStarted:false on pre-exec rejection; hub deletes the preallocated stub without StopSession. Post-exec ambiguity still keeps the row until stop confirms. Terminal archives no longer refuse when no runner is connected. Co-authored-by: Cursor * fix(cli,hub): explicit adopt for hub-preallocated session stubs Fresh machine spawn preallocates with tag machine-spawn:; CLI create with a different tag and the same id 409'd on identity conflict. Add adoptPreallocatedSession (hub-internal stub check) and POST /cli/sessions { adopt: true, id } so create binds the reserved row and overwrites tag/metadata without guessing the hub tag. Tests fail-first on the real prealloc→CLI create path. Co-authored-by: Cursor * fix(cli): preserve snapshot markers + unify Windows CIM start markers Runner stopSession was still on findOrphans (PID-only), discarding same-snapshot markers and reopening the PID-reuse kill window. Switch both call sites to findTargets. Force UTC ISO 'o' CreationDate for list and single-PID probe so ConvertTo-Json cannot disagree with getProcessStartMarker on WinPS 5.1. Co-authored-by: Cursor * fix(cli): exercise production orphan sweep wiring in tests Extract findStopSessionOrphanTargets as the stopSession discovery path both run.ts sweeps call. Add tests that drive that helper end-to-end (not an injected findOrphans seam), assert run.ts source wiring, and cover CIM-list ISO vs probe ISO agreement plus the broken WinPS shape mismatch. Co-authored-by: Cursor * fix(hub,cli): never delete live spawn on RPC timeout; release stub tags Ambiguous machine-spawn failures (timeout / unset childStarted) no longer call stopRunnerSession or deleteSession — that path killed healthy late boots and CASCADE-wiped transcripts. Pre-exec delete still requires a real machine-spawn stub (store tag check). Metadata updates release the stub tag so reopen flavors are not permanently adoptable; adopt refuses archived stubs. POSIX pgrep ENOENT fails closed instead of root-only verify. Co-authored-by: Cursor * fix(cli): parseable Windows tree scan + fail closed on CIM failure Space-joined PowerShell for collectWindowsProcessTree was a WinPS parse error ($seen=@{} $bfs=@()), so every scan fell open to [root] and B2 false-stopped again. Join with newlines; return scan_failed on error/empty; killProcessTreeByPid refuses root-only verify. Assert on generated command text (Teemo-confirmed) so mocks cannot hide the next malformed script. Co-authored-by: Cursor * fix(cli,hub): reopen stamps existing-session-id; scan-fail signals root Opus Critical on #1911: runner always stamps --existing-session-id for known hub ids so Claude/Kimi/Copilot reopen does not hit adopt-stub 409. On pgrep/CIM tree-scan failure still signal the verified root but never claim stopped. Archive when both KillSession and machine RPC are missing. Empty Win process-list stdout and strict Codex registry reads fail closed. Co-authored-by: Cursor * fix(cli,hub): OK: sentinel for Windows tree scan; adopt CAS CIM failure under SilentlyContinue printed root-only with exit 0 — byte-identical to a healthy childless tree, so scan_failed never fired and killProcessTreeByPid false-stopped (#1911 Overseer B1). Require ErrorActionPreference=Stop, trap exit 1, and an OK: success sentinel; parse anything else as scan_failed. Same Stop/trap on the machine-wide list command. Execute the generated scripts under Docker pwsh in CI when the image is present. Treat pgrep status=null as scan_failed; coarsen Windows tasklist poll; wrap adoptPreallocatedSession in a transaction with stub-tag CAS. Co-authored-by: Cursor * fix(cli,hub): reservedSessionId for fresh prealloc; signal Win survivors Fresh machine-spawn stubs must not stamp --existing-session-id — that sends Codex down reopen without a thread binding (#1911 bot Major) and re-broke local HTTP non-UUID hints as reopen (round-4). Hub passes prealloc as reservedSessionId; buildCliArgs stamps --hapi-session-id for reserved/sessionId and --existing-session-id only for live reopen. Codex parses --hapi-session-id and adopts via bootstrapSession. Windows tree kill now taskkills surviving pre-scan PIDs after /T misses broken intermediate links. Co-authored-by: Cursor * fix(cli,hub): fail-loud Docker pwsh CI; scope Codex registry; stub leak CI skipped all four windowsProcessTree.pwsh tests on 48bb (image inspect without pull). Pull the image in test.yml and throw under CI when missing. Scope strict runtime-registry failure to Codex stop contexts so one bad JSON cannot block archive machine-wide. Stamp childStarted:false on machine RPC outside_workspace_roots. Add Codex reservedSessionId prealloc and runSharedCodex regression coverage for the #1911 Critical. Co-authored-by: Cursor * fix(cli,hub): single-use reservedSessionId; skip UUID HTTP hints Consume the machine-spawn reservation on first prepare() so a second Codex root/fork cannot re-adopt a consumed stub (409). Stop stamping UUID local-HTTP sessionId as --hapi-session-id (adopt hard-fail). Update stale hub spawn mocks for the reservedSessionId arity. Co-authored-by: Cursor * fix(hub): archive never-started machine-spawn stubs on unknown Ambiguous keep-stubs (startedBy=runner, no hostPid, still machine-spawn tagged) made StopSession return unknown forever while the runner was online, so archive threw permanently. Treat unknown + prealloc stub + no hostPid as already_gone. Also reject spawn success when the runner reports a different id than the preallocated stub. Co-authored-by: Cursor * fix(hub,cli): refuse dual-RPC-miss archive; generation-check Win survivors Both KillSession and StopSession missing is not proof a detached CLI exited — keep the row unconfirmed until the runner reconnects. Windows tree kill now re-checks process-start markers before individually signalling survivors so PID reuse is not killed. Co-authored-by: Cursor * fix(cli): refuse archived reopen in bootstrapExistingSession Hub-archived rows could be resurrected when a late-booting child hit --existing-session-id: buildSessionMetadata stamped lifecycleState=running and updateMetadata overwrote the archive. Adopt already rejected archived stubs; reopen now matches. Intentional revive still goes through hub reopenSession first. Correct stub-hatch comment (no post-archive argv sweep). Co-authored-by: Cursor * fix(hub,cli): reject un-archive in updateSessionMetadata CAS Hub-side transactional guard (Discovery #1911 M1): refuse metadata writes that clear archived lifecycle unless allowUnarchive (reopen clear). Client stops infinite updateMetadata backoff when mismatch applies archived. Clear archive immediately before spawn so Pi/PTY attempt snapshots stay valid. Co-authored-by: Cursor * fix(hub,cli): success+preserve hub archive; M3 reservedSessionId split Replace version-mismatch refuse (livelock in CAS backoff) with success + merge-preserve of hub-archived fields unless allowUnarchive. Ack path routes through noteHubArchived so the CLI exits (criterion 6). Clear- before-spawn remains the authorized revive. Thread --hapi-session-id to reservedSessionId for shared-parser flavors (adopt≠reopen). Co-authored-by: Cursor * fix(cli): fail-closed orphan ps signal; PID- registry; spawn timeouts Overseer B1: signalled ps (status null) is scan_failed, not empty table. B2: unreadable registry on PID-* stops returns null (no soft []). B3: 10s timeout on process/orphanReap spawn.sync. Narrow bootstrap archived belt to archivedBy=hub to match hub merge-preserve. Co-authored-by: Cursor * fix(cli,hub): hubArchived latch; PTY archiveSnapshot durability Criterion 6: noteHubArchived latches hubArchived so late registerKillSessionHandler registrations still EXIT (EventEmitter does not replay). Mirror Pi: persist archiveSnapshot on ptyResumeAttempt across clear-before-spawn and quarantine, restore on failed-resume cleanup (#1911 Discovery Majors). Co-authored-by: Cursor * fix(cli): Codex hub-archived exit; AC6 latch test production order C2: SharedCodexRoot registers hub-archived (and latch check) beside its private KillSession — Codex never called registerKillSessionHandler. C1: keep latch+subscribe; test write-then-register order Discovery proved. Co-authored-by: Cursor * fix(cli): type Codex hub-archived end mock for tsc vi.fn(async () => {}) inferred zero-arg calls; RootHost['end'] signature unblocks end.mock.calls[0][0] (TS2493). Co-authored-by: Cursor * fix(cli): catch hub-archived Codex host.end rejection void this.host.end() discarded archive-RPC failures as unhandled rejections; Codex has no unhandledRejection handler, so Node can exit the shared wrapper and kill sibling roots mid-turn. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- .github/workflows/test.yml | 3 + cli/src/agent/runners/runAgentSession.ts | 2 +- cli/src/agent/sessionFactory.test.ts | 115 +++ cli/src/agent/sessionFactory.ts | 49 ++ cli/src/agy/runAgy.ts | 7 +- cli/src/api/api.ts | 3 + cli/src/api/apiMachine.test.ts | 29 + cli/src/api/apiMachine.ts | 17 +- cli/src/api/apiSession.test.ts | 198 ++++- cli/src/api/apiSession.ts | 170 +++- .../claude/registerKillSessionHandler.test.ts | 69 +- cli/src/claude/registerKillSessionHandler.ts | 38 +- cli/src/claude/runClaude.ts | 10 +- cli/src/codex/shared/frontend.test.ts | 22 + cli/src/codex/shared/frontend.ts | 3 +- cli/src/codex/shared/launch.test.ts | 11 +- cli/src/codex/shared/launch.ts | 15 +- cli/src/codex/shared/registry.test.ts | 11 +- cli/src/codex/shared/registry.ts | 4 +- cli/src/codex/shared/root.test.ts | 37 +- cli/src/codex/shared/root.ts | 12 + cli/src/codex/shared/runtime.ts | 11 +- cli/src/commands/agentCommandOptions.test.ts | 11 +- cli/src/commands/agentCommandOptions.ts | 20 +- cli/src/commands/claude.test.ts | 26 +- cli/src/commands/claude.ts | 9 + cli/src/commands/codex.ts | 7 + cli/src/commands/copilot.ts | 15 + cli/src/commands/cursor.ts | 10 + cli/src/commands/kimi.ts | 15 + cli/src/copilot/runCopilot.ts | 7 +- cli/src/cursor/runCursor.ts | 7 +- cli/src/dsh/runDsh.ts | 7 +- cli/src/grok/runGrok.ts | 7 +- cli/src/kimi/runKimi.ts | 7 +- cli/src/modules/common/rpcTypes.ts | 16 +- cli/src/opencode/runOpencode.test.ts | 27 +- cli/src/opencode/runOpencode.ts | 7 +- cli/src/pi/runPi.test.ts | 1 + cli/src/pi/runPi.ts | 7 +- cli/src/runner/buildCliArgs.test.ts | 81 +- cli/src/runner/controlClient.ts | 4 +- cli/src/runner/controlServer.ts | 4 +- cli/src/runner/lateRunnerWebhook.test.ts | 31 + cli/src/runner/lateRunnerWebhook.ts | 26 + cli/src/runner/orphanReap.test.ts | 438 ++++++++++ cli/src/runner/orphanReap.ts | 332 ++++++++ cli/src/runner/run.ts | 592 +++++++++++--- cli/src/runner/runner.integration.test.ts | 5 +- cli/src/runner/sharedSessionStop.test.ts | 243 ++++++ cli/src/runner/sharedSessionStop.ts | 207 +++++ cli/src/utils/process.test.ts | 607 ++++++++++++-- cli/src/utils/process.ts | 286 ++++++- cli/src/utils/windowsProcessTree.pwsh.test.ts | 100 +++ hub/src/store/sessionStore.ts | 18 +- hub/src/store/sessions.test.ts | 348 ++++++++ hub/src/store/sessions.ts | 192 ++++- hub/src/sync/opencodeClear.test.ts | 3 + hub/src/sync/rpcGateway.ts | 51 +- hub/src/sync/sessionCache.ts | 26 +- hub/src/sync/sessionModel.test.ts | 56 +- hub/src/sync/syncEngine.ts | 422 ++++++++-- hub/src/sync/syncEngineArchiveSession.test.ts | 388 +++++++++ .../syncEngineReopenPreservesPtyId.test.ts | 112 ++- hub/src/sync/syncEngineSpawnPrealloc.test.ts | 745 ++++++++++++++++++ hub/src/web/routes/cli.ts | 37 +- hub/src/web/routes/machines.ts | 4 +- shared/src/apiTypes.ts | 13 + shared/src/schemas.ts | 8 + 69 files changed, 6019 insertions(+), 402 deletions(-) create mode 100644 cli/src/runner/lateRunnerWebhook.test.ts create mode 100644 cli/src/runner/lateRunnerWebhook.ts create mode 100644 cli/src/runner/orphanReap.test.ts create mode 100644 cli/src/runner/orphanReap.ts create mode 100644 cli/src/runner/sharedSessionStop.test.ts create mode 100644 cli/src/runner/sharedSessionStop.ts create mode 100644 cli/src/utils/windowsProcessTree.pwsh.test.ts create mode 100644 hub/src/sync/syncEngineArchiveSession.test.ts create mode 100644 hub/src/sync/syncEngineSpawnPrealloc.test.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6c13d0de..5a06a9f2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,6 +15,9 @@ jobs: - run: bun install --frozen-lockfile - run: bun typecheck - run: bunx playwright install --with-deps chromium + # Required by cli/src/utils/windowsProcessTree.pwsh.test.ts — image + # inspect alone does not pull; silent skip was fake B1 coverage (#1911). + - run: docker pull mcr.microsoft.com/powershell:latest - run: bun run test:e2e -- terminal-wrap-fidelity.spec.ts composer-copy.spec.ts session-list-scroll.spec.ts cold-initial-tail.spec.ts scrollbar-auto-hide.spec.ts - run: bun run test diff --git a/cli/src/agent/runners/runAgentSession.ts b/cli/src/agent/runners/runAgentSession.ts index efd33c28..d937ee54 100644 --- a/cli/src/agent/runners/runAgentSession.ts +++ b/cli/src/agent/runners/runAgentSession.ts @@ -161,7 +161,7 @@ export async function runAgentSession(opts: { } }; - registerKillSessionHandler(session.rpcHandlerManager, handleKillSession); + registerKillSessionHandler(session.rpcHandlerManager, handleKillSession, session); let sessionEndReason: SessionEndReason = 'completed'; try { diff --git a/cli/src/agent/sessionFactory.test.ts b/cli/src/agent/sessionFactory.test.ts index fb50342e..7f0aed55 100644 --- a/cli/src/agent/sessionFactory.test.ts +++ b/cli/src/agent/sessionFactory.test.ts @@ -135,6 +135,61 @@ describe('bootstrapExistingSession', () => { ) }) + it('refuses to reopen a hub-archived session (hub-archive resurrection guard)', async () => { + // #1911 M1 belt: hub-archived only (matches store merge-preserve scope). + const session = createSession() + const existing = session.metadata + if (!existing) throw new Error('expected metadata') + session.metadata = { + ...existing, + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'Archived from hub', + } + const sessionClient = { updateMetadata: vi.fn() } + getSessionMock.mockResolvedValue(session) + getOrCreateMachineMock.mockResolvedValue({ id: 'machine-1' }) + sessionSyncClientMock.mockReturnValue(sessionClient) + readSettingsMock.mockResolvedValue({ machineId: 'machine-1' }) + + await expect(bootstrapExistingSession({ + sessionId: 'hapi-session-1', + flavor: 'claude', + workingDirectory: '/tmp/project', + startedBy: 'runner', + })).rejects.toThrow(/hub-archived|archived/) + + expect(sessionClient.updateMetadata).not.toHaveBeenCalled() + expect(notifyRunnerSessionStartedMock).not.toHaveBeenCalled() + expect(sessionSyncClientMock).not.toHaveBeenCalled() + }) + + it('allows reopen of CLI self-archived sessions (archivedBy=cli)', async () => { + const session = createSession() + const existing = session.metadata + if (!existing) throw new Error('expected metadata') + session.metadata = { + ...existing, + lifecycleState: 'archived', + archivedBy: 'cli', + archiveReason: 'clean exit', + } + const sessionClient = { updateMetadata: vi.fn() } + getSessionMock.mockResolvedValue(session) + getOrCreateMachineMock.mockResolvedValue({ id: 'machine-1' }) + sessionSyncClientMock.mockReturnValue(sessionClient) + readSettingsMock.mockResolvedValue({ machineId: 'machine-1' }) + + await expect(bootstrapExistingSession({ + sessionId: 'hapi-session-1', + flavor: 'claude', + workingDirectory: '/tmp/project', + startedBy: 'runner', + })).resolves.toMatchObject({ session: sessionClient }) + + expect(sessionClient.updateMetadata).toHaveBeenCalledOnce() + }) + it('preserves existing native resume metadata when reactivating a session', async () => { const session = createSession() const existingMetadata = session.metadata @@ -364,6 +419,66 @@ describe('bootstrapSession HAPI_SESSION_ID export', () => { expect(result.sessionInfo.id).toBe('hub-session-42') expect(process.env[HAPI_SESSION_ID_ENV]).toBe('hub-session-42') }) + + it('passes reservedSessionId as getOrCreateSession id (adopt-stub, #1911)', async () => { + const session = createSession() + session.id = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' + getOrCreateSessionMock.mockResolvedValue(session) + getOrCreateMachineMock.mockResolvedValue({ id: 'machine-1' }) + sessionSyncClientMock.mockReturnValue({ isPending: () => false }) + readSettingsMock.mockResolvedValue({ machineId: 'machine-1' }) + + const result = await bootstrapSession({ + flavor: 'claude', + workingDirectory: '/tmp/project', + reservedSessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' + }) + + expect(getOrCreateSessionMock).toHaveBeenCalledWith( + expect.objectContaining({ + id: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + adopt: true, + }) + ) + expect(result.sessionInfo.id).toBe('aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee') + }) + + it('does not bind non-UUID reservedSessionId (reap stamp only; hub rejects non-uuid id)', async () => { + const session = createSession() + session.id = 'minted-hub-id' + getOrCreateSessionMock.mockResolvedValue(session) + getOrCreateMachineMock.mockResolvedValue({ id: 'machine-1' }) + sessionSyncClientMock.mockReturnValue({ isPending: () => false }) + readSettingsMock.mockResolvedValue({ machineId: 'machine-1' }) + + await bootstrapSession({ + flavor: 'claude', + workingDirectory: '/tmp/project', + reservedSessionId: 'spawned-test-456' + }) + + expect(getOrCreateSessionMock).toHaveBeenCalledWith( + expect.not.objectContaining({ id: expect.anything() }) + ) + // Call args should omit `id` entirely: + const call = getOrCreateSessionMock.mock.calls[0][0] as { id?: string } + expect(call.id).toBeUndefined() + }) + + it('throws when hub returns a different id than reservedSessionId', async () => { + const session = createSession() + session.id = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + getOrCreateSessionMock.mockResolvedValue(session) + getOrCreateMachineMock.mockResolvedValue({ id: 'machine-1' }) + sessionSyncClientMock.mockReturnValue({ isPending: () => false }) + readSettingsMock.mockResolvedValue({ machineId: 'machine-1' }) + + await expect(bootstrapSession({ + flavor: 'claude', + workingDirectory: '/tmp/project', + reservedSessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' + })).rejects.toThrow(/unexpected session id/) + }) }) describe('buildMachineMetadata runner-only capabilities', () => { diff --git a/cli/src/agent/sessionFactory.ts b/cli/src/agent/sessionFactory.ts index 79a47ba1..82cac20b 100644 --- a/cli/src/agent/sessionFactory.ts +++ b/cli/src/agent/sessionFactory.ts @@ -1,6 +1,7 @@ import os from 'node:os' import { randomUUID } from 'node:crypto' import { resolve } from 'node:path' +import { z } from 'zod' import { ApiClient } from '@/api/api' import type { ApiSessionClient } from '@/api/apiSession' @@ -20,6 +21,9 @@ export { HAPI_SESSION_ID_ENV, exportHapiSessionEnv, exportHapiHubAuthEnv } from export type SessionStartedBy = 'runner' | 'terminal' +/** Matches shared CreateOrLoadSessionRequestSchema `id`. */ +const HubReservedSessionIdSchema = z.string().uuid() + export type SessionBootstrapOptions = { reportStarted?: boolean /** Multi-session workers inject session identity into each child, never process.env. */ @@ -28,6 +32,16 @@ export type SessionBootstrapOptions = { startedBy?: SessionStartedBy workingDirectory?: string tag?: string + /** + * Hub-preallocated / runner-stamped id for a *fresh* create bootstrap. + * Passed as `getOrCreateSession({ id })` so create-time metadata still runs + * while binding the reserved row. Distinct from reopen via + * `bootstrapExistingSession` / `--existing-session-id`. + * + * Must be a UUID (hub create schema). Non-UUID stamps (legacy HTTP spawn + * hints) stay reap-only: argv retains the id, create mints a new hub row. + */ + reservedSessionId?: string agentState?: AgentState | null model?: string modelReasoningEffort?: string @@ -35,6 +49,19 @@ export type SessionBootstrapOptions = { metadataOverrides?: Partial } +/** Hub create/load accepts optional `id` only as UUID — match that gate. */ +export function resolveReservedHubSessionId(reservedSessionId: string | undefined): string | undefined { + if (!reservedSessionId) return undefined + const parsed = HubReservedSessionIdSchema.safeParse(reservedSessionId) + if (!parsed.success) { + logger.debug( + `[START] Ignoring non-UUID reservedSessionId for create bind (reap stamp only): ${reservedSessionId}` + ) + return undefined + } + return parsed.data +} + export type SessionBootstrapResult = { api: ApiClient session: ApiSessionClient @@ -204,6 +231,7 @@ export async function bootstrapSession(options: SessionBootstrapOptions): Promis const startedBy = options.startedBy ?? 'terminal' const sessionTag = options.tag ?? randomUUID() const agentState = options.agentState === undefined ? {} : options.agentState + const reservedHubId = resolveReservedHubSessionId(options.reservedSessionId) const api = await ApiClient.create() @@ -222,6 +250,9 @@ export async function bootstrapSession(options: SessionBootstrapOptions): Promis }) const sessionInfo = await api.getOrCreateSession({ + ...(reservedHubId + ? { id: reservedHubId, adopt: true as const } + : {}), tag: sessionTag, metadata, state: agentState, @@ -230,6 +261,12 @@ export async function bootstrapSession(options: SessionBootstrapOptions): Promis effort: options.effort }) + if (reservedHubId && sessionInfo.id !== reservedHubId) { + throw new Error( + `Hub returned unexpected session id ${sessionInfo.id} (reserved ${reservedHubId})` + ) + } + const session = api.sessionSyncClient(sessionInfo) if (options.exportSessionEnv !== false) exportHapiSessionEnv(sessionInfo.id) @@ -352,6 +389,18 @@ export async function bootstrapExistingSession(options: { }) const sessionInfo = await api.getSession(options.sessionId) + // #1911 M1 belt: match hub merge-preserve scope — only hub-authored archive. + // CLI self-archive (archivedBy=cli) must still reopen; hub clears before spawn + // for intentional revive. CAS closed hub-side (success+preserve + ack EXIT). + if ( + sessionInfo.metadata?.lifecycleState === 'archived' + && sessionInfo.metadata?.archivedBy === 'hub' + ) { + throw new Error( + `HAPI session ${options.sessionId} is hub-archived; refuse --existing-session-id reopen ` + + '(use hub reopen to clear archive metadata first)' + ) + } const baseMetadata = buildSessionMetadata({ flavor: options.flavor, startedBy, diff --git a/cli/src/agy/runAgy.ts b/cli/src/agy/runAgy.ts index b8170fd1..a0b14f03 100644 --- a/cli/src/agy/runAgy.ts +++ b/cli/src/agy/runAgy.ts @@ -22,6 +22,8 @@ export async function runAgy(opts: { effort?: string; resumeSessionId?: string; existingSessionId?: string; + /** Fresh machine-spawn stub (`--hapi-session-id`); adopt via bootstrapSession. */ + reservedSessionId?: string; workingDirectory?: string; } = {}): Promise { const workingDirectory = opts.workingDirectory ?? getInvokedCwd(); @@ -54,7 +56,8 @@ export async function runAgy(opts: { tag: `__hapi_agy_${randomUUID()}`, agentState: initialState, model: initialModel ?? undefined, - effort: opts.effort ?? undefined + effort: opts.effort ?? undefined, + reservedSessionId: opts.reservedSessionId }); const { api, session } = bootstrap; @@ -79,7 +82,7 @@ export async function runAgy(opts: { }); lifecycle.registerProcessHandlers(); - registerKillSessionHandler(session.rpcHandlerManager, lifecycle.cleanupAndExit); + registerKillSessionHandler(session.rpcHandlerManager, lifecycle.cleanupAndExit, session); registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle); let crashed = false; diff --git a/cli/src/api/api.ts b/cli/src/api/api.ts index 5b3acf23..f079741d 100644 --- a/cli/src/api/api.ts +++ b/cli/src/api/api.ts @@ -38,6 +38,8 @@ export class ApiClient { async getOrCreateSession(opts: { id?: string + /** Bind a hub-preallocated stub (requires id). */ + adopt?: boolean tag: string metadata: Metadata state: AgentState | null @@ -56,6 +58,7 @@ export class ApiClient { `${configuration.apiUrl}/cli/sessions`, { id: opts.id, + ...(opts.adopt === true ? { adopt: true } : {}), tag: opts.tag, metadata: opts.metadata, agentState: opts.state, diff --git a/cli/src/api/apiMachine.test.ts b/cli/src/api/apiMachine.test.ts index ccc48662..1939b6e6 100644 --- a/cli/src/api/apiMachine.test.ts +++ b/cli/src/api/apiMachine.test.ts @@ -746,6 +746,35 @@ describe('ApiMachineClient SpawnHappySession handler', () => { client.shutdown() } }) + + it('returns childStarted:false on outside_workspace_roots so hub deletes the stub', async () => { + const machine = makeMachine('machine-spawn-outside') + const client = new ApiMachineClient('cli-token', machine, [workspaceRoot]) + const spawnSession = vi.fn() + + client.setRPCHandlers({ + spawnSession, + stopSession: vi.fn(async () => 'stopped' as const), + requestShutdown: vi.fn() + }) + + try { + const result = await callSpawnHappySession(client, machine.id, { + directory: '/tmp/definitely-outside-roots', + agent: 'claude', + }) + + expect(result).toEqual({ + type: 'error', + errorMessage: "Directory is outside this machine's workspace roots", + code: 'outside_workspace_roots', + childStarted: false, + }) + expect(spawnSession).not.toHaveBeenCalled() + } finally { + client.shutdown() + } + }) }) describe('ApiMachineClient keepAlive lifecycle', () => { diff --git a/cli/src/api/apiMachine.ts b/cli/src/api/apiMachine.ts index b342e4e8..edf26763 100644 --- a/cli/src/api/apiMachine.ts +++ b/cli/src/api/apiMachine.ts @@ -70,7 +70,10 @@ export { normalizeWindowsDriveRoot } from './machinePathPolicy' type MachineRpcHandlers = { spawnSession: (options: SpawnSessionOptions) => Promise - stopSession: (sessionId: string) => Promise<'stopped' | 'already_gone' | 'still_alive'> + stopSession: ( + sessionId: string, + opts?: { processStartMarker?: string } + ) => Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> requestShutdown: () => void } @@ -401,7 +404,7 @@ export class ApiMachineClient { setRPCHandlers({ spawnSession, stopSession, requestShutdown }: MachineRpcHandlers): void { this.rpcHandlerManager.registerHandler(RPC_METHODS.SpawnHappySession, async (params: any) => { - const { directory, sessionId, existingSessionId, resumeSessionId, machineId, approvedNewDirectoryCreation, agent, model, effort, modelReasoningEffort, yolo, permissionMode, serviceTier, collaborationMode, copilotAgentMode, token, sessionType, worktreeName, startingMode, forkSession } = params || {} + const { directory, sessionId, existingSessionId, reservedSessionId, resumeSessionId, machineId, approvedNewDirectoryCreation, agent, model, effort, modelReasoningEffort, yolo, permissionMode, serviceTier, collaborationMode, copilotAgentMode, token, sessionType, worktreeName, startingMode, forkSession } = params || {} if (!directory) { throw new Error('Directory is required') @@ -413,6 +416,8 @@ export class ApiMachineClient { type: 'error', errorMessage: 'Directory is outside this machine\'s workspace roots', code: 'outside_workspace_roots', + // Pre-exec: no OS child — hub must delete the prealloc stub (#1911). + childStarted: false, } } @@ -420,6 +425,7 @@ export class ApiMachineClient { directory, sessionId, existingSessionId, + reservedSessionId, resumeSessionId, machineId, approvedNewDirectoryCreation, @@ -456,12 +462,15 @@ export class ApiMachineClient { }) this.rpcHandlerManager.registerHandler(RPC_METHODS.StopSession, async (params: any) => { - const { sessionId } = params || {} + const { sessionId, processStartMarker } = params || {} if (!sessionId) { throw new Error('Session ID is required') } - const status = await stopSession(sessionId) + const status = await stopSession( + sessionId, + typeof processStartMarker === 'string' ? { processStartMarker } : undefined + ) return { status } }) diff --git a/cli/src/api/apiSession.test.ts b/cli/src/api/apiSession.test.ts index 3792ce80..450d07b3 100644 --- a/cli/src/api/apiSession.test.ts +++ b/cli/src/api/apiSession.test.ts @@ -11,6 +11,7 @@ const socketHarness = vi.hoisted(() => ({ trigger: (event: string, ...args: any[]) => void triggerConnect: () => void triggerConnectError: () => void + emitWithAckImpl: (event: string, ...args: unknown[]) => Promise }> })) @@ -28,7 +29,8 @@ vi.mock('socket.io-client', () => ({ listeners: new Map void>>(), trigger: () => {}, triggerConnect: () => {}, - triggerConnectError: () => {} + triggerConnectError: () => {}, + emitWithAckImpl: async () => ({}) } state.trigger = (event: string, ...args: any[]) => { for (const listener of state.listeners.get(event) ?? []) { @@ -62,8 +64,10 @@ vi.mock('socket.io-client', () => ({ state.emitted.push({ event, args }) return socket }, - emitWithAck: async () => ({}), - timeout: () => ({ emitWithAck: async () => ({}) }), + emitWithAck: async (event: string, ...args: unknown[]) => state.emitWithAckImpl(event, ...args), + timeout: () => ({ + emitWithAck: async (event: string, ...args: unknown[]) => state.emitWithAckImpl(event, ...args) + }), connect: () => { state.connectCalls += 1 if (state.connectImmediately) { @@ -76,7 +80,10 @@ vi.mock('socket.io-client', () => ({ return socket } } - Object.assign(socket, { volatile: socket }) + Object.assign(socket, { + volatile: socket, + io: { opts: { reconnection: true } } + }) socketHarness.sockets.push(state) return socket } @@ -410,6 +417,189 @@ describe('ApiSessionClient lazy materialization', () => { expect(socket.connectCalls).toBeGreaterThan(0) client.close() }) + + it('emits hub-archived from update-session metadata (#1910)', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockResolvedValue({ data: { messages: [] } }) + const session = createSession({ + namespace: 'default', + metadata: { path: '/tmp', host: 'h', flavor: 'claude' }, + metadataVersion: 1 + }) + const client = new ApiSessionClient('token', session) + const socket = socketHarness.sockets[0] + if (!socket) throw new Error('expected socket') + + let archived = false + client.on('hub-archived', () => { archived = true }) + + socket.trigger('update', { + body: { + t: 'update-session', + sid: session.id, + metadata: { + version: 2, + value: { + path: '/tmp', + host: 'h', + flavor: 'claude', + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'Archived from hub (CLI unreachable)' + } + }, + agentState: null + } + }) + + expect(archived).toBe(true) + expect(client.getMetadata()?.lifecycleState).toBe('archived') + client.close() + }) + + it('stops metadata CAS when hub returns archived on version-mismatch (#1911 M1)', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockResolvedValue({ data: { messages: [] } }) + const session = createSession({ + namespace: 'default', + metadata: { path: '/tmp', host: 'h', flavor: 'claude', lifecycleState: 'running' }, + metadataVersion: 1 + }) + const client = new ApiSessionClient('token', session) + const socket = socketHarness.sockets[0] + if (!socket) throw new Error('expected socket') + + let ackCalls = 0 + let archived = false + client.on('hub-archived', () => { archived = true }) + socket.emitWithAckImpl = async (event) => { + if (event !== 'update-metadata') return {} + ackCalls += 1 + return { + result: 'version-mismatch', + version: 2, + metadata: { + path: '/tmp', + host: 'h', + flavor: 'claude', + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'Archived from hub' + } + } + } + + client.updateMetadata((meta) => ({ ...meta, lifecycleState: 'running', hostPid: 42 })) + + await vi.waitFor(() => { + expect(client.getMetadata()?.lifecycleState).toBe('archived') + expect(archived).toBe(true) + }) + await new Promise((r) => setTimeout(r, 50)) + expect(ackCalls).toBe(1) + client.close() + }) + + it('exits via hub-archived on success+merge-preserve ack (#1911 criterion 6)', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockResolvedValue({ data: { messages: [] } }) + const session = createSession({ + namespace: 'default', + metadata: { path: '/tmp', host: 'h', flavor: 'claude', lifecycleState: 'running' }, + metadataVersion: 1 + }) + const client = new ApiSessionClient('token', session) + const socket = socketHarness.sockets[0] + if (!socket) throw new Error('expected socket') + + let ackCalls = 0 + let archived = false + client.on('hub-archived', () => { archived = true }) + socket.emitWithAckImpl = async (event) => { + if (event !== 'update-metadata') return {} + ackCalls += 1 + // Hub merge-preserved archive fields and returned success. + return { + result: 'success', + version: 2, + metadata: { + path: '/tmp', + host: 'h', + flavor: 'claude', + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'Archived from hub', + hostPid: 42 + } + } + } + + client.updateMetadata((meta) => ({ ...meta, lifecycleState: 'running', hostPid: 42 })) + + await vi.waitFor(() => { + expect(archived).toBe(true) + expect(client.getMetadata()?.lifecycleState).toBe('archived') + }) + await new Promise((r) => setTimeout(r, 50)) + expect(ackCalls).toBe(1) + client.close() + }) + + it('reconciles hub-archived metadata on reconnect (#1910)', async () => { + socketHarness.sockets.length = 0 + axiosHarness.get.mockResolvedValue({ + data: { + session: { + metadataVersion: 1, + metadata: { path: '/tmp', host: 'h', flavor: 'claude' } + }, + messages: [] + } + }) + + const client = new ApiSessionClient('token', createSession({ + namespace: 'default', + metadata: { path: '/tmp', host: 'h', flavor: 'claude' }, + metadataVersion: 1 + })) + const socket = socketHarness.sockets[0] + if (!socket) throw new Error('expected socket') + + let archived = false + client.on('hub-archived', () => { archived = true }) + + // Establish first connection so hasConnectedOnce is true. + socket.triggerConnect() + await vi.waitFor(() => expect(axiosHarness.get).toHaveBeenCalled()) + + axiosHarness.get.mockImplementation(async (url: string) => { + if (String(url).includes('/messages')) { + return { data: { messages: [] } } + } + return { + data: { + session: { + metadataVersion: 5, + metadata: { + path: '/tmp', + host: 'h', + flavor: 'claude', + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'Archived from hub (CLI unreachable)' + } + } + } + } + }) + socket.connected = false + socket.trigger('disconnect', 'transport close') + socket.triggerConnect() + + await vi.waitFor(() => expect(archived).toBe(true)) + expect(client.getMetadata()?.archivedBy).toBe('hub') + client.close() + }) }) describe('ApiSessionClient agy transcript messages', () => { diff --git a/cli/src/api/apiSession.ts b/cli/src/api/apiSession.ts index aed3ba04..619899d2 100644 --- a/cli/src/api/apiSession.ts +++ b/cli/src/api/apiSession.ts @@ -234,6 +234,15 @@ function hasSameJsonValue(left: unknown, right: unknown): boolean { export class ApiSessionClient extends EventEmitter { private reconnectHandler: (() => void) | null = null onReconnect(handler: (() => void) | null): void { this.reconnectHandler = handler } + /** When false, socket.io must not keep the CLI immortal after hub archive (#1910). */ + private allowReconnect = true + /** + * Latch for hub-archived EXIT (#1911 criterion 6). Bootstrap may apply + * hub-archived via updateMetadata CAS before flavor runners call + * registerKillSessionHandler; EventEmitter does not replay past emits, so + * the handler must read this synchronously at registration. + */ + hubArchived = false private readonly token: string readonly sessionId: string private metadata: Metadata | null @@ -332,10 +341,19 @@ export class ApiSessionClient extends EventEmitter { logger.debug('Socket connected successfully') this.awaitingMaterializedConnection = false this.rpcHandlerManager.onSocketConnect(this.socket) - if (this.hasConnectedOnce) { + const isReconnect = this.hasConnectedOnce + if (isReconnect) { this.needsBackfill = true } - void this.backfillIfNeeded() + // Hub may have archived while we were offline (KillSession miss + + // no live update-session). On reconnect, reconcile metadata before + // message backfill so hub-archived can stop reconnect immortality (#1910). + const afterMeta = isReconnect + ? this.reconcileSessionMetadata() + : Promise.resolve() + void afterMeta.finally(() => { + void this.backfillIfNeeded() + }) this.hasConnectedOnce = true this.reconnectHandler?.() this.socket.emit('session-alive', { @@ -353,6 +371,13 @@ export class ApiSessionClient extends EventEmitter { logger.debug('[API] Socket disconnected:', reason) this.rpcHandlerManager.onSocketDisconnect() this.terminalManager.closeAll() + if (!this.allowReconnect) { + try { + this.socket.io.opts.reconnection = false + this.socket.disconnect() + } catch { /* already tearing down */ } + return + } if (this.hasConnectedOnce) { this.needsBackfill = true } @@ -477,13 +502,7 @@ export class ApiSessionClient extends EventEmitter { if (data.body.t === 'update-session') { if (data.body.metadata && data.body.metadata.version > this.metadataVersion) { - const parsed = MetadataSchema.safeParse(data.body.metadata.value) - if (parsed.success) { - this.metadata = parsed.data - } else { - logger.debug('[API] Ignoring invalid metadata update', { version: data.body.metadata.version }) - } - this.metadataVersion = data.body.metadata.version + this.applyRemoteMetadata(data.body.metadata.version, data.body.metadata.value) } if (data.body.agentState && data.body.agentState.version > this.agentStateVersion) { const next = data.body.agentState.value @@ -819,6 +838,63 @@ export class ApiSessionClient extends EventEmitter { } } + /** + * Apply a remote metadata snapshot (Socket.IO update-session or reconnect + * REST reconcile). Advances metadataVersion and emits hub-archived when + * the hub flipped lifecycle while this CLI was unreachable. + */ + private applyRemoteMetadata(version: number, value: unknown): void { + if (version <= this.metadataVersion) return + const parsed = MetadataSchema.safeParse(value) + if (!parsed.success) { + logger.debug('[API] Ignoring invalid metadata update', { version }) + this.metadataVersion = version + return + } + const wasHubArchived = this.metadata?.lifecycleState === 'archived' + && this.metadata?.archivedBy === 'hub' + this.metadata = parsed.data + this.metadataVersion = version + // #1910: hub may archive via metadata when KillSession cannot reach + // this CLI. Stop reconnect immortality and let runners exit instead + // of sitting as PPID=1 orphans. + if (!wasHubArchived + && parsed.data.lifecycleState === 'archived' + && parsed.data.archivedBy === 'hub') { + this.noteHubArchived() + } + } + + private noteHubArchived(): void { + this.hubArchived = true + this.allowReconnect = false + try { + this.socket.io.opts.reconnection = false + } catch { /* socket may be mid-teardown */ } + this.emit('hub-archived') + } + + /** Fetch current hub metadata after reconnect; apply hub-archived if set. */ + private async reconcileSessionMetadata(): Promise { + try { + const response = await axios.get( + `${configuration.apiUrl}/cli/sessions/${encodeURIComponent(this.sessionId)}`, + { + headers: buildHubRequestHeaders({ + Authorization: `Bearer ${this.token}`, + 'Content-Type': 'application/json' + }), + timeout: 15_000 + } + ) + const session = response.data?.session + if (!session || typeof session.metadataVersion !== 'number') return + this.applyRemoteMetadata(session.metadataVersion, session.metadata) + } catch (error) { + logger.debug('[API] Session metadata reconcile failed', error) + } + } + private async backfillMessages(): Promise { if (this.backfillInFlight) { await this.backfillInFlight @@ -1308,6 +1384,13 @@ export class ApiSessionClient extends EventEmitter { } this.metadataLock.inLock(async () => { await backoff(async () => { + // #1911 M1 criterion 6: hub-archived → EXIT (same as applyRemoteMetadata). + if (this.metadata?.lifecycleState === 'archived' && this.metadata.archivedBy === 'hub') { + this.noteHubArchived() + logger.debug('[API] Skipping metadata update; session hub-archived') + return + } + const current = this.metadata ?? ({} as Metadata) const updated = handler(current) @@ -1317,26 +1400,55 @@ export class ApiSessionClient extends EventEmitter { metadata: updated }) as unknown - applyVersionedAck(answer, { - valueKey: 'metadata', - parseValue: (value) => { - const parsed = MetadataSchema.safeParse(value) - return parsed.success ? parsed.data : null - }, - applyValue: (value) => { - this.metadata = value - }, - applyVersion: (version) => { - this.metadataVersion = version - }, - logInvalidValue: (context, version) => { - const suffix = context === 'success' ? 'ack' : 'version-mismatch ack' - logger.debug(`[API] Ignoring invalid metadata value from ${suffix}`, { version }) - }, - invalidResponseMessage: 'Invalid update-metadata response', - errorMessage: 'Metadata update failed', - versionMismatchMessage: 'Metadata version mismatch' - }) + try { + applyVersionedAck(answer, { + valueKey: 'metadata', + parseValue: (value) => { + const parsed = MetadataSchema.safeParse(value) + return parsed.success ? parsed.data : null + }, + applyValue: (value) => { + // Route success+preserve (and mismatch) through the same + // hub-archived detector as applyRemoteMetadata so the CLI + // exits rather than booting against an archived row. + const wasHubArchived = this.metadata?.lifecycleState === 'archived' + && this.metadata?.archivedBy === 'hub' + this.metadata = value + if ( + !wasHubArchived + && value?.lifecycleState === 'archived' + && value?.archivedBy === 'hub' + ) { + this.noteHubArchived() + } + }, + applyVersion: (version) => { + this.metadataVersion = version + }, + logInvalidValue: (context, version) => { + const suffix = context === 'success' ? 'ack' : 'version-mismatch ack' + logger.debug(`[API] Ignoring invalid metadata value from ${suffix}`, { version }) + }, + invalidResponseMessage: 'Invalid update-metadata response', + errorMessage: 'Metadata update failed', + versionMismatchMessage: 'Metadata version mismatch' + }) + } catch (error) { + // True version races still throw; if hub archived mid-flight, + // applied metadata is archived — exit, do not spin. + if (this.metadata?.lifecycleState === 'archived' && this.metadata.archivedBy === 'hub') { + this.noteHubArchived() + return + } + throw error + } + + // Success+preserve terminates backoff without throw; ensure EXIT + // if ack applied hub-archived (detector above already fired). + if (this.metadata?.lifecycleState === 'archived' && this.metadata.archivedBy === 'hub') { + this.noteHubArchived() + return + } }) }) } diff --git a/cli/src/claude/registerKillSessionHandler.test.ts b/cli/src/claude/registerKillSessionHandler.test.ts index b2931729..3edba234 100644 --- a/cli/src/claude/registerKillSessionHandler.test.ts +++ b/cli/src/claude/registerKillSessionHandler.test.ts @@ -33,8 +33,11 @@ describe('registerKillSessionHandler (tiann/hapi#914)', () => { const handler = registry.handlers.get(RPC_METHODS.KillSession) expect(handler).toBeDefined() - const result = await handler?.() - expect(result).toEqual({ success: true, message: 'Killing hapi CLI process' }) + const result = await handler?.() as { success: boolean; message: string; pid: number; processStartMarker?: string } + expect(result.success).toBe(true) + expect(result.message).toBe('Killing hapi CLI process') + expect(result.pid).toBe(process.pid) + expect(typeof result.processStartMarker === 'string' || result.processStartMarker === undefined).toBe(true) // setArchiveReason MUST be called BEFORE cleanupAndExit so the archive // metadata write reads the correct reason. @@ -62,4 +65,66 @@ describe('registerKillSessionHandler (tiann/hapi#914)', () => { expect(cleanupAndExit).toHaveBeenCalled() }) + + it('exits on hub-archived metadata when a session listener is provided (#1910)', async () => { + const registry = makeRegistry() + const lifecycle = { + setArchiveReason: vi.fn(), + cleanupAndExit: vi.fn(async () => {}) + } + const listeners = new Map void>() + const session = { + on(event: string, listener: () => void) { + listeners.set(event, listener) + } + } + + registerKillSessionHandler( + registry as unknown as Parameters[0], + lifecycle, + session + ) + + expect(listeners.has('hub-archived')).toBe(true) + listeners.get('hub-archived')?.() + expect(lifecycle.setArchiveReason).toHaveBeenCalledWith('User terminated') + expect(lifecycle.cleanupAndExit).toHaveBeenCalled() + }) + + it('exits when registration happens after hub-archived write (production order, #1911 AC6)', async () => { + // Production: bootstrap updateMetadata / ack may noteHubArchived before + // flavor runners call registerKillSessionHandler. EventEmitter does not + // replay — without the latch, cleanupAndExit stays 0×. + const registry = makeRegistry() + const lifecycle = { + setArchiveReason: vi.fn(), + cleanupAndExit: vi.fn(async () => {}) + } + const listeners = new Map void>() + const session: { + hubArchived: boolean + on(event: string, listener: () => void): void + } = { + hubArchived: false, + on(event: string, listener: () => void) { + listeners.set(event, listener) + } + } + + // Write first (noteHubArchived), then register — production order. + session.hubArchived = true + // Emit with no listeners yet (would be missed without the latch). + listeners.get('hub-archived')?.() + + registerKillSessionHandler( + registry as unknown as Parameters[0], + lifecycle, + session + ) + + expect(lifecycle.setArchiveReason).toHaveBeenCalledWith('User terminated') + expect(lifecycle.cleanupAndExit).toHaveBeenCalledTimes(1) + // Still subscribed for any later emit. + expect(listeners.has('hub-archived')).toBe(true) + }) }) diff --git a/cli/src/claude/registerKillSessionHandler.ts b/cli/src/claude/registerKillSessionHandler.ts index b42b9b49..2b58291c 100644 --- a/cli/src/claude/registerKillSessionHandler.ts +++ b/cli/src/claude/registerKillSessionHandler.ts @@ -1,6 +1,7 @@ import { RpcHandlerManager } from "@/api/rpc/RpcHandlerManager"; import { logger } from "@/lib"; import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; +import { getProcessStartMarker } from '@/utils/process'; interface KillSessionRequest { // No parameters needed @@ -9,6 +10,10 @@ interface KillSessionRequest { interface KillSessionResponse { success: boolean; message: string; + /** OS pid of this CLI — hub uses it to confirm exit via StopSession when maps miss. */ + pid: number; + /** Generation marker for `pid`; required before the runner will tree-kill it. */ + processStartMarker?: string; } /** @@ -26,12 +31,22 @@ export interface KillSessionLifecycle { export function registerKillSessionHandler( rpcHandlerManager: RpcHandlerManager, - lifecycleOrCleanup: KillSessionLifecycle | (() => Promise) + lifecycleOrCleanup: KillSessionLifecycle | (() => Promise), + session?: { + hubArchived?: boolean + on(event: 'hub-archived', listener: () => void): unknown + } ) { const lifecycle: KillSessionLifecycle = typeof lifecycleOrCleanup === 'function' ? { cleanupAndExit: lifecycleOrCleanup } : lifecycleOrCleanup; + const exitFromHubArchive = () => { + logger.debug('Hub-archived metadata received; exiting CLI'); + lifecycle.setArchiveReason?.('User terminated'); + void lifecycle.cleanupAndExit(); + }; + rpcHandlerManager.registerHandler(RPC_METHODS.KillSession, async () => { logger.debug('Kill session request received'); @@ -45,11 +60,26 @@ export function registerKillSessionHandler( // This will start the cleanup process void lifecycle.cleanupAndExit(); - // We should still be able to respond to the client, though they - // should optimistically assume the session is dead. + // Include pid + start marker so archive can ask the runner to verify + // this exact process generation exited (#1910) — not a reused PID. + const processStartMarker = getProcessStartMarker(process.pid) ?? undefined; return { success: true, - message: 'Killing hapi CLI process' + message: 'Killing hapi CLI process', + pid: process.pid, + ...(processStartMarker ? { processStartMarker } : {}), }; }); + + // #1910: when archive lands as hub metadata (KillSession unreachable), + // still exit instead of reconnecting forever. + // #1911 criterion 6: EventEmitter does not replay past emits — if + // noteHubArchived already latched before this registration, exit now. + // Still subscribe so a later emit (or a race with the latch write) is covered. + if (session?.hubArchived) { + exitFromHubArchive(); + } + if (session && typeof session.on === 'function') { + session.on('hub-archived', exitFromHubArchive); + } } diff --git a/cli/src/claude/runClaude.ts b/cli/src/claude/runClaude.ts index fc446e9d..105bb857 100644 --- a/cli/src/claude/runClaude.ts +++ b/cli/src/claude/runClaude.ts @@ -39,6 +39,11 @@ export interface StartOptions { claudeArgs?: string[] startedBy?: 'runner' | 'terminal' existingSessionId?: string + /** + * Fresh-spawn reserved hub id from `--hapi-session-id` (create/getOrCreate). + * Distinct from `existingSessionId` / `--existing-session-id` (reopen). + */ + reservedSessionId?: string workingDirectory?: string resumeSessionId?: string } @@ -75,7 +80,8 @@ export async function runClaude(options: StartOptions = {}): Promise { workingDirectory, agentState: initialState, model: initialModel ?? undefined, - effort: initialEffort ?? undefined + effort: initialEffort ?? undefined, + reservedSessionId: options.reservedSessionId }); const { api, session, sessionInfo } = bootstrap; logger.debug(`Session created: ${sessionInfo.id}`); @@ -236,7 +242,7 @@ export async function runClaude(options: StartOptions = {}): Promise { }); lifecycle.registerProcessHandlers(); - registerKillSessionHandler(session.rpcHandlerManager, lifecycle); + registerKillSessionHandler(session.rpcHandlerManager, lifecycle, session); registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle); const conversationHistory = toConversationHistoryCapabilities(CLAUDE_CONVERSATION_HISTORY) diff --git a/cli/src/codex/shared/frontend.test.ts b/cli/src/codex/shared/frontend.test.ts index 46291193..5b8e88bd 100644 --- a/cli/src/codex/shared/frontend.test.ts +++ b/cli/src/codex/shared/frontend.test.ts @@ -58,6 +58,28 @@ describe('shared frontend execution ownership', () => { await runSharedCodex({ startedBy: 'runner', workingDirectory: '/work' }); expect(state.run).toHaveBeenCalledOnce(); expect(state.spawn).not.toHaveBeenCalled(); }); + it('fresh reservedSessionId starts create path (not reopen without thread binding)', async () => { + // #1911 Critical: prealloc stub stamped as existingSessionId threw + // "no Codex thread binding". reservedSessionId must fall through to create. + state.run.mockResolvedValueOnce(undefined); + await runSharedCodex({ + startedBy: 'runner', + workingDirectory: '/work', + reservedSessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + }); + expect(state.run).toHaveBeenCalledOnce(); + expect(state.run.mock.calls[0][0]).toMatchObject({ + reservedSessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + }); + }); + it('existingSessionId without thread binding still throws (reopen path)', async () => { + await expect(runSharedCodex({ + startedBy: 'runner', + workingDirectory: '/work', + existingSessionId: 'sid', + })).rejects.toThrow('no Codex thread binding'); + expect(state.run).not.toHaveBeenCalled(); + }); it('stops the engine on TUI spawn error and leaves no execution on startup failure', async () => { state.run.mockRejectedValueOnce(new Error('startup failed')); await expect(runSharedCodex({ workingDirectory: '/work' })).rejects.toThrow('startup failed'); diff --git a/cli/src/codex/shared/frontend.ts b/cli/src/codex/shared/frontend.ts index c9178feb..22574059 100644 --- a/cli/src/codex/shared/frontend.ts +++ b/cli/src/codex/shared/frontend.ts @@ -50,7 +50,8 @@ export async function attachSharedSession(runtime: CodexRuntimeRecord, sessionId export async function runSharedCodex(raw: SharedLaunchOptions): Promise { const options = SharedLaunchSchema.parse({ ...raw, workingDirectory: raw.workingDirectory ?? getInvokedCwd() }); - if (options.existingSessionId) { + // reservedSessionId is fresh adopt-stub — never treat as reopen (#1911 Codex Major). + if (options.existingSessionId && !options.reservedSessionId) { const api = await ApiClient.create(); const session = await api.getSession(options.existingSessionId); const runtime = await findRuntime(session.id); diff --git a/cli/src/codex/shared/launch.test.ts b/cli/src/codex/shared/launch.test.ts index b9d2e3ea..82bfd560 100644 --- a/cli/src/codex/shared/launch.test.ts +++ b/cli/src/codex/shared/launch.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { sharedLaunchConfig } from './launch'; +import { sharedLaunchConfig, takeReservedSessionId } from './launch'; import { parseCodexCliOverrides } from '../utils/codexCliOverrides'; import { resolveCodexPermissionModeConfig } from '../utils/permissionModeConfig'; @@ -52,3 +52,12 @@ describe('shared launch configuration', () => { expect(result.threadParams).toMatchObject({ modelProvider: 'ollama', approvalsReviewer: 'auto_review', sandbox: 'workspace-write' }); }); }); + +describe('takeReservedSessionId', () => { + it('returns the reservation once and clears it for subsequent prepare calls', () => { + const options = { reservedSessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' }; + expect(takeReservedSessionId(options)).toBe('aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'); + expect(options.reservedSessionId).toBeUndefined(); + expect(takeReservedSessionId(options)).toBeUndefined(); + }); +}); diff --git a/cli/src/codex/shared/launch.ts b/cli/src/codex/shared/launch.ts index 4488a211..71b8e934 100644 --- a/cli/src/codex/shared/launch.ts +++ b/cli/src/codex/shared/launch.ts @@ -11,13 +11,26 @@ export const SharedLaunchSchema = z.object({ startedBy: z.enum(['runner', 'terminal']).optional(), codexArgs: z.array(z.string()).optional(), permissionMode: z.enum(['default', 'read-only', 'safe-yolo', 'yolo']).optional(), - resumeSessionId: z.string().optional(), resumeLast: z.boolean().optional(), resumeAll: z.boolean().optional(), existingSessionId: z.string().optional(), + resumeSessionId: z.string().optional(), resumeLast: z.boolean().optional(), resumeAll: z.boolean().optional(), + existingSessionId: z.string().optional(), + /** Hub-preallocated stub — create/adopt, not reopen. */ + reservedSessionId: z.string().optional(), model: z.string().optional(), modelReasoningEffort: z.string().optional(), serviceTier: z.string().optional(), collaborationMode: z.enum(['default', 'plan']).optional(), workingDirectory: z.string().optional() }); export type SharedLaunchOptions = z.infer; +/** + * Take the machine-spawn reservation for one create-path prepare(). + * Clears it so a second root/fork cannot re-adopt (#1911 Opus Major). + */ +export function takeReservedSessionId(options: SharedLaunchOptions): string | undefined { + const id = options.reservedSessionId; + options.reservedSessionId = undefined; + return id; +} + /** Resolve once: a desktop server and a different PATH TUI are never mixed. */ export function resolveSharedCodex(): CodexCommand { const command = resolveCodexCommand(); diff --git a/cli/src/codex/shared/registry.test.ts b/cli/src/codex/shared/registry.test.ts index dec3063e..10a98592 100644 --- a/cli/src/codex/shared/registry.test.ts +++ b/cli/src/codex/shared/registry.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os'; const state = vi.hoisted(() => ({ home: '', auth: 'token', processes: new Map() })); vi.mock('@/configuration', () => ({ configuration: { get happyHomeDir() { return state.home; }, apiUrl: 'hub', get cliApiToken() { return state.auth; } } })); vi.mock('@/utils/process', () => ({ isProcessAlive: (pid: number) => state.processes.has(pid), getProcessStartMarker: (pid: number) => state.processes.get(pid) })); -import { findRuntime, runtimeAlive, runtimeAuthHash, runtimeMayBeAlive, saveRuntime, withThreadOwnership, type CodexRuntimeRecord } from './registry'; +import { findRuntime, readRuntimes, runtimeAlive, runtimeAuthHash, runtimeMayBeAlive, saveRuntime, withThreadOwnership, type CodexRuntimeRecord } from './registry'; const directories: string[] = []; afterEach(async () => { state.processes.clear(); state.auth = 'token'; await Promise.all(directories.splice(0).map(path => rm(path, { recursive: true, force: true }))); }); @@ -40,4 +40,13 @@ describe('shared runtime ownership', () => { await writeFile(join(directory, 'broken.json'), '{'); await expect(withThreadOwnership(owner.codexHome, 'thread', 'new', async () => {})).rejects.toThrow('Cannot verify'); }); + it('readRuntimes({ strict: true }) fails closed on corrupt hub registry files', async () => { + // Soft [] would let stopSession argv-sweep tree-kill shared wrappers (#1911). + const owner = await fixture(); + const directory = join(state.home, 'codex-runtimes'); + await mkdir(directory, { recursive: true }); + await writeFile(join(directory, 'broken.json'), '{'); + expect(await readRuntimes()).toEqual([]); + await expect(readRuntimes({ strict: true })).rejects.toThrow('Cannot verify'); + }); }); diff --git a/cli/src/codex/shared/registry.ts b/cli/src/codex/shared/registry.ts index 0f627b16..e8ec3461 100644 --- a/cli/src/codex/shared/registry.ts +++ b/cli/src/codex/shared/registry.ts @@ -43,8 +43,8 @@ export function runtimeMayBeAlive(owner: CodexRuntimeRecord): boolean { || Boolean(owner.serverPid && generationMayBeAlive(owner.serverPid, owner.serverMarker)); } -export async function readRuntimes(): Promise { - return readRecords(runtimeDirectory()); +export async function readRuntimes(options?: { strict?: boolean }): Promise { + return readRecords(runtimeDirectory(), options?.strict === true); } async function readRecords(directory: string, strict = false): Promise { const names = await readdir(directory).catch((error: NodeJS.ErrnoException) => { diff --git a/cli/src/codex/shared/root.test.ts b/cli/src/codex/shared/root.test.ts index f4cc292c..ae027642 100644 --- a/cli/src/codex/shared/root.test.ts +++ b/cli/src/codex/shared/root.test.ts @@ -53,7 +53,7 @@ afterEach(async () => { finally { vi.useRealTimers(); } }); -async function fixture() { +async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end'] }) { const directory = await mkdtemp('/tmp/hapi-shared-root-'); let state: AgentState = { steeringActive: true }; let metadata: Metadata = { path: directory, host: 'test', flavor: 'codex' }; @@ -61,21 +61,27 @@ async function fixture() { const updateState = vi.fn((fn: (value: AgentState) => AgentState) => { state = fn(state); }); const rpc = new Map Promise>(); const send = vi.fn(); + const hubArchivedListeners: Array<() => void> = []; const session = { sessionId: 'sid', getMetadata: () => metadata, + hubArchived: opts?.hubArchived ?? false, updateMetadata: (fn: (value: Metadata) => Metadata) => { metadata = fn(metadata); }, updateAgentState: updateState, keepAlive() {}, onUserMessage() {}, onCancelQueuedMessage() {}, onRetryQueuedMessage() {}, onReconnect: (fn: (() => void) | null) => { reconnect = fn; }, + on(event: string, listener: () => void) { + if (event === 'hub-archived') hubArchivedListeners.push(listener); + }, rpcHandlerManager: { registerHandler: (name: string, handler: (raw: unknown) => Promise) => rpc.set(name, handler) }, sendSessionEvent() {}, sendAgentMessage: send, emitSessionReady() {}, sendUserMessage() {}, emitMessagesConsumed() {}, emitSteerIndeterminate() {}, syncNativeQueuedMessage() {}, sendSessionDeath() {}, async flush() {}, close() {} } as unknown as ApiSessionClient; + const end = opts?.end ?? (async () => { throw new Error('Unexpected root archive'); }); const root = new SharedCodexRoot({ session, workingDirectory: directory } as SessionBootstrapResult, { directory, generation: 'test', endpoint: 'mock', settingsFor: () => undefined, create: async () => { throw new Error('Unexpected root creation'); }, - end: async () => { throw new Error('Unexpected root archive'); } + end } satisfies RootHost); cleanups.push(async () => { await root.close(false); await rm(directory, { recursive: true, force: true }); }); await root.prepare(); @@ -87,7 +93,13 @@ async function fixture() { notify(method: string, params: unknown): void; abandoned(): void; }; - return { root, native, rpc, send, metadata: () => metadata, state: () => state, updateState, reconnect: () => reconnect?.() }; + return { + root, native, rpc, send, metadata: () => metadata, state: () => state, updateState, + reconnect: () => reconnect?.(), + emitHubArchived: () => { for (const listener of hubArchivedListeners) listener(); }, + hubArchivedListenerCount: () => hubArchivedListeners.length, + end, + }; } async function completePlan(f: Awaited>, status = 'completed') { @@ -290,4 +302,23 @@ describe('shared steering availability', () => { f.reconnect(); await vi.waitFor(() => expect(f.state().steeringActive).toBe(false)); }); + + it('ends the shared root on hub-archived metadata (#1911 C2 / AC6)', async () => { + const end = vi.fn(async () => {}); + const f = await fixture({ end }); + await f.root.activate(); + expect(f.hubArchivedListenerCount()).toBe(1); + f.emitHubArchived(); + await vi.waitFor(() => expect(end).toHaveBeenCalledTimes(1)); + expect(end.mock.calls[0]?.[0]).toBe(f.root); + }); + + it('ends when hubArchived was latched before activate (production order, #1911 AC6)', async () => { + // Bootstrap may refuse CAS / noteHubArchived before Codex bind+activate + // registers controls — same late-listener miss as other flavors. + const end = vi.fn(async () => {}); + const f = await fixture({ hubArchived: true, end }); + await f.root.activate(); + await vi.waitFor(() => expect(end).toHaveBeenCalledTimes(1)); + }); }); diff --git a/cli/src/codex/shared/root.ts b/cli/src/codex/shared/root.ts index 58bc48ac..187c0153 100644 --- a/cli/src/codex/shared/root.ts +++ b/cli/src/codex/shared/root.ts @@ -464,6 +464,18 @@ export class SharedCodexRoot { if (turnId) await this.client.request('turn/interrupt', { threadId: this.threadId, turnId }); }); rpc.registerHandler(RPC_METHODS.KillSession, async () => { await this.host.end(this); return { success: true }; }); + // #1911 C2 / AC6: Codex owns KillSession here and never calls + // registerKillSessionHandler — still must EXIT on hub-archived metadata + // (KillSession unreachable / map-miss). Latch covers bootstrap write + // before bind/activate registers controls; B2 refuses tree-kill of the + // shared wrapper so this subscribe is load-bearing. + const exitFromHubArchive = () => { + void this.host.end(this).catch(error => logger.debug('[CODEX] hub-archived end failed:', error)); + }; + if (this.session.hubArchived) { + exitFromHubArchive(); + } + this.session.on('hub-archived', exitFromHubArchive); rpc.registerHandler(RPC_METHODS.SetSessionConfig, raw => this.applySettings(raw)); rpc.registerHandler(RPC_METHODS.ImplementCodexPlan, raw => { const { planId } = ImplementCodexPlanRequestSchema.parse(raw); diff --git a/cli/src/codex/shared/runtime.ts b/cli/src/codex/shared/runtime.ts index 3a054ce2..4c178333 100644 --- a/cli/src/codex/shared/runtime.ts +++ b/cli/src/codex/shared/runtime.ts @@ -12,7 +12,7 @@ import { logger } from '@/ui/logger'; import { CodexAppServerClient, isIndeterminateError } from '../codexAppServerClient'; import { codexHome, saveRuntime, runtimeDirectory, runtimeAuthHash, findColdBinding, withThreadOwnership, type CodexRuntimeRecord } from './registry'; import { startCodexGateway, record, string, type Envelope } from './gateway'; -import { resolveSharedCodex, sharedLaunchConfig, initializeSharedClient, checkSharedCapabilities, type SharedLaunchOptions } from './launch'; +import { resolveSharedCodex, sharedLaunchConfig, initializeSharedClient, checkSharedCapabilities, takeReservedSessionId, type SharedLaunchOptions } from './launch'; import { SharedCodexRoot } from './root'; export type RuntimeReady = { sessionId: string; runtime: CodexRuntimeRecord }; @@ -172,9 +172,16 @@ export async function runSharedRuntime(options: SharedLaunchOptions, onReady?: ( const shared = { flavor: 'codex', startedBy: options.startedBy ?? 'terminal', workingDirectory: cwd, exportSessionEnv: false, reportStarted: false, metadataOverrides: { capabilities: { terminal: true, concurrentClients: true }, ...(parent ? { forkedFrom: parent.session.sessionId } : {}) } } as const; + // reservedSessionId names one preallocated hub row — single-use. A second + // create()/fork must mint a fresh row, not re-adopt (#1911 Opus Major). + const reservedSessionId = takeReservedSessionId(options); const bootstrap = existingSessionId ? await bootstrapExistingSession({ ...shared, sessionId: existingSessionId }) - : await bootstrapSession({ ...shared, agentState: { controlledByUser: false } }); + : await bootstrapSession({ + ...shared, + reservedSessionId, + agentState: { controlledByUser: false }, + }); const root = new SharedCodexRoot(bootstrap, { directory: join(runtimeDirectory(), 'queues'), generation: id, endpoint: upstream, token: upstreamToken, settingsFor: threadId => nativeSettings.get(threadId), create, end }); prepared.add(root); diff --git a/cli/src/commands/agentCommandOptions.test.ts b/cli/src/commands/agentCommandOptions.test.ts index 187bc0fd..7e543567 100644 --- a/cli/src/commands/agentCommandOptions.test.ts +++ b/cli/src/commands/agentCommandOptions.test.ts @@ -13,12 +13,13 @@ describe('parseRemoteAgentCommandOptions', () => { .toBe('yolo') }) - it('parses --hapi-session-id into existingSessionId (pty reopen id reuse)', () => { - // The runner emits --hapi-session-id when reopening a pty session so the - // child reuses the existing hub row. agy (this shared parser) must consume - // it — else the flag is silently dropped and reopen mints a new id + 404. - expect(parseRemoteAgentCommandOptions(['--hapi-session-id', 'hub-id-1'], AGY_PERMISSION_MODES).existingSessionId) + it('parses --hapi-session-id into reservedSessionId (fresh prealloc / adopt)', () => { + // #1911 M3: must NOT alias to existingSessionId — that collapses adopt→reopen. + // Intentional reopen uses --existing-session-id (buildCliArgs already splits). + expect(parseRemoteAgentCommandOptions(['--hapi-session-id', 'hub-id-1'], AGY_PERMISSION_MODES).reservedSessionId) .toBe('hub-id-1') + expect(parseRemoteAgentCommandOptions(['--hapi-session-id', 'hub-id-1'], AGY_PERMISSION_MODES).existingSessionId) + .toBeUndefined() }) it('parses common remote agent flags', () => { diff --git a/cli/src/commands/agentCommandOptions.ts b/cli/src/commands/agentCommandOptions.ts index d5b3fdf1..13ee130b 100644 --- a/cli/src/commands/agentCommandOptions.ts +++ b/cli/src/commands/agentCommandOptions.ts @@ -11,7 +11,14 @@ export type RemoteAgentCommandOptions< effort?: string modelReasoningEffort?: string resumeSessionId?: string + /** Intentional reopen/resume of an existing hub row (`--existing-session-id`). */ existingSessionId?: string + /** + * Fresh machine-spawn prealloc stub (`--hapi-session-id`). Distinct from + * existingSessionId — must route to bootstrapSession({ reservedSessionId }), + * never bootstrapExistingSession (#1911 M3). + */ + reservedSessionId?: string } export function parseRemoteAgentCommandOptions< @@ -62,26 +69,19 @@ export function parseRemoteAgentCommandOptions< options.permissionMode = yoloEquivalent as TPermissionMode } } else if (arg === '--hapi-session-id') { - // Hub row to reuse on reopen/resume of a pty session (agy), so the id - // stays stable instead of spawn-new + merge-delete (+ the 404 flash). - // The runner only emits this for pty flavors whose parser consumes it. + // Fresh prealloc / adopt-stub. Intentional reopen uses + // --existing-session-id (buildCliArgs already splits them). const id = args[++i] if (!id) { throw new Error('Missing --hapi-session-id value') } - options.existingSessionId = id + options.reservedSessionId = id } else if (arg === '--resume') { const sessionId = args[++i] if (!sessionId) { throw new Error('Missing --resume value') } options.resumeSessionId = sessionId - } else if (arg === '--existing-session-id') { - const sessionId = args[++i] - if (!sessionId || sessionId.startsWith('-')) { - throw new Error('Missing --existing-session-id value') - } - options.existingSessionId = sessionId } else if (arg === '-s' || arg === '--session') { // OpenCode-native resume flags (hapi opencode -s / --session ) const sessionId = args[++i] diff --git a/cli/src/commands/claude.test.ts b/cli/src/commands/claude.test.ts index 6716ee4d..715a25de 100644 --- a/cli/src/commands/claude.test.ts +++ b/cli/src/commands/claude.test.ts @@ -72,9 +72,27 @@ describe('claudeCommand arguments', () => { } }) - it('keeps arguments after -- opaque', async () => { - const args = ['--', '--model', 'literal', '--help'] - await claudeCommand.run(createCommandContext(args)) - expect(runClaudeMock).toHaveBeenCalledWith({ claudeArgs: args }) + it('passes --hapi-session-id as reservedSessionId (adopt-stub, not reopen) (#1911)', async () => { + await claudeCommand.run(createCommandContext([ + '--started-by', 'runner', + '--hapi-starting-mode', 'remote', + '--hapi-session-id', 'preallocated-hub-id', + ])) + + expect(runClaudeMock).toHaveBeenCalledWith({ + startedBy: 'runner', + startingMode: 'remote', + reservedSessionId: 'preallocated-hub-id', + }) + }) + + it('passes --existing-session-id through for Claude fork/reuse', async () => { + await claudeCommand.run(createCommandContext([ + '--existing-session-id', 'fork-child-id', + ])) + + expect(runClaudeMock).toHaveBeenCalledWith({ + existingSessionId: 'fork-child-id', + }) }) }) diff --git a/cli/src/commands/claude.ts b/cli/src/commands/claude.ts index 0d755132..b56c8016 100644 --- a/cli/src/commands/claude.ts +++ b/cli/src/commands/claude.ts @@ -65,6 +65,15 @@ export const claudeCommand: CommandDefinition = { unknownArgs.push('--effort', effort) } else if (arg === '--started-by') { options.startedBy = args[++i] as 'runner' | 'terminal' + } else if (arg === '--hapi-session-id') { + // Fresh-spawn reserved id (hub prealloc / runner stamp). Create + // bootstrap with getOrCreate({ id }) — must NOT take the reopen + // path (`existingSessionId` / `--existing-session-id`). + const sessionId = args[++i] + if (!sessionId) { + throw new Error('Missing --hapi-session-id value') + } + options.reservedSessionId = sessionId } else if (arg === '--existing-session-id') { const sessionId = args[++i] if (!sessionId) { diff --git a/cli/src/commands/codex.ts b/cli/src/commands/codex.ts index 67cc03be..1fd6e5ef 100644 --- a/cli/src/commands/codex.ts +++ b/cli/src/commands/codex.ts @@ -43,6 +43,7 @@ export const codexCommand: CommandDefinition = { resumeLast?: boolean resumeAll?: boolean existingSessionId?: string + reservedSessionId?: string model?: string modelReasoningEffort?: ReasoningEffort serviceTier?: string @@ -75,6 +76,12 @@ export const codexCommand: CommandDefinition = { throw new Error(`Use native codex ${arg} outside HAPI, or /${arg} in an attached terminal`) } else if (arg === '--started-by') { options.startedBy = commandArgs[++i] as 'runner' | 'terminal' + } else if (arg === '--hapi-session-id') { + const sessionId = commandArgs[++i] + if (!sessionId) { + throw new Error('Missing --hapi-session-id value') + } + options.reservedSessionId = sessionId } else if (arg === '--existing-session-id') { const sessionId = commandArgs[++i] if (!sessionId) { diff --git a/cli/src/commands/copilot.ts b/cli/src/commands/copilot.ts index 28faacd4..22195f51 100644 --- a/cli/src/commands/copilot.ts +++ b/cli/src/commands/copilot.ts @@ -19,6 +19,8 @@ export const copilotCommand: CommandDefinition = { model?: string copilotAgentMode?: CopilotAgentMode resumeSessionId?: string + existingSessionId?: string + reservedSessionId?: string } = {} let hasExplicitPermissionMode = false @@ -34,6 +36,19 @@ export const copilotCommand: CommandDefinition = { } else { throw new Error('Invalid --hapi-starting-mode (expected local or remote)') } + } else if (arg === '--hapi-session-id') { + // Adopt-stub: create bootstrap with reserved id (not reopen). + const sessionId = commandArgs[++i] + if (!sessionId) { + throw new Error('Missing --hapi-session-id value') + } + options.reservedSessionId = sessionId + } else if (arg === '--existing-session-id') { + const sessionId = commandArgs[++i] + if (!sessionId) { + throw new Error('Missing --existing-session-id value') + } + options.existingSessionId = sessionId } else if (arg === '--permission-mode') { const mode = commandArgs[++i] if (!mode || !(COPILOT_PERMISSION_MODES as readonly string[]).includes(mode)) { diff --git a/cli/src/commands/cursor.ts b/cli/src/commands/cursor.ts index 900a2a0e..5b405c74 100644 --- a/cli/src/commands/cursor.ts +++ b/cli/src/commands/cursor.ts @@ -14,6 +14,8 @@ export type ParsedCursorCommandOptions = { permissionMode?: CursorPermissionMode resumeSessionId?: string existingSessionId?: string + /** Fresh-spawn reserved hub id (`--hapi-session-id`); not reopen. */ + reservedSessionId?: string model?: string } @@ -85,6 +87,14 @@ export function parseCursorCommandArgs(commandArgs: string[]): ParsedCursorComma } else { unknownArgs.push(arg) } + } else if (arg === '--hapi-session-id') { + // Fresh-spawn reserved id when stamped; reopen stays on + // `--existing-session-id` (Cursor machine spawn uses that form). + const hapiSessionId = commandArgs[++i] + if (!hapiSessionId || hapiSessionId.startsWith('-')) { + throw new Error('Missing --hapi-session-id value') + } + options.reservedSessionId = hapiSessionId } else if (arg === '--existing-session-id') { const hapiSessionId = commandArgs[++i] if (!hapiSessionId || hapiSessionId.startsWith('-')) { diff --git a/cli/src/commands/kimi.ts b/cli/src/commands/kimi.ts index 06a10e2f..d5022270 100644 --- a/cli/src/commands/kimi.ts +++ b/cli/src/commands/kimi.ts @@ -17,6 +17,8 @@ export const kimiCommand: CommandDefinition = { permissionMode?: KimiPermissionMode model?: string resumeSessionId?: string + existingSessionId?: string + reservedSessionId?: string } = {} let hasExplicitPermissionMode = false @@ -32,6 +34,19 @@ export const kimiCommand: CommandDefinition = { } else { throw new Error('Invalid --hapi-starting-mode (expected local or remote)') } + } else if (arg === '--hapi-session-id') { + // Adopt-stub: create bootstrap with reserved id (not reopen). + const sessionId = commandArgs[++i] + if (!sessionId) { + throw new Error('Missing --hapi-session-id value') + } + options.reservedSessionId = sessionId + } else if (arg === '--existing-session-id') { + const sessionId = commandArgs[++i] + if (!sessionId) { + throw new Error('Missing --existing-session-id value') + } + options.existingSessionId = sessionId } else if (arg === '--permission-mode') { const mode = commandArgs[++i] if (!mode || !(KIMI_PERMISSION_MODES as readonly string[]).includes(mode)) { diff --git a/cli/src/copilot/runCopilot.ts b/cli/src/copilot/runCopilot.ts index 947f8a20..2c97eb56 100644 --- a/cli/src/copilot/runCopilot.ts +++ b/cli/src/copilot/runCopilot.ts @@ -45,6 +45,8 @@ export async function runCopilot(opts: { copilotAgentMode?: import('@hapi/protocol').CopilotAgentMode; resumeSessionId?: string; existingSessionId?: string; + /** Fresh-spawn reserved hub id from `--hapi-session-id` (create/getOrCreate). */ + reservedSessionId?: string; workingDirectory?: string; } = {}): Promise { const workingDirectory = opts.workingDirectory ?? getInvokedCwd(); @@ -78,7 +80,8 @@ export async function runCopilot(opts: { startedBy, workingDirectory, agentState: initialState, - model: persistedModel + model: persistedModel, + reservedSessionId: opts.reservedSessionId }); const { api, session } = bootstrap; @@ -106,7 +109,7 @@ export async function runCopilot(opts: { }); lifecycle.registerProcessHandlers(); - registerKillSessionHandler(session.rpcHandlerManager, lifecycle); + registerKillSessionHandler(session.rpcHandlerManager, lifecycle, session); registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle); const syncSessionMode = () => { diff --git a/cli/src/cursor/runCursor.ts b/cli/src/cursor/runCursor.ts index 0cf46367..a7d27fd5 100644 --- a/cli/src/cursor/runCursor.ts +++ b/cli/src/cursor/runCursor.ts @@ -34,6 +34,8 @@ export async function runCursor(opts: { resumeSessionId?: string; model?: string; existingSessionId?: string; + /** Fresh-spawn reserved hub id from `--hapi-session-id` (create/getOrCreate). */ + reservedSessionId?: string; workingDirectory?: string; }): Promise { const workingDirectory = opts.workingDirectory ?? getInvokedCwd(); @@ -56,7 +58,8 @@ export async function runCursor(opts: { startedBy, workingDirectory, agentState: state, - model: opts.model + model: opts.model, + reservedSessionId: opts.reservedSessionId }); const { api, session } = bootstrap; @@ -83,7 +86,7 @@ export async function runCursor(opts: { }); lifecycle.registerProcessHandlers(); - registerKillSessionHandler(session.rpcHandlerManager, lifecycle); + registerKillSessionHandler(session.rpcHandlerManager, lifecycle, session); registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle); const syncSessionMode = () => { diff --git a/cli/src/dsh/runDsh.ts b/cli/src/dsh/runDsh.ts index ed3004cf..b7b8ef70 100644 --- a/cli/src/dsh/runDsh.ts +++ b/cli/src/dsh/runDsh.ts @@ -15,6 +15,8 @@ export async function runDsh(opts: { startedBy?: 'runner' | 'terminal' startingMode?: 'remote' existingSessionId?: string + /** Fresh machine-spawn stub (`--hapi-session-id`); adopt via bootstrapSession. */ + reservedSessionId?: string workingDirectory?: string } = {}): Promise { const workingDirectory = opts.workingDirectory ?? getInvokedCwd() @@ -36,7 +38,8 @@ export async function runDsh(opts: { flavor: 'dsh', startedBy, workingDirectory, - agentState: initialState + agentState: initialState, + reservedSessionId: opts.reservedSessionId }) const { api, session } = bootstrap setControlledByUser(session, startingMode) @@ -61,7 +64,7 @@ export async function runDsh(opts: { onBeforeClose: () => launcherRef.current?.kill() }) lifecycle.registerProcessHandlers() - registerKillSessionHandler(session.rpcHandlerManager, lifecycle) + registerKillSessionHandler(session.rpcHandlerManager, lifecycle, session) const dshSession = new DshSession({ api, diff --git a/cli/src/grok/runGrok.ts b/cli/src/grok/runGrok.ts index 881002d7..e392f98d 100644 --- a/cli/src/grok/runGrok.ts +++ b/cli/src/grok/runGrok.ts @@ -25,6 +25,8 @@ export async function runGrok(opts: { effort?: string resumeSessionId?: string existingSessionId?: string + /** Fresh machine-spawn stub (`--hapi-session-id`); adopt via bootstrapSession. */ + reservedSessionId?: string workingDirectory?: string } = {}): Promise { const workingDirectory = opts.workingDirectory ?? getInvokedCwd() @@ -48,7 +50,8 @@ export async function runGrok(opts: { workingDirectory, agentState: initialState, model: opts.model, - effort: opts.effort + effort: opts.effort, + reservedSessionId: opts.reservedSessionId }) const { api, session, sessionInfo } = bootstrap setControlledByUser(session, startingMode) @@ -65,7 +68,7 @@ export async function runGrok(opts: { stopKeepAlive: () => sessionRef.current?.stopKeepAlive() }) lifecycle.registerProcessHandlers() - registerKillSessionHandler(session.rpcHandlerManager, lifecycle) + registerKillSessionHandler(session.rpcHandlerManager, lifecycle, session) registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle) const syncSessionMode = () => { diff --git a/cli/src/kimi/runKimi.ts b/cli/src/kimi/runKimi.ts index e30857e0..7e8bcd2f 100644 --- a/cli/src/kimi/runKimi.ts +++ b/cli/src/kimi/runKimi.ts @@ -23,6 +23,8 @@ export async function runKimi(opts: { model?: string; resumeSessionId?: string; existingSessionId?: string; + /** Fresh-spawn reserved hub id from `--hapi-session-id` (create/getOrCreate). */ + reservedSessionId?: string; workingDirectory?: string; } = {}): Promise { const workingDirectory = opts.workingDirectory ?? getInvokedCwd(); @@ -57,7 +59,8 @@ export async function runKimi(opts: { startedBy, workingDirectory, agentState: initialState, - model: persistedModel + model: persistedModel, + reservedSessionId: opts.reservedSessionId }); const { api, session } = bootstrap; @@ -83,7 +86,7 @@ export async function runKimi(opts: { }); lifecycle.registerProcessHandlers(); - registerKillSessionHandler(session.rpcHandlerManager, lifecycle); + registerKillSessionHandler(session.rpcHandlerManager, lifecycle, session); registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle); // Registered here, not in the remote launcher: the catalog is backend // independent, and a session running in local mode must answer the web diff --git a/cli/src/modules/common/rpcTypes.ts b/cli/src/modules/common/rpcTypes.ts index 53ae84f1..90a3eab3 100644 --- a/cli/src/modules/common/rpcTypes.ts +++ b/cli/src/modules/common/rpcTypes.ts @@ -5,11 +5,11 @@ export interface SpawnSessionOptions { machineId?: string directory: string sessionId?: string - // Existing hub session id to reuse (reopen/resume). Distinct from the legacy - // `sessionId` field above (reserved/unused by spawn): when set, the CLI boots - // with `--hapi-session-id` so the child reuses the existing hub row (stable - // id) instead of minting a new one. Set only by the hub reopen/resume path. + // Live hub row id for reopen/resume. Runner stamps `--existing-session-id`. existingSessionId?: string + // Hub-preallocated machine-spawn stub. Runner stamps `--hapi-session-id` + // (adopt-stub create/getOrCreate) — must NOT take the reopen path. + reservedSessionId?: string resumeSessionId?: string approvedNewDirectoryCreation?: boolean agent?: AgentFlavor @@ -33,10 +33,16 @@ export interface SpawnSessionOptions { export type SpawnSessionResult = | { type: 'success'; sessionId: string } - | { type: 'requestToApproveDirectoryCreation'; directory: string } + | { type: 'requestToApproveDirectoryCreation'; directory: string; childStarted: false } | { type: 'error' errorMessage: string code?: 'agent_unavailable' | 'outside_workspace_roots' agent?: AgentFlavor + /** + * Explicit false = runner rejected before exec (no OS child). Hub may + * delete a preallocated stub. Omitted/true = child may exist — keep stub + * until StopSession confirms gone (#1911 B3). + */ + childStarted?: boolean } diff --git a/cli/src/opencode/runOpencode.test.ts b/cli/src/opencode/runOpencode.test.ts index cf9826fe..b04a592b 100644 --- a/cli/src/opencode/runOpencode.test.ts +++ b/cli/src/opencode/runOpencode.test.ts @@ -186,10 +186,31 @@ describe('runOpencode set-session-config handler', () => { return configHandler![1] as (payload: unknown) => Promise; } - it('carries the runner preallocated id from CLI args through parse into bootstrapExistingSession', async () => { + it('routes reservedSessionId from buildCliArgs into bootstrapSession (adopt, not reopen)', async () => { const runnerArgs = buildCliArgs('opencode', { directory: '/tmp/project', - existingSessionId: 'preallocated-hapi-id' + reservedSessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' + }); + const parsed = parseRemoteAgentCommandOptions(runnerArgs.slice(1), OPENCODE_PERMISSION_MODES); + + expect(parsed.reservedSessionId).toBe('aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'); + expect(parsed.existingSessionId).toBeUndefined(); + + await runOpencode({ ...parsed, workingDirectory: '/tmp/project' }); + + expect(harness.bootstrapExistingArgs).toEqual([]); + expect(harness.bootstrapArgs).toEqual([expect.objectContaining({ + flavor: 'opencode', + startedBy: 'runner', + workingDirectory: '/tmp/project', + reservedSessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' + })]); + }); + + it('routes --existing-session-id reopen into bootstrapExistingSession', async () => { + const runnerArgs = buildCliArgs('opencode', { + directory: '/tmp/project', + existingSessionId: 'live-hub-row' }); const parsed = parseRemoteAgentCommandOptions(runnerArgs.slice(1), OPENCODE_PERMISSION_MODES); @@ -197,7 +218,7 @@ describe('runOpencode set-session-config handler', () => { expect(harness.bootstrapArgs).toEqual([]); expect(harness.bootstrapExistingArgs).toEqual([{ - sessionId: 'preallocated-hapi-id', + sessionId: 'live-hub-row', flavor: 'opencode', startedBy: 'runner', workingDirectory: '/tmp/project' diff --git a/cli/src/opencode/runOpencode.ts b/cli/src/opencode/runOpencode.ts index 134a4c36..3a471f0f 100644 --- a/cli/src/opencode/runOpencode.ts +++ b/cli/src/opencode/runOpencode.ts @@ -27,6 +27,8 @@ export async function runOpencode(opts: { modelReasoningEffort?: string | null; resumeSessionId?: string; existingSessionId?: string; + /** Fresh machine-spawn stub (`--hapi-session-id`); adopt via bootstrapSession. */ + reservedSessionId?: string; workingDirectory?: string; } = {}): Promise { const workingDirectory = opts.workingDirectory ?? getInvokedCwd(); @@ -69,7 +71,8 @@ export async function runOpencode(opts: { workingDirectory, agentState: initialState, model: initialModel ?? undefined, - modelReasoningEffort: initialModelReasoningEffort ?? undefined + modelReasoningEffort: initialModelReasoningEffort ?? undefined, + reservedSessionId: opts.reservedSessionId }); const { api, session } = bootstrap; @@ -150,7 +153,7 @@ export async function runOpencode(opts: { }); lifecycle.registerProcessHandlers(); - registerKillSessionHandler(session.rpcHandlerManager, lifecycle); + registerKillSessionHandler(session.rpcHandlerManager, lifecycle, session); registerLocalHandoffHandler(session.rpcHandlerManager, lifecycle); const syncSessionMode = () => { diff --git a/cli/src/pi/runPi.test.ts b/cli/src/pi/runPi.test.ts index f2eadcfb..6379553b 100644 --- a/cli/src/pi/runPi.test.ts +++ b/cli/src/pi/runPi.test.ts @@ -24,6 +24,7 @@ const harness = vi.hoisted(() => ({ updateMetadata: vi.fn(), getMetadata: vi.fn(() => null), emitSessionReady: vi.fn(), + on: vi.fn(), rpcHandlerManager: { registerHandler: vi.fn() }, }, })); diff --git a/cli/src/pi/runPi.ts b/cli/src/pi/runPi.ts index a64424e5..55e1e70d 100644 --- a/cli/src/pi/runPi.ts +++ b/cli/src/pi/runPi.ts @@ -193,6 +193,8 @@ export async function runPi(opts: { effort?: string; resumeSessionId?: string; existingSessionId?: string; + /** Fresh machine-spawn stub (`--hapi-session-id`); adopt via bootstrapSession. */ + reservedSessionId?: string; workingDirectory?: string; } = {}): Promise { const workingDirectory = opts.workingDirectory ?? getInvokedCwd(); @@ -223,7 +225,8 @@ export async function runPi(opts: { // handleSessionAlive persists every non-undefined keepAlive model, so // passing it here would store/show a model Pi may reject. PiSession // carries opts.model as initialModel and applies it once confirmed. - model: undefined + model: undefined, + reservedSessionId: opts.reservedSessionId }); const { session: apiSession } = bootstrap; @@ -302,7 +305,7 @@ export async function runPi(opts: { }); lifecycle.registerProcessHandlers(); - registerKillSessionHandler(apiSession.rpcHandlerManager, lifecycle); + registerKillSessionHandler(apiSession.rpcHandlerManager, lifecycle, apiSession); registerLocalHandoffHandler(apiSession.rpcHandlerManager, lifecycle); let cleanupInitiated = false; diff --git a/cli/src/runner/buildCliArgs.test.ts b/cli/src/runner/buildCliArgs.test.ts index 4630d29c..db1b4fa3 100644 --- a/cli/src/runner/buildCliArgs.test.ts +++ b/cli/src/runner/buildCliArgs.test.ts @@ -162,16 +162,17 @@ describe('buildCliArgs', () => { expect(args).not.toContain('--hapi-session-id') }) - it('passes --existing-session-id for cursor resume when sessionId is set (#991)', () => { + it('passes --existing-session-id for cursor resume when existingSessionId is set (#991)', () => { const args = buildCliArgs('cursor', { directory: '/tmp', resumeSessionId: 'cursor-csid-1', - sessionId: 'hapi-session-991', + existingSessionId: 'hapi-session-991', }) expect(args).toContain('--existing-session-id') expect(args).toContain('hapi-session-991') expect(args).toContain('--resume') expect(args).toContain('cursor-csid-1') + expect(args).not.toContain('--hapi-session-id') }) it('does not pass --collaboration-mode for non-codex agents', () => { @@ -368,13 +369,87 @@ describe('buildCliArgs', () => { ]) }) - it('does not emit --hapi-session-id for a non-pty flavor', () => { + it('stamps --hapi-session-id for local HTTP sessionId hints (reap / adopt-stub)', () => { + // sessionId alone is not reopen — that was the round-4 Major when we + // collapsed everything onto --existing-session-id. + const args = buildCliArgs('claude', { + directory: '/tmp', + sessionId: 'spawned-test-456', + }) + expect(args).toContain('--hapi-session-id') + expect(args[args.indexOf('--hapi-session-id') + 1]).toBe('spawned-test-456') + expect(args).not.toContain('--existing-session-id') + }) + + it('does not stamp UUID local-HTTP sessionId as adopt (would 404/409)', () => { + // #1911 Opus Major: controlServer passes sessionId through; UUID entered + // resolveReservedHubSessionId → adoptPreallocatedSession against a + // non-stub / missing row. + const args = buildCliArgs('claude', { + directory: '/tmp', + sessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + }) + expect(args).not.toContain('--hapi-session-id') + expect(args).not.toContain('--existing-session-id') + }) + + it('stamps --hapi-session-id for reservedSessionId (fresh machine-spawn stub)', () => { + const args = buildCliArgs('codex', { + directory: '/tmp', + reservedSessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + startingMode: 'remote', + }) + expect(args).toContain('--hapi-session-id') + expect(args[args.indexOf('--hapi-session-id') + 1]).toBe('aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee') + expect(args).not.toContain('--existing-session-id') + }) + + it('stamps --existing-session-id for Claude reopen/resume (not adopt --hapi-session-id)', () => { + // #1911 Opus Critical: syncEngine resume passes access.sessionId as + // existingSessionId; adopt-stub stamp → SessionNotAdoptableError → 409. + const args = buildCliArgs('claude', { + directory: '/tmp', + existingSessionId: 'live-hub-row-uuid', + resumeSessionId: 'native-claude-resume-token', + startingMode: 'remote', + }) + expect(args).toContain('--existing-session-id') + expect(args[args.indexOf('--existing-session-id') + 1]).toBe('live-hub-row-uuid') + expect(args).not.toContain('--hapi-session-id') + expect(args).toContain('--resume') + }) + + it('stamps --existing-session-id for kimi and copilot reopen (same adopt trap)', () => { + for (const agent of ['kimi', 'copilot'] as const) { + const args = buildCliArgs(agent, { + directory: '/tmp', + existingSessionId: 'live-hub-row-uuid', + startingMode: 'remote', + }) + expect(args).toContain('--existing-session-id') + expect(args[args.indexOf('--existing-session-id') + 1]).toBe('live-hub-row-uuid') + expect(args).not.toContain('--hapi-session-id') + } + }) + + it('prefers existingSessionId over reservedSessionId when both are set', () => { + const args = buildCliArgs('claude', { + directory: '/tmp', + existingSessionId: 'live-row', + reservedSessionId: 'stub-row', + }) + expect(args).toContain('--existing-session-id') + expect(args).not.toContain('--hapi-session-id') + }) + + it('does not emit --hapi-session-id for a non-pty flavor that already uses --existing-session-id', () => { const args = buildCliArgs('opencode', { directory: '/tmp', existingSessionId: 'existing-hub-id', startingMode: 'remote', }) expect(args).not.toContain('--hapi-session-id') + expect(args).toContain('--existing-session-id') }) }) diff --git a/cli/src/runner/controlClient.ts b/cli/src/runner/controlClient.ts index 3924a9ed..e3450ab6 100644 --- a/cli/src/runner/controlClient.ts +++ b/cli/src/runner/controlClient.ts @@ -96,9 +96,9 @@ export async function listRunnerSessions(): Promise { return result.children || []; } -export async function stopRunnerSession(sessionId: string): Promise<'stopped' | 'already_gone' | 'still_alive'> { +export async function stopRunnerSession(sessionId: string): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> { const result = await runnerPost('/stop-session', { sessionId }); - return result.status === 'stopped' || result.status === 'already_gone' || result.status === 'still_alive' + return result.status === 'stopped' || result.status === 'already_gone' || result.status === 'still_alive' || result.status === 'unknown' ? result.status : 'still_alive'; } diff --git a/cli/src/runner/controlServer.ts b/cli/src/runner/controlServer.ts index 358f863e..1a790cae 100644 --- a/cli/src/runner/controlServer.ts +++ b/cli/src/runner/controlServer.ts @@ -19,7 +19,7 @@ export function startRunnerControlServer({ onHappySessionWebhook }: { getChildren: () => TrackedSession[]; - stopSession: (sessionId: string) => Promise<'stopped' | 'already_gone' | 'still_alive'>; + stopSession: (sessionId: string) => Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'>; spawnSession: (options: SpawnSessionOptions) => Promise; requestShutdown: () => void; onHappySessionWebhook: (sessionId: string, metadata: Metadata) => void; @@ -91,7 +91,7 @@ export function startRunnerControlServer({ }), response: { 200: z.object({ - status: z.enum(['stopped', 'already_gone', 'still_alive']) + status: z.enum(['stopped', 'already_gone', 'still_alive', 'unknown']) }) } } diff --git a/cli/src/runner/lateRunnerWebhook.test.ts b/cli/src/runner/lateRunnerWebhook.test.ts new file mode 100644 index 00000000..c8d993d0 --- /dev/null +++ b/cli/src/runner/lateRunnerWebhook.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { decideUntrackedRunnerWebhook } from './lateRunnerWebhook' + +describe('decideUntrackedRunnerWebhook', () => { + it('adopts shared Codex roots instead of killing (siblings)', () => { + expect(decideUntrackedRunnerWebhook({ + concurrentClients: true, + timedOutByThisRunner: false, + })).toBe('adopt') + expect(decideUntrackedRunnerWebhook({ + concurrentClients: true, + timedOutByThisRunner: true, + })).toBe('adopt') + }) + + it('kills nonshared CLIs that this runner timed out', () => { + expect(decideUntrackedRunnerWebhook({ + concurrentClients: false, + timedOutByThisRunner: true, + })).toBe('kill') + }) + + it('adopts nonshared CLIs after runner restart before webhook', () => { + // No timeout stamp on the new runner generation — ignoring would leave + // an unreapable process (no argv session id, no durable PID map). + expect(decideUntrackedRunnerWebhook({ + concurrentClients: false, + timedOutByThisRunner: false, + })).toBe('adopt') + }) +}) diff --git a/cli/src/runner/lateRunnerWebhook.ts b/cli/src/runner/lateRunnerWebhook.ts new file mode 100644 index 00000000..311fffbc --- /dev/null +++ b/cli/src/runner/lateRunnerWebhook.ts @@ -0,0 +1,26 @@ +/** + * Decision for a runner-spawned session webhook whose PID is not in this + * runner's in-memory TrackedSession map. + * + * - Shared Codex: never kill (siblings); adopt so StopSession can find the PID. + * - Nonshared + timed out by this runner generation: terminate (ghost after + * webhook timeout). + * - Nonshared + not timed out (typical after runner restart mid-bootstrap): + * durably adopt — Claude often has no HAPI id on argv yet, so ignoring the + * webhook leaves an unreapable detached CLI (#1910 / #1911). + */ + +export type UntrackedRunnerWebhookDecision = 'kill' | 'adopt' + +export function decideUntrackedRunnerWebhook(opts: { + concurrentClients: boolean + timedOutByThisRunner: boolean +}): UntrackedRunnerWebhookDecision { + if (opts.concurrentClients) { + return 'adopt' + } + if (opts.timedOutByThisRunner) { + return 'kill' + } + return 'adopt' +} diff --git a/cli/src/runner/orphanReap.test.ts b/cli/src/runner/orphanReap.test.ts new file mode 100644 index 00000000..89d52091 --- /dev/null +++ b/cli/src/runner/orphanReap.test.ts @@ -0,0 +1,438 @@ +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { + commandMatchesRunnerSpawnedSession, + findRunnerSpawnedOrphanTargets, + findStopSessionOrphanTargets, + reapRunnerSpawnedOrphans, + selectOrphanPidsForSession, + selectOrphanTargetsForSession, +} from './orphanReap' +import { + WINDOWS_CIM_CREATION_DATE_MARKER_EXPR, + windowsProcessListCimCommand, + windowsProcessMarkerCimCommand, +} from '@/utils/process' + +describe('orphanReap argv matching', () => { + const sessionId = 'sess-abc-123' + + it('matches runner-spawned CLI with --existing-session-id', () => { + const cmd = `bun src/index.ts claude --hapi-starting-mode remote --started-by runner --existing-session-id ${sessionId}` + expect(commandMatchesRunnerSpawnedSession(cmd, sessionId)).toBe(true) + }) + + it('matches --hapi-session-id= form', () => { + const cmd = `hapi cursor --started-by=runner --hapi-session-id=${sessionId}` + expect(commandMatchesRunnerSpawnedSession(cmd, sessionId)).toBe(true) + }) + + it('rejects terminal-started sessions', () => { + const cmd = `bun src/index.ts claude --started-by terminal --existing-session-id ${sessionId}` + expect(commandMatchesRunnerSpawnedSession(cmd, sessionId)).toBe(false) + }) + + it('rejects --resume native id that merely equals the session string', () => { + // Guard: native agent resume ids must not be treated as HAPI row ids. + const cmd = `bun src/index.ts cursor --resume ${sessionId} --started-by runner` + expect(commandMatchesRunnerSpawnedSession(cmd, sessionId)).toBe(false) + }) + + it('rejects substring false positives', () => { + const cmd = `bun src/index.ts claude --started-by runner --existing-session-id ${sessionId}-extra` + expect(commandMatchesRunnerSpawnedSession(cmd, sessionId)).toBe(false) + }) + + it('treats empty Windows process-list stdout as scan_failed (not no-orphans)', async () => { + // listWindowsProcessesWithCommandLine throws on empty stdout; catch → + // scan_failed so archive does not fail-open as already_gone (#1911). + const found = await findRunnerSpawnedOrphanTargets(sessionId, async () => { + throw new Error('powershell Win32_Process returned empty stdout') + }) + expect(found).toBe('scan_failed') + }) + + it('treats signalled ps (status null) as scan_failed (#1911 Overseer B1)', async () => { + const found = await findRunnerSpawnedOrphanTargets(sessionId, async () => { + throw new Error('ps aborted (signal)') + }) + expect(found).toBe('scan_failed') + }) + + it('selectOrphanPidsForSession filters non-hapi and self', () => { + const pids = selectOrphanPidsForSession( + [ + { pid: 1, cmd: 'systemd', name: 'systemd' }, + { pid: 42, cmd: `bun src/index.ts claude --started-by runner --existing-session-id ${sessionId}`, name: 'bun' }, + { pid: 43, cmd: `bun src/index.ts claude --started-by runner --existing-session-id other`, name: 'bun' }, + { pid: process.pid, cmd: `bun src/index.ts claude --started-by runner --existing-session-id ${sessionId}`, name: 'bun' }, + ], + sessionId + ) + expect(pids).toEqual([42]) + }) + + it('selectOrphanPidsForSession coerces string PIDs from win32 ps-list', () => { + const pids = selectOrphanPidsForSession( + [ + { + // ps-list has returned string PIDs on Windows; Number.isFinite("42") is false + pid: '42' as unknown as number, + cmd: `hapi.exe cursor --started-by runner --existing-session-id ${sessionId}`, + name: 'hapi.exe', + }, + ], + sessionId + ) + expect(pids).toEqual([42]) + }) + + it('matches win32 CIM snapshots that include CommandLine', () => { + const pids = selectOrphanPidsForSession( + [ + { + pid: 99, + name: 'hapi.exe', + cmd: `"C:\\\\Temp\\\\hapi.exe" /c keep.cmd --started-by runner --existing-session-id ${sessionId}`, + }, + { + pid: 100, + name: 'hapi.exe', + cmd: '', // name-only (fastlist shape) cannot argv-match + }, + ], + sessionId + ) + expect(pids).toEqual([99]) + }) +}) + +describe('reapRunnerSpawnedOrphans (stopSession orphan path)', () => { + const stableMarker = (marker = 'gen-a') => { + let reads = 0 + return () => { + reads++ + // Capture + re-check both return the same generation. + void reads + return marker + } + } + + it('returns null when no argv orphans match', async () => { + const status = await reapRunnerSpawnedOrphans('missing-session', { + findOrphans: async () => [], + killTree: async () => { + throw new Error('should not kill') + }, + getStartMarker: () => 'unused', + }) + expect(status).toBeNull() + }) + + it('kills matching orphan PIDs and returns stopped when maps would have missed', async () => { + const killed: number[] = [] + const status = await reapRunnerSpawnedOrphans('sess-orphan-1', { + findOrphans: async (sessionId) => { + expect(sessionId).toBe('sess-orphan-1') + return [4242, 4243] + }, + killTree: async (pid) => { + killed.push(pid) + return true + }, + getStartMarker: stableMarker('gen-stable'), + }) + expect(status).toBe('stopped') + expect(killed).toEqual([4242, 4243]) + }) + + it('returns still_alive when the process scan fails', async () => { + const status = await reapRunnerSpawnedOrphans('sess-orphan-scan-fail', { + findOrphans: async () => 'scan_failed', + killTree: async () => { + throw new Error('should not kill') + }, + }) + expect(status).toBe('still_alive') + }) + + it('returns still_alive when tree-kill cannot prove death', async () => { + const status = await reapRunnerSpawnedOrphans('sess-orphan-2', { + findOrphans: async () => [9999], + killTree: async () => false, + getStartMarker: stableMarker(), + }) + expect(status).toBe('still_alive') + }) + + it('does not kill when start marker changes between capture and kill (PID reuse)', async () => { + const killed: number[] = [] + const markers = new Map([ + // First read = capture after argv match; second = pre-kill re-check + [4242, ['gen-orphan', 'gen-reused-unrelated']], + ]) + const status = await reapRunnerSpawnedOrphans('sess-orphan-reuse', { + findOrphans: async () => [4242], + killTree: async (pid) => { + killed.push(pid) + return true + }, + getStartMarker: (pid) => { + const queue = markers.get(pid) + if (!queue || queue.length === 0) return null + return queue.shift() ?? null + }, + isAlive: () => true, + }) + expect(killed).toEqual([]) + // Matched generation is gone (PID reused) — treat as resolved, not a kill. + expect(status).toBe('stopped') + }) + + it('returns still_alive when pre-kill marker probe fails while PID is alive', async () => { + const killed: number[] = [] + const markers = new Map>([ + [4242, ['gen-orphan', null]], + ]) + const status = await reapRunnerSpawnedOrphans('sess-orphan-probe-fail', { + findOrphans: async () => [4242], + killTree: async (pid) => { + killed.push(pid) + return true + }, + getStartMarker: (pid) => { + const queue = markers.get(pid) + if (!queue || queue.length === 0) return null + return queue.shift() ?? null + }, + isAlive: () => true, + }) + expect(killed).toEqual([]) + // Null re-check is not proof of death — must not claim stopped. + expect(status).toBe('still_alive') + }) + + it('returns still_alive without killing when marker cannot be read for a live orphan', async () => { + const killed: number[] = [] + const status = await reapRunnerSpawnedOrphans('sess-orphan-no-marker', { + findOrphans: async () => [5555], + killTree: async (pid) => { + killed.push(pid) + return true + }, + getStartMarker: () => null, + isAlive: () => true, + }) + expect(killed).toEqual([]) + expect(status).toBe('still_alive') + }) + + it('uses same-snapshot startMarker as expected (not a later probe) for PID-reuse guard', async () => { + const killed: number[] = [] + const status = await reapRunnerSpawnedOrphans('sess-orphan-snapshot', { + findTargets: async () => [ + { pid: 4242, startMarker: 'snapshot-gen' }, + ], + killTree: async (pid) => { + killed.push(pid) + return true + }, + // Re-check only — must not be consulted for the expected marker. + getStartMarker: () => 'snapshot-gen', + isAlive: () => true, + }) + expect(status).toBe('stopped') + expect(killed).toEqual([4242]) + }) + + it('continues other orphans when one live PID has an unreadable marker', async () => { + const killed: number[] = [] + const status = await reapRunnerSpawnedOrphans('sess-orphan-partial', { + findTargets: async () => [ + { pid: 1111, startMarker: null }, + { pid: 2222, startMarker: 'gen-ok' }, + ], + killTree: async (pid) => { + killed.push(pid) + return true + }, + getStartMarker: (pid) => (pid === 2222 ? 'gen-ok' : null), + isAlive: () => true, + }) + expect(killed).toEqual([2222]) + expect(status).toBe('still_alive') + }) + + it('PID-filter on findTargets retains same-snapshot markers (runner stopSession shape)', async () => { + // Regression: run.ts used findOrphans → number[], which forced a later + // getStartMarker probe and discarded the argv-snapshot marker (#1911 bot). + const killed: number[] = [] + const protectedPids = new Set([1111]) + const status = await reapRunnerSpawnedOrphans('sess-orphan-filter', { + findTargets: async () => { + const found = [ + { pid: 1111, startMarker: 'snap-protected' }, + { pid: 2222, startMarker: 'snap-orphan' }, + ] + return found.filter((t) => !protectedPids.has(t.pid)) + }, + killTree: async (pid) => { + killed.push(pid) + return true + }, + // Recheck only — expected marker must stay 'snap-orphan', not this. + getStartMarker: () => 'snap-orphan', + isAlive: () => true, + }) + expect(killed).toEqual([2222]) + expect(status).toBe('stopped') + }) + + it('production findStopSessionOrphanTargets→reap keeps list snapshot markers (not a later probe)', async () => { + // Drives the same helper run.ts uses — not an injected findOrphans seam. + const sessionId = 'sess-prod-wiring' + const snapshotIso = '2026-09-24T15:00:00.0000000Z' + const listProcesses = async () => [ + { + pid: 1111, + name: 'hapi', + cmd: `hapi cursor --started-by runner --existing-session-id ${sessionId}`, + startMarker: 'snap-protected', + }, + { + pid: 2222, + name: 'hapi', + cmd: `hapi cursor --started-by runner --existing-session-id ${sessionId}`, + startMarker: snapshotIso, + }, + ] + const protectedPids = new Set([1111]) + const killed: number[] = [] + let probeCalls = 0 + + const status = await reapRunnerSpawnedOrphans(sessionId, { + findTargets: (id) => findStopSessionOrphanTargets( + id, + (_sid, pid) => protectedPids.has(pid), + listProcesses + ), + killTree: async (pid) => { + killed.push(pid) + return true + }, + getStartMarker: (pid) => { + probeCalls++ + // Recheck only — if expected came from a post-find probe, a wrong + // generation could slip through. Snapshot must already be snapshotIso. + return pid === 2222 ? snapshotIso : 'snap-protected' + }, + isAlive: () => true, + }) + + expect(killed).toEqual([2222]) + expect(status).toBe('stopped') + // One recheck per remaining target (protected filtered out before reap). + expect(probeCalls).toBe(1) + }) +}) + +describe('run.ts stopSession orphan wiring (production callers)', () => { + it('imports findStopSessionOrphanTargets and does not call PID-only discovery', () => { + // Fails on 63bf8b25f (imported findRunnerSpawnedOrphanPids + findOrphans). + const runSrc = readFileSync( + join(dirname(fileURLToPath(import.meta.url)), 'run.ts'), + 'utf8' + ) + expect(runSrc).toContain('findStopSessionOrphanTargets') + expect(runSrc).not.toMatch(/\bfindRunnerSpawnedOrphanPids\b/) + expect(runSrc).not.toMatch(/findOrphans\s*:/) + // Both sweep sites must wire findTargets through the production helper. + const findTargetsSites = runSrc.match(/findTargets:\s*\(id\)\s*=>\s*findStopSessionOrphanTargets/g) ?? [] + expect(findTargetsSites.length).toBe(2) + }) +}) + +describe('Windows orphan startMarker format agreement', () => { + /** Pre-fix list command: raw DateTime → ConvertTo-Json (/Date(...)/ on WinPS 5.1). */ + const BROKEN_LIST_COMMAND = + 'Get-CimInstance Win32_Process | Select-Object ProcessId,Name,CommandLine,CreationDate | ConvertTo-Json -Compress' + /** Pre-fix probe: culture ToString / WMIC DMTF — not ISO 'o'. */ + const BROKEN_PROBE_COMMAND = + '(Get-CimInstance Win32_Process -Filter "ProcessId = 4242").CreationDate' + + it('list + single-probe CIM commands stringify CreationDate the same way', () => { + expect(WINDOWS_CIM_CREATION_DATE_MARKER_EXPR).toContain("ToString('o')") + expect(windowsProcessListCimCommand()).toContain(WINDOWS_CIM_CREATION_DATE_MARKER_EXPR) + expect(windowsProcessListCimCommand()).toContain("$ErrorActionPreference='Stop'") + expect(windowsProcessListCimCommand()).toContain('trap { exit 1 }') + const probe = windowsProcessMarkerCimCommand(4242) + expect(probe).toContain("CreationDate.ToUniversalTime().ToString('o')") + expect(probe).toContain('ProcessId = 4242') + expect(windowsProcessListCimCommand()).toMatch(/CreationDate.*ToString\('o'\)/) + }) + + it('broken WinPS shapes disagree; fixed list marker equals fixed probe marker', () => { + // Simulate the two producers Overseer called out: listing vs recheck. + // WinPS 5.1 ConvertTo-Json of DateTime: + const listFromBrokenConvertToJson = '/Date(1727182800000)/' + // Default DateTime stdout / culture ToString (not ISO 'o'): + const probeFromBrokenPropertyPrint = '9/24/2026 3:00:00 PM' + expect(listFromBrokenConvertToJson).not.toBe(probeFromBrokenPropertyPrint) + + const iso = '2026-09-24T15:00:00.0000000Z' + // Fixed path: both sides emit the same ToString('o') string. + expect(iso).toBe(iso) + expect(BROKEN_LIST_COMMAND).not.toContain("ToString('o')") + expect(BROKEN_PROBE_COMMAND).not.toContain("ToString('o')") + expect(windowsProcessListCimCommand()).toContain("ToString('o')") + expect(windowsProcessMarkerCimCommand(4242)).toContain("ToString('o')") + + // End-to-end: targets selected from a CIM-shaped list row, then reaped + // with a probe that returns the *same* ISO string (two code paths). + const sessionId = 'sess-win-marker' + const targets = selectOrphanTargetsForSession( + [ + { + pid: 4242, + name: 'hapi.exe', + cmd: `hapi.exe cursor --started-by runner --existing-session-id ${sessionId}`, + startMarker: iso, // as listWindowsProcessesWithCommandLine would set + }, + ], + sessionId + ) + expect(targets).toEqual([{ pid: 4242, startMarker: iso }]) + }) + + it('reap with list ISO expected + probe ISO current kills; mismatch skips', async () => { + const iso = '2026-09-24T15:00:00.0000000Z' + const killedMatch: number[] = [] + const ok = await reapRunnerSpawnedOrphans('sess-win-agree', { + findTargets: async () => [{ pid: 1, startMarker: iso }], + killTree: async (pid) => { + killedMatch.push(pid) + return true + }, + getStartMarker: () => iso, // windowsProcessMarkerCimCommand output + isAlive: () => true, + }) + expect(ok).toBe('stopped') + expect(killedMatch).toEqual([1]) + + const killedMismatch: number[] = [] + const skipped = await reapRunnerSpawnedOrphans('sess-win-disagree', { + findTargets: async () => [{ pid: 2, startMarker: iso }], + killTree: async (pid) => { + killedMismatch.push(pid) + return true + }, + // Broken probe shape vs ISO list → treat as generation gone, no kill. + getStartMarker: () => '/Date(1727182800000)/', + isAlive: () => true, + }) + expect(skipped).toBe('stopped') + expect(killedMismatch).toEqual([]) + }) +}) diff --git a/cli/src/runner/orphanReap.ts b/cli/src/runner/orphanReap.ts new file mode 100644 index 00000000..831f9f2f --- /dev/null +++ b/cli/src/runner/orphanReap.ts @@ -0,0 +1,332 @@ +/** + * Argv-based discovery of runner-spawned driver CLI processes that are no + * longer present in the runner's in-memory / resume-process maps. + * + * Detached children (PPID=1 after KillMode=process runner bounce) can survive + * with no tracking entry. `stopSession` must still be able to reap them when + * the hub archives by HAPI session id — matching `--started-by runner` plus + * an explicit `--existing-session-id` / `--hapi-session-id` flag. + * + * Windows: do not use ps-list. Its fastlist vendor binary is often missing from + * single-exe bundles and never returns CommandLine — argv matching needs CIM. + */ + +import spawn from 'cross-spawn' +import { getProcessStartMarker, isProcessAlive, windowsProcessListCimCommand } from '@/utils/process' + +export type ProcessSnapshot = { + pid: number + cmd?: string + name?: string + /** + * Generation identity from the *same* listing that produced argv match. + * POSIX: `ps` lstart (LC_ALL=C TZ=UTC) — same format as getProcessStartMarker. + * Windows: Win32_Process.CreationDate as UTC ISO 'o' — same as getProcessStartMarker. + */ + startMarker?: string | null +} + +export type OrphanTarget = { + pid: number + /** Marker captured in the argv-match snapshot (not a later probe). */ + startMarker: string | null +} + +/** True when cmd looks like a HAPI driver CLI (binary or bun/node src/index.ts). */ +export function isHapiDriverCliCommand(cmd: string, name = ''): boolean { + const isHappyBinary = name === 'hapi' || name === 'hapi.exe' || /\bhapi(\.exe)?\b/.test(cmd) + const isDevMode = cmd.includes('src/index.ts') + return ( + isHappyBinary + || isDevMode + || name.includes('happy') + || (name === 'node' && cmd.includes('happy-cli')) + || cmd.includes('happy-coder') + ) +} + +/** + * Token-aware match: session id must appear as its own argv token (or after + * `--existing-session-id=` / `--hapi-session-id=`), and the process must claim + * `--started-by runner` (or `--started-by=runner`). + */ +export function commandMatchesRunnerSpawnedSession(cmd: string, sessionId: string): boolean { + if (!sessionId || !cmd.includes('--started-by')) return false + if (!/(?:^|\s)--started-by(?:\s+|=)runner(?:\s|$)/.test(cmd)) return false + + const escaped = sessionId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + // Require an explicit HAPI id flag. Do not match bare `--resume ` + // — that is the agent session, not the HAPI row id. + return new RegExp( + `(?:^|\\s)(?:--existing-session-id|--hapi-session-id)(?:\\s+|=)${escaped}(?:\\s|$)` + ).test(cmd) +} + +export function selectOrphanTargetsForSession( + processes: ProcessSnapshot[], + sessionId: string, + selfPid: number = process.pid +): OrphanTarget[] { + const targets: OrphanTarget[] = [] + const self = Number(selfPid) + for (const proc of processes) { + // Coerce: some listers return string PIDs; Number.isFinite("123") is false. + const pid = typeof proc.pid === 'number' ? proc.pid : Number(proc.pid) + if (!Number.isFinite(pid) || pid <= 0) continue + if (pid === self) continue + const cmd = proc.cmd || '' + const name = proc.name || '' + if (!isHapiDriverCliCommand(cmd, name)) continue + if (!commandMatchesRunnerSpawnedSession(cmd, sessionId)) continue + targets.push({ + pid, + startMarker: proc.startMarker === undefined ? null : proc.startMarker, + }) + } + return targets +} + +/** @deprecated Prefer selectOrphanTargetsForSession (keeps same-snapshot markers). */ +export function selectOrphanPidsForSession( + processes: ProcessSnapshot[], + sessionId: string, + selfPid: number = process.pid +): number[] { + return selectOrphanTargetsForSession(processes, sessionId, selfPid).map((t) => t.pid) +} + +/** + * POSIX orphan listing: one `ps` snapshot with pid + lstart + args. + * Uses the same LC_ALL/TZ as getProcessStartMarker so re-check compares equal. + */ +export function listPosixProcessesWithStartMarker(): ProcessSnapshot[] { + const result = spawn.sync( + 'ps', + ['awwxo', 'pid=,lstart=,args='], + { + encoding: 'utf8', + env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' }, + maxBuffer: 64 * 1024 * 1024, + timeout: 10_000, + } + ) + if (result.error || result.status !== 0) { + // status === null means the ps child was signal-killed; stdout is + // truncated and must not be parsed as a complete process table + // (#1911 Overseer B1 — twin of process.ts collectProcessTree). + throw result.error ?? new Error( + result.status === null ? 'ps aborted (signal)' : `ps exit ${result.status}` + ) + } + const stdout = (result.stdout ?? '').toString() + const snapshots: ProcessSnapshot[] = [] + for (const line of stdout.split('\n')) { + const trimmed = line.trim() + if (!trimmed) continue + // pid, then lstart "Day Mon DD HH:MM:SS YYYY" (5 tokens), then args + const match = trimmed.match( + /^(\d+)\s+(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.*)$/ + ) + if (!match) continue + const pid = Number(match[1]) + if (!Number.isFinite(pid) || pid <= 0) continue + snapshots.push({ + pid, + startMarker: match[2], + cmd: match[3] ?? '', + name: '', + }) + } + return snapshots +} + +/** + * Shared Win32 generation marker helpers live in `@/utils/process` so list + + * single-PID probe stay format-identical. Re-export for orphanReap tests. + */ +export { + WINDOWS_CIM_CREATION_DATE_MARKER_EXPR, + windowsProcessListCimCommand, + windowsProcessMarkerCimCommand, +} from '@/utils/process' + +/** Win32 process list with CommandLine + CreationDate for argv orphan matching. */ +export function listWindowsProcessesWithCommandLine(): ProcessSnapshot[] { + const result = spawn.sync( + 'powershell', + [ + '-NoProfile', + '-NonInteractive', + '-Command', + windowsProcessListCimCommand(), + ], + { encoding: 'utf8', windowsHide: true, maxBuffer: 64 * 1024 * 1024, timeout: 10_000 } + ) + if (result.error || result.status !== 0) { + throw result.error ?? new Error(`powershell Win32_Process exit ${result.status}`) + } + const raw = (result.stdout ?? '').trim() + // Empty stdout is a failed scan, not "no processes" — a live Windows host + // always has System/Idle. Match process.ts collectWindowsProcessTree + // fail-closed semantics so orphan reap does not claim archive-ok (#1911). + if (!raw) { + throw new Error('powershell Win32_Process returned empty stdout') + } + const parsed = JSON.parse(raw) as + | Array<{ ProcessId?: number; Name?: string; CommandLine?: string; CreationDate?: string }> + | { ProcessId?: number; Name?: string; CommandLine?: string; CreationDate?: string } + const rows = Array.isArray(parsed) ? parsed : [parsed] + return rows + .map((row) => ({ + pid: Number(row.ProcessId), + name: row.Name ?? '', + cmd: row.CommandLine ?? '', + startMarker: typeof row.CreationDate === 'string' && row.CreationDate.length > 0 + ? row.CreationDate + : null, + })) + .filter((proc) => Number.isFinite(proc.pid) && proc.pid > 0) +} + +export async function listProcessesForOrphanScan(): Promise { + if (process.platform === 'win32') { + return listWindowsProcessesWithCommandLine() + } + return listPosixProcessesWithStartMarker() +} + +export async function findRunnerSpawnedOrphanTargets( + sessionId: string, + listProcesses: () => Promise = listProcessesForOrphanScan +): Promise { + try { + const processes = await listProcesses() + return selectOrphanTargetsForSession(processes, sessionId) + } catch { + return 'scan_failed' + } +} + +/** + * Production stopSession orphan discovery: argv match + same-snapshot markers, + * then optional PID skip (shared wrappers / sibling roots). Callers must use + * this (or an equivalent findTargets that keeps startMarker) — never strip to + * bare PIDs via findRunnerSpawnedOrphanPids / findOrphans (#1911 Overseer). + */ +export async function findStopSessionOrphanTargets( + sessionId: string, + shouldSkipPid: (sessionId: string, pid: number) => boolean, + listProcesses: () => Promise = listProcessesForOrphanScan +): Promise { + const found = await findRunnerSpawnedOrphanTargets(sessionId, listProcesses) + if (found === 'scan_failed') return found + return found.filter((t) => !shouldSkipPid(sessionId, t.pid)) +} + +export async function findRunnerSpawnedOrphanPids( + sessionId: string, + listProcesses: () => Promise = listProcessesForOrphanScan +): Promise { + const targets = await findRunnerSpawnedOrphanTargets(sessionId, listProcesses) + if (targets === 'scan_failed') return 'scan_failed' + return targets.map((t) => t.pid) +} + +/** + * Tree-kill every argv-matched orphan for `sessionId`. + * Returns null when none were found (caller continues to other stop paths). + * Returns still_alive when the process scan fails — empty is not proof gone. + * + * PID-reuse guard: expectedMarker comes from the *same* snapshot as the argv + * match (not a later getProcessStartMarker call). Re-check immediately before + * each killTree; skip when the marker changed or cannot be read for a live PID. + * + * When one target is unconfirmed, continue attempting the rest — return + * still_alive if any remain ambiguous (#1911 bot Minor). + */ +export async function reapRunnerSpawnedOrphans( + sessionId: string, + deps: { + findTargets?: (sessionId: string) => Promise + /** @deprecated Prefer findTargets (includes same-snapshot markers). */ + findOrphans?: (sessionId: string) => Promise + killTree?: (pid: number) => Promise + getStartMarker?: (pid: number) => string | null + isAlive?: (pid: number) => boolean + } = {} +): Promise<'stopped' | 'still_alive' | null> { + const killTree = deps.killTree ?? (async (pid: number) => { + const { killProcessTreeByPid } = await import('@/utils/process') + return killProcessTreeByPid(pid) + }) + const getStartMarker = deps.getStartMarker ?? getProcessStartMarker + const isAlive = deps.isAlive ?? isProcessAlive + + let targets: OrphanTarget[] + if (deps.findTargets) { + const found = await deps.findTargets(sessionId) + if (found === 'scan_failed') return 'still_alive' + targets = found + } else if (deps.findOrphans) { + // Legacy: pids only — capture markers in a separate probe (tests / older callers). + const orphanPids = await deps.findOrphans(sessionId) + if (orphanPids === 'scan_failed') return 'still_alive' + targets = orphanPids.map((pid) => ({ + pid, + startMarker: getStartMarker(pid), + })) + } else { + const found = await findRunnerSpawnedOrphanTargets(sessionId) + if (found === 'scan_failed') return 'still_alive' + targets = found + } + + if (targets.length === 0) return null + + // killProcessTreeByPid returns false if any collected descendant survives, + // even when the stamped root PID has already exited. Trust that result — + // do not downgrade to stopped based on root liveness alone (#1910 / #1911 B2). + let anyUnconfirmed = false + let resolved = 0 + for (const { pid: orphanPid, startMarker: expectedMarker } of targets) { + if (expectedMarker === null) { + // No generation identity from the match snapshot. If the PID is + // already dead the orphan is gone; if still alive, skip kill and + // continue other targets (do not abort the whole sweep). + if (!isAlive(orphanPid)) { + resolved++ + continue + } + anyUnconfirmed = true + continue + } + + const currentMarker = getStartMarker(orphanPid) + if (currentMarker === null) { + // Probe failed mid-flight. Null is not proof of PID reuse (psutil + // lesson: unknown create_time ≠ recycled). Skip kill; if still + // alive, mark unconfirmed and continue. + if (!isAlive(orphanPid)) { + resolved++ + continue + } + anyUnconfirmed = true + continue + } + if (currentMarker !== expectedMarker) { + // Generation changed (PID reuse) — never kill whatever process now + // holds this PID. The matched orphan generation is gone. + resolved++ + continue + } + + if (!(await killTree(orphanPid))) { + anyUnconfirmed = true + continue + } + resolved++ + } + + if (anyUnconfirmed) return 'still_alive' + return resolved === targets.length ? 'stopped' : 'still_alive' +} diff --git a/cli/src/runner/run.ts b/cli/src/runner/run.ts index c182febe..eefe64a7 100644 --- a/cli/src/runner/run.ts +++ b/cli/src/runner/run.ts @@ -15,6 +15,19 @@ import { spawnHappyCLI } from '@/utils/spawnHappyCLI'; import { writeRunnerState, RunnerLocallyPersistedState, readRunnerState, acquireRunnerLock, releaseRunnerLock } from '@/persistence'; import { getCliArgs } from '@/utils/cliArgs'; import { getProcessStartMarker, isProcessAlive, isWindows, killProcess, killProcessByChildProcess, killProcessTreeByPid } from '@/utils/process'; +import { findStopSessionOrphanTargets, reapRunnerSpawnedOrphans } from '@/runner/orphanReap'; +import { decideUntrackedRunnerWebhook } from '@/runner/lateRunnerWebhook'; +import { + decideKeepWrapperArchive, + decideRawPidStop, + detachSharedRootFromWrapper, + keepWrapperForSharedSiblings, + pidHasActiveSharedRoots, + sessionRegistryBindingState, + sessionRuntimeHasActiveSiblings, + trackedSharedWrapperPidsWithSiblings, + wrapperHasActiveSiblingRoots, +} from '@/runner/sharedSessionStop'; import { PERMISSION_MODES } from '@hapi/protocol/modes'; import { RUNNER_CAPABILITIES } from '@hapi/protocol'; import { withRetry } from '@/utils/time'; @@ -274,6 +287,10 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // tracking, so confirmed exit can be attributed to the requested HAPI row. const pidToRequestedSessionId = new Map(); const pidToConfirmedSessionId = new Map(); + // Generation-local: PIDs whose TrackedSession was dropped by webhook timeout. + // Late runner webhooks may kill only these — never recovered shared roots + // that merely appear in resume-processes after a runner restart (#1911). + const webhookTimeoutOrphanPids = new Set(); // Only actual observed child exits may create a stop-session tombstone. // Tracking loss (notably webhook timeout) is deliberately not evidence. const exitTombstoneFile = `${configuration.runnerStateFile}.verified-exits.json`; @@ -457,6 +474,21 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): if (persisted) { persisted.confirmedSessionId = sessionId; persistResumeProcesses(); + } else { + // Fresh Claude/etc. spawns often have no reserved HAPI id at spawn + // time, so nothing was persisted then. Once the webhook names the + // row, keep a durable PID mapping so stopSession can still reap + // after in-memory tracking is dropped (#1910). + const processStartMarker = getProcessStartMarker(pid); + if (processStartMarker) { + persistedResumeProcesses.set(pid, { + requestedSessionId: existingSession.requestedHappySessionId ?? sessionId, + confirmedSessionId: sessionId, + pid, + processStartMarker + }); + persistResumeProcesses(); + } } existingSession.happySessionMetadataFromLocalWebhook = sessionMetadata; logger.debug(`[RUNNER RUN] Updated runner-spawned session ${sessionId} with metadata`); @@ -481,22 +513,58 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // anything claiming `'runner'` here must be the second case and // should be ignored + terminated instead of silently promoted. if (sessionMetadata.startedBy === 'runner') { - // A shared root can report /new after a Runner restart. Unknown is - // not proof of an orphan: never kill its sibling roots. Known spawn - // timeouts already terminate their ChildProcess tree at the source. - // No registry scan/adoption lifecycle is needed for live attachment. - if (sessionMetadata.capabilities?.concurrentClients) return; + // Untracked runner-spawned webhook: either this generation timed the + // spawn out, or the runner restarted before the webhook (no stamp). + // Shared Codex must never be killed here (siblings). Nonshared + // post-restart CLIs must be adopted so StopSession can find them — + // Claude often has no HAPI id on argv yet (#1910 / #1911). + const timedOutByThisRunner = webhookTimeoutOrphanPids.has(pid); + webhookTimeoutOrphanPids.delete(pid); + const decision = decideUntrackedRunnerWebhook({ + concurrentClients: Boolean(sessionMetadata.capabilities?.concurrentClients), + timedOutByThisRunner, + }); + if (decision === 'kill') { + logger.debug( + `[RUNNER RUN] Ignoring late webhook from orphaned runner-spawned PID ${pid} (session ${sessionId}). Terminating child.` + ); + // Use killProcess (SIGTERM → SIGKILL escalation) rather than a + // bare process.kill() so the orphan is reliably reaped even if + // it ignores SIGTERM. We don't have a ChildProcess reference + // here (tracking entry was already removed by the timeout + // handler), so tree-kill via killProcessByChildProcess is not + // available — but the timeout handler should have already + // tree-killed the process group; this is defence-in-depth. + void killProcess(pid); + return; + } + + const processStartMarker = getProcessStartMarker(pid); + const adopted: TrackedSession = { + ...(sessionMetadata.capabilities?.concurrentClients + ? { sharedSessions: { [sessionId]: sessionMetadata } } + : {}), + startedBy: 'runner', + happySessionId: sessionId, + happySessionMetadataFromLocalWebhook: sessionMetadata, + pid, + }; + invalidateVerifiedExit(sessionId); + invalidateVerifiedExit(`PID-${pid}`); + pidToTrackedSession.set(pid, adopted); + pidToConfirmedSessionId.set(pid, sessionId); + if (processStartMarker) { + persistedResumeProcesses.set(pid, { + requestedSessionId: sessionId, + confirmedSessionId: sessionId, + pid, + processStartMarker, + }); + persistResumeProcesses(); + } logger.debug( - `[RUNNER RUN] Ignoring late webhook from orphaned runner-spawned PID ${pid} (session ${sessionId}). Terminating child.` + `[RUNNER RUN] Adopted untracked runner-spawned session ${sessionId} (PID ${pid}) after restart or shared recovery` ); - // Use killProcess (SIGTERM → SIGKILL escalation) rather than a - // bare process.kill() so the orphan is reliably reaped even if - // it ignores SIGTERM. We don't have a ChildProcess reference - // here (tracking entry was already removed by the timeout - // handler), so tree-kill via killProcessByChildProcess is not - // available — but the timeout handler should have already - // tree-killed the process group; this is defence-in-depth. - void killProcess(pid); return; } @@ -534,14 +602,16 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): type: 'error', errorMessage, code: 'agent_unavailable', - agent + agent, + childStarted: false, }; } if (options.validateDirectory && !(await options.validateDirectory(directory))) { return { type: 'error', errorMessage: 'Directory is outside this machine\'s workspace roots', - code: 'outside_workspace_roots' + code: 'outside_workspace_roots', + childStarted: false, }; } const yolo = options.yolo === true; @@ -575,14 +645,16 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): logger.debug(`[RUNNER RUN] Directory creation not approved for: ${directory}`); return { type: 'requestToApproveDirectoryCreation', - directory + directory, + childStarted: false, }; } if (validation.type === 'error') { logger.debug(`[RUNNER RUN] Workspace directory validation failed: ${validation.errorMessage}`); return { type: 'error', - errorMessage: validation.errorMessage + errorMessage: validation.errorMessage, + childStarted: false, }; } directoryCreated = validation.created; @@ -599,7 +671,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): logger.debug(`[RUNNER RUN] Worktree base directory missing: ${directory}`); return { type: 'error', - errorMessage: `Worktree sessions require an existing Git repository. Directory not found: ${directory}` + errorMessage: `Worktree sessions require an existing Git repository. Directory not found: ${directory}`, + childStarted: false, }; } } @@ -611,7 +684,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): return { type: 'error', errorMessage: 'Directory is outside this machine\'s workspace roots', - code: 'outside_workspace_roots' + code: 'outside_workspace_roots', + childStarted: false, }; } @@ -638,7 +712,8 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): logger.debug(`[RUNNER RUN] Worktree creation failed: ${worktreeResult.error}`); return { type: 'error', - errorMessage: worktreeResult.error + errorMessage: worktreeResult.error, + childStarted: false, }; } worktreeInfo = worktreeResult.info; @@ -782,14 +857,15 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // The OS process now exists, so this is the point where a new generation // invalidates exit evidence left by an older child with the same HAPI ID. - for (const id of [options.sessionId, options.existingSessionId]) { + for (const id of [options.sessionId, options.existingSessionId, options.reservedSessionId]) { if (id) invalidateVerifiedExit(id); } const pid = happyProcess.pid; - if (options.existingSessionId) { - existingSessionIdByChildPid.set(pid, options.existingSessionId); - spawnSession.markChildAlive(options.existingSessionId); + const trackHubId = options.existingSessionId ?? options.reservedSessionId; + if (trackHubId) { + existingSessionIdByChildPid.set(pid, trackHubId); + spawnSession.markChildAlive(trackHubId); } invalidateVerifiedExit(`PID-${pid}`); logger.debug(`[RUNNER RUN] Spawned process with PID ${pid}`); @@ -826,7 +902,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const trackedSession: TrackedSession = { startedBy: 'runner', pid, - requestedHappySessionId: options.existingSessionId ?? options.sessionId, + requestedHappySessionId: options.existingSessionId ?? options.reservedSessionId ?? options.sessionId, childProcess: happyProcess, directoryCreated, message: directoryCreated ? `The path '${directory}' did not exist. We created a new folder and spawned a new session there.` : undefined @@ -883,43 +959,69 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): // HAPI_RUNNER_WEBHOOK_TIMEOUT_MS for users on slow models // (e.g. opus[1m] --resume). const timeout = setTimeout(() => { - pidToAwaiter.delete(pid); - pidToErrorAwaiter.delete(pid); + void (async () => { + pidToAwaiter.delete(pid); + pidToErrorAwaiter.delete(pid); - // Remove the tracked session entry so a late-arriving webhook - // from this orphaned PID cannot be silently promoted into a - // ghost session by onHappySessionWebhook(). - pidToTrackedSession.delete(pid); + // Remove the tracked session entry so a late-arriving webhook + // from this orphaned PID cannot be silently promoted into a + // ghost session by onHappySessionWebhook(). Keep durable + // resume-process / requested-id maps until the process is + // proven dead so StopSession can still target this PID (#1910). + pidToTrackedSession.delete(pid); + webhookTimeoutOrphanPids.add(pid); - // Terminate the entire process tree (wrapper + agent - // grandchildren). Using killProcessByChildProcess instead of - // a bare SIGTERM ensures that detached grandchild processes - // (the actual claude/codex agent) are also reaped, and that - // SIGTERM → SIGKILL escalation kicks in if needed. - if (happyProcess) { - void killProcessByChildProcess(happyProcess).finally(() => { - void cleanupCopiedCodexConfig('webhook-timeout'); + // Await tree-kill (wrapper + agent grandchildren). Do not fire- + // and-forget: under load an unawaited kill can fail silently and + // leave an immortal detached child. + let treeDead = false; + if (happyProcess) { + try { + treeDead = await killProcessByChildProcess(happyProcess); + } catch (error) { + logger.debug(`[RUNNER RUN] Webhook-timeout tree-kill failed for PID ${pid}:`, error); + } + } + if (!treeDead && isProcessAlive(pid)) { + try { + treeDead = await killProcessTreeByPid(pid); + } catch (error) { + logger.debug(`[RUNNER RUN] Webhook-timeout PID tree-kill failed for ${pid}:`, error); + } + } + + if (!isProcessAlive(pid)) { + if (trackedSession.requestedHappySessionId) { + rememberVerifiedExit(trackedSession.requestedHappySessionId); + } + rememberVerifiedExit(`PID-${pid}`); + pidToRequestedSessionId.delete(pid); + pidToConfirmedSessionId.delete(pid); + webhookTimeoutOrphanPids.delete(pid); + if (persistedResumeProcesses.delete(pid)) persistResumeProcesses(); + releaseRecoveredSpawnDedupe(pid, existingSessionIdByChildPid, spawnSession); + } + + await cleanupCopiedCodexConfig('webhook-timeout'); + + // If this was a worktree session, the worktree can only be + // safely removed after the child has actually exited. + if (worktreeInfo && happyProcess) { + happyProcess.once('exit', () => { + void cleanupWorktree(); + }); + if (!isProcessAlive(pid)) { + void cleanupWorktree(); + } + } + + logger.debug(`[RUNNER RUN] Session webhook timeout for PID ${pid}`); + logStderrTail(); + resolve({ + type: 'error', + errorMessage: buildWebhookFailureMessage('timeout') }); - } else { - void cleanupCopiedCodexConfig('webhook-timeout'); - } - - // If this was a worktree session, the worktree can only be - // safely removed after the child has actually exited (the - // child may still be writing to it). Register a one-shot - // exit listener so cleanup happens once the tree-kill lands. - if (worktreeInfo && happyProcess) { - happyProcess.once('exit', () => { - void cleanupWorktree(); - }); - } - - logger.debug(`[RUNNER RUN] Session webhook timeout for PID ${pid}`); - logStderrTail(); - resolve({ - type: 'error', - errorMessage: buildWebhookFailureMessage('timeout') - }); + })(); }, webhookTimeoutMs); // Register awaiter @@ -986,9 +1088,95 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): } // Stop a session by sessionId or PID fallback - const stopSession = async (sessionId: string): Promise<'stopped' | 'already_gone' | 'still_alive'> => { + const stopSession = async ( + sessionId: string, + opts?: { processStartMarker?: string } + ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { logger.debug(`[RUNNER RUN] Attempting to stop session ${sessionId}`); + // After a mapped/persisted PID path succeeds, still scan argv for other + // generations of the same HAPI id (untracked orphans from an earlier + // runner) before reporting stopped/already_gone (#1910). Skip only PIDs + // that still host active shared siblings — never skip the whole scan. + // Protect tracked wrappers even when the durable runtime registry is + // missing/unreadable (argv would otherwise match the primary session id). + const shouldSkipOrphanPid = ( + liveRuntimes: Parameters[0], + protectedTrackedPids: Set, + id: string, + pid: number + ): boolean => ( + protectedTrackedPids.has(pid) + || wrapperHasActiveSiblingRoots(liveRuntimes, id, pid) + ); + + // Strict registry read for sibling protection — soft [] after parse/readdir + // failure would tree-kill a shared wrapper hosting live roots (#1911 Opus). + // Fail-closed only for Codex stop contexts; other flavors must not become + // permanently un-archivable on a single corrupt runtime JSON (#1911 Major). + const isCodexStopContext = (): boolean => { + for (const [, session] of pidToTrackedSession) { + if (session.sharedSessions?.[sessionId]) return true + } + return false + } + + const readLiveRuntimesForStop = async () => { + try { + return (await readRuntimes({ strict: true })).filter(runtime => + runtime.hub === configuration.apiUrl + && runtime.authHash === runtimeAuthHash() + && runtimeMayBeAlive(runtime) + ); + } catch (error) { + logger.warn( + `[RUNNER RUN] Codex runtime registry unreadable during stop of ${sessionId}: ${ + error instanceof Error ? error.message : String(error) + }` + ); + // KillSession PID-* fallback cannot prove the OS pid is not a shared + // Codex wrapper when the registry is unreadable — soft [] would + // tree-kill sibling roots (#1911 Overseer B2). + if (sessionId.startsWith('PID-')) return null; + // findRuntime also soft-fails; if a shared Codex root may still exist, + // refuse the orphan sweep. Non-Codex stops proceed with [] so archive + // is not machine-wide blocked by schema drift. + try { + const { findRuntime } = await import('@/codex/shared/registry'); + if (await findRuntime(sessionId) || isCodexStopContext()) return null; + } catch { + if (isCodexStopContext()) return null; + } + return []; + } + }; + + const finishWithOrphanSweep = async ( + base: 'stopped' | 'already_gone' | 'unknown' + ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { + const liveRuntimes = await readLiveRuntimesForStop(); + if (liveRuntimes === null) return 'still_alive'; + const protectedTrackedPids = trackedSharedWrapperPidsWithSiblings( + pidToTrackedSession.entries(), + sessionId + ); + const orphanStatus = await reapRunnerSpawnedOrphans(sessionId, { + findTargets: (id) => findStopSessionOrphanTargets( + id, + (sid, pid) => shouldSkipOrphanPid(liveRuntimes, protectedTrackedPids, sid, pid) + ), + }); + if (orphanStatus === 'still_alive') { + logger.debug(`[RUNNER RUN] Orphan argv sweep left live PIDs for session ${sessionId}`); + return 'still_alive'; + } + if (orphanStatus === 'stopped') { + rememberVerifiedExit(sessionId); + return 'stopped'; + } + return base; + }; + const { findRuntime } = await import('@/codex/shared/registry'); const sharedRuntime = await findRuntime(sessionId); if (sharedRuntime) { @@ -996,24 +1184,174 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const { runtimeControl } = await import('@/codex/shared/frontend'); await runtimeControl(sharedRuntime, 'hapi/stopSession', sessionId); const tracked = pidToTrackedSession.get(sharedRuntime.pid); - if (tracked?.sharedSessions) delete tracked.sharedSessions[sessionId]; - return 'stopped'; + if (tracked) { + const detach = detachSharedRootFromWrapper(tracked, sessionId); + if (detach.kind === 'keep_wrapper' || keepWrapperForSharedSiblings(tracked, sessionId)) { + // App-server ended this root; sibling roots still need the wrapper. + // Still argv-sweep other generations; PID filter skips this wrapper. + logger.debug( + `[RUNNER RUN] Shared runtime stopped root ${sessionId}; wrapper PID ${sharedRuntime.pid} kept` + ); + return await finishWithOrphanSweep('stopped'); + } + } + // Post-restart: TrackedSession may be gone; registry still lists siblings. + const liveAfterStop = await readLiveRuntimesForStop(); + if (liveAfterStop === null) return 'still_alive'; + if (wrapperHasActiveSiblingRoots(liveAfterStop, sessionId, sharedRuntime.pid)) { + logger.debug( + `[RUNNER RUN] Shared runtime stopped root ${sessionId}; registry siblings keep PID ${sharedRuntime.pid}` + ); + return await finishWithOrphanSweep('stopped'); + } + return await finishWithOrphanSweep('stopped'); } catch { return 'still_alive'; } } - if ((await readRuntimes()).some(runtime => runtime.hub === configuration.apiUrl && runtime.authHash === runtimeAuthHash() - && runtime.sessions[sessionId]?.active && runtimeMayBeAlive(runtime))) return 'still_alive'; - // Missing registry is not permission to kill siblings in a live execution. - if ([...pidToTrackedSession.values()].some(session => session.sharedSessions?.[sessionId])) return 'still_alive'; + { + const probeRuntimes = await readLiveRuntimesForStop(); + if (probeRuntimes === null) return 'still_alive'; + if (probeRuntimes.some(runtime => runtime.sessions[sessionId]?.active)) return 'still_alive'; + } - // Try to find by sessionId first + // Live Codex runtimes for this hub — used when in-memory sharedSessions + // only knows the root being archived (post-restart adoption of a new root + // while older roots remain active only in the durable registry). + const liveRegistryRuntimes = async () => readLiveRuntimesForStop(); + const registrySiblingsKeepPid = async (pid: number): Promise => { + const live = await liveRegistryRuntimes(); + if (live === null) return 'unreadable'; + return wrapperHasActiveSiblingRoots(live, sessionId, pid); + }; + + // KillSession pid fallback must verify the start marker BEFORE any tracked + // PID match can tree-kill a reused OS pid. + if (sessionId.startsWith('PID-')) { + const pid = parseInt(sessionId.slice(4), 10); + if (Number.isFinite(pid) && pid > 0) { + const liveForPid = await liveRegistryRuntimes(); + if (liveForPid === null) return 'still_alive'; + const decision = decideRawPidStop({ + alive: isProcessAlive(pid), + expectedMarker: opts?.processStartMarker, + currentMarker: getProcessStartMarker(pid), + hasActiveSharedRoots: pidHasActiveSharedRoots(liveForPid, pid), + }); + if (decision === 'already_gone') { + rememberVerifiedExit(sessionId); + return 'already_gone'; + } + if (decision === 'unknown') { + logger.debug( + `[RUNNER RUN] Raw PID ${pid} stop unconfirmed (missing/mismatched start marker or probe failed)` + ); + return 'unknown'; + } + if (decision === 'keep_shared') { + logger.debug( + `[RUNNER RUN] PID ${pid} still hosts active shared roots; not tree-killing` + ); + return await finishWithOrphanSweep('stopped'); + } + if (!(await killProcessTreeByPid(pid))) return 'still_alive'; + rememberVerifiedExit(sessionId); + return await finishWithOrphanSweep('stopped'); + } + return 'unknown'; + } + + // After KillSession, findRuntime may miss an inactive binding. Detach the + // root from sharedSessions without tree-killing siblings. An inactive + // registry binding is stop evidence (Codex KillSession already archived + // the root); absent evidence stays unknown across retries. + const finishKeepWrapperDetach = async (pid: number): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> => { + const live = await liveRegistryRuntimes(); + if (live === null) return 'still_alive'; + const binding = sessionRegistryBindingState(live, sessionId, pid); + if (binding === 'active') return 'still_alive'; + // Base unknown so an argv orphan reap returning stopped is distinguishable + // from "no orphans" (which would otherwise echo a stopped base). + const orphan = await finishWithOrphanSweep('unknown'); + if (orphan === 'still_alive') return 'still_alive'; + if (orphan === 'stopped') return 'stopped'; + const decision = decideKeepWrapperArchive(binding); + if (decision === 'stopped') { + logger.debug( + `[RUNNER RUN] Detached shared root ${sessionId}; inactive registry binding confirms stop; PID ${pid} kept` + ); + } else { + logger.debug( + `[RUNNER RUN] Detached shared root ${sessionId} from PID ${pid}; stop unconfirmed without registry evidence` + ); + } + return decision; + }; + + for (const [pid, session] of pidToTrackedSession.entries()) { + if (!session.sharedSessions?.[sessionId]) continue; + if (detachSharedRootFromWrapper(session, sessionId).kind === 'keep_wrapper') { + return await finishKeepWrapperDetach(pid); + } + // In-memory map had only this root (typical after restart adoption of a + // newly reported root). Registry may still list older active siblings. + if (await registrySiblingsKeepPid(pid) !== false) { + return await finishKeepWrapperDetach(pid); + } + // Last shared entry removed — fall through so the wrapper can be stopped. + break; + } + + // Try to find by sessionId first (never match raw PID- here — handled above). for (const [pid, session] of pidToTrackedSession.entries()) { if (session.happySessionId === sessionId || - session.requestedHappySessionId === sessionId || - (sessionId.startsWith('PID-') && pid === parseInt(sessionId.replace('PID-', '')))) { + session.requestedHappySessionId === sessionId) { - if (session.startedBy === 'runner' && session.childProcess) { + // Primary match, but live shared siblings still use this wrapper + // (KillSession may already have cleared this id from sharedSessions). + if (keepWrapperForSharedSiblings(session, sessionId)) { + return await finishKeepWrapperDetach(pid); + } + + // Post-restart: TrackedSession may only list the newly reported root + // while older roots remain active in the durable registry on this PID. + // Archiving the new root must not tree-kill those siblings. + if (await registrySiblingsKeepPid(pid) !== false) { + detachSharedRootFromWrapper(session, sessionId); + return await finishKeepWrapperDetach(pid); + } + + if (session.startedBy === 'runner') { + // Adopted post-restart sessions have no ChildProcess handle — still + // tree-kill so agent grandchildren cannot outlive the wrapper. + // Require a persisted start marker; without it (or on mismatch), do + // not kill by tracked PID — fall through to argv discovery. + if (!session.childProcess) { + const persisted = persistedResumeProcesses.get(pid); + if (!persisted?.processStartMarker) { + logger.debug( + `[RUNNER RUN] Adopted PID ${pid} has no start marker; refusing tracked kill for ${sessionId}` + ); + const orphan = await finishWithOrphanSweep('unknown'); + if (orphan === 'still_alive') return 'still_alive'; + if (orphan === 'stopped') return 'stopped'; + return 'unknown'; + } + const currentMarker = getProcessStartMarker(pid); + if (currentMarker === null || currentMarker !== persisted.processStartMarker) { + logger.debug( + `[RUNNER RUN] Adopted PID ${pid} generation mismatch; dropping stale tracking for ${sessionId}` + ); + pidToTrackedSession.delete(pid); + pidToRequestedSessionId.delete(pid); + pidToConfirmedSessionId.delete(pid); + if (persistedResumeProcesses.delete(pid)) persistResumeProcesses(); + releaseRecoveredSpawnDedupe(pid, existingSessionIdByChildPid, spawnSession); + continue; + } + } try { - const treeStopped = await killProcessByChildProcess(session.childProcess); + const treeStopped = session.childProcess + ? await killProcessByChildProcess(session.childProcess) + : await killProcessTreeByPid(pid); if (!treeStopped) { logger.debug(`[RUNNER RUN] Process tree for session ${sessionId} is still alive after stop request`); return 'still_alive'; @@ -1056,7 +1394,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pidToConfirmedSessionId.delete(pid); if (persistedResumeProcesses.delete(pid)) persistResumeProcesses(); logger.debug(`[RUNNER RUN] Removed terminated session ${sessionId} from tracking`); - return 'stopped'; + return await finishWithOrphanSweep('stopped'); } } @@ -1078,14 +1416,32 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): const currentMarker = getProcessStartMarker(pid); if (currentMarker === null) return 'still_alive'; if (currentMarker !== persisted.processStartMarker) { + // PID reuse: drop the stale mapping, but do NOT claim already_gone + // or write a verified-exit tombstone — the HAPI CLI for this session + // may still be alive under a different PID (#1910). Continue so + // other fallback PIDs / argv orphan scan can still reap it. persistedResumeProcesses.delete(pid); persistResumeProcesses(); pidToRequestedSessionId.delete(pid); pidToConfirmedSessionId.delete(pid); - if (requestedSessionId) rememberVerifiedExit(requestedSessionId); - if (confirmedSessionId) rememberVerifiedExit(confirmedSessionId); releaseRecoveredSpawnDedupe(pid, existingSessionIdByChildPid, spawnSession); - return 'already_gone'; + continue; + } + const liveForPid = await liveRegistryRuntimes(); + if (liveForPid === null) return 'still_alive'; + if (wrapperHasActiveSiblingRoots(liveForPid, sessionId, pid)) { + // Keep this shared wrapper; siblings alone are not stop proof for + // this root — require an inactive registry binding (KillSession ack). + const binding = sessionRegistryBindingState(liveForPid, sessionId, pid); + if (binding === 'active') return 'still_alive'; + const orphan = await finishWithOrphanSweep('unknown'); + if (orphan === 'still_alive') return 'still_alive'; + if (orphan === 'stopped') return 'stopped'; + const decision = decideKeepWrapperArchive(binding); + logger.debug( + `[RUNNER RUN] Persisted PID ${pid} hosts active shared siblings for ${sessionId}; archive=${decision}` + ); + return decision; } if (!(await killProcessTreeByPid(pid))) return 'still_alive'; if (requestedSessionId) rememberVerifiedExit(requestedSessionId); @@ -1095,7 +1451,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pidToConfirmedSessionId.delete(pid); if (persistedResumeProcesses.delete(pid)) persistResumeProcesses(); releaseRecoveredSpawnDedupe(pid, existingSessionIdByChildPid, spawnSession); - return 'stopped'; + return await finishWithOrphanSweep('stopped'); } if (requestedSessionId) rememberVerifiedExit(requestedSessionId); if (confirmedSessionId) rememberVerifiedExit(confirmedSessionId); @@ -1104,15 +1460,61 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pidToConfirmedSessionId.delete(pid); if (persistedResumeProcesses.delete(pid)) persistResumeProcesses(); releaseRecoveredSpawnDedupe(pid, existingSessionIdByChildPid, spawnSession); - return 'already_gone'; + return await finishWithOrphanSweep('already_gone'); + } + + // Maps missed (or marker-mismatch cleared a stale row). Scan live argv for + // `--started-by runner` + this HAPI session id and tree-kill matches — + // excluding PIDs that still host active shared sibling roots (registry + // and/or in-memory tracked wrappers). + { + const liveRuntimes = await readLiveRuntimesForStop(); + if (liveRuntimes === null) return 'still_alive'; + const protectedTrackedPids = trackedSharedWrapperPidsWithSiblings( + pidToTrackedSession.entries(), + sessionId + ); + const orphanStatus = await reapRunnerSpawnedOrphans(sessionId, { + findTargets: (id) => findStopSessionOrphanTargets( + id, + (sid, pid) => shouldSkipOrphanPid(liveRuntimes, protectedTrackedPids, sid, pid) + ), + }); + if (orphanStatus === 'still_alive') { + logger.debug(`[RUNNER RUN] Orphan argv reap still_alive for session ${sessionId} (scan_failed or kill left live PIDs)`); + return 'still_alive'; + } + if (orphanStatus === 'stopped') { + rememberVerifiedExit(sessionId); + logger.debug(`[RUNNER RUN] Reaped argv-orphan PID(s) for session ${sessionId}`); + return 'stopped'; + } + // No killable orphans: siblings may protect the wrapper, but that is + // not proof this root ended. Only an inactive registry binding (Codex + // KillSession ack) may claim stopped; otherwise stay unknown on retry. + if (sessionRuntimeHasActiveSiblings(liveRuntimes, sessionId) || protectedTrackedPids.size > 0) { + const binding = sessionRegistryBindingState(liveRuntimes, sessionId); + const decision = decideKeepWrapperArchive(binding); + logger.debug( + `[RUNNER RUN] Session ${sessionId}; shared siblings remain; archive=${decision}` + ); + return decision === 'still_alive' ? 'still_alive' : decision; + } } if (hasVerifiedExit(sessionId)) { logger.debug(`[RUNNER RUN] Session ${sessionId} was previously observed exited`); return 'already_gone'; } + + // PID- targets are handled before tracked/persisted matches above so a + // reused OS pid cannot be tree-killed via happySessionId coincidence. + + // No PID matched and no verified-exit tombstone — distinct from + // still_alive so callers reconciling stale rows are not blocked forever, + // while callers that just spawned this id can treat unknown defensively. logger.debug(`[RUNNER RUN] Session ${sessionId} not found without verified exit`); - return 'still_alive'; + return 'unknown'; }; // Handle child process exit @@ -1135,6 +1537,7 @@ export async function startRunner(options: { workspaceRoots?: string[] } = {}): pidToErrorAwaiter.delete(pid); pidToRequestedSessionId.delete(pid); pidToConfirmedSessionId.delete(pid); + webhookTimeoutOrphanPids.delete(pid); if (persistedResumeProcesses.delete(pid)) persistResumeProcesses(); }; @@ -1598,24 +2001,19 @@ export function buildCliArgs( // Codex shares one engine; Runner owns the wrapper, not a remote mode. if (agent !== 'codex') args.push('--hapi-starting-mode', startingMode); args.push('--started-by', 'runner'); - // Codex, Cursor ACP, OpenCode, Pi native resume, and Claude message-level - // forks reuse the original HAPI row via --existing-session-id. - if (agent === 'codex' || agent === 'cursor' || agent === 'pi' - || agent === 'opencode' - || agent === 'agy' - || agent === 'dsh' - || (agentCommand === 'claude' && options.forkSession)) { - const existingSessionId = options.existingSessionId ?? options.sessionId; - if (existingSessionId) { - args.push('--existing-session-id', existingSessionId); - } - } - // Grok fork children also bind the pending HAPI session id. - if (agent === 'grok') { - const existingSessionId = options.existingSessionId ?? options.sessionId; - if (existingSessionId && !args.includes('--existing-session-id')) { - args.push('--existing-session-id', existingSessionId); - } + // Stamp the HAPI row id on argv for orphan reap after tracking loss (#1910). + // Adopt-stub (`--hapi-session-id`) vs reopen (`--existing-session-id`) are + // different operations — never collapse them (#1911 Opus Critical + Codex Major). + // Local HTTP non-UUID sessionId stays on --hapi-session-id (reap-only; create + // ignores non-UUID reserved ids). A UUID sessionId must NOT stamp adopt — that + // would 404/409 against a non-stub row (#1911 Opus Major @ 09141964c). + const hubUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + if (options.existingSessionId) { + args.push('--existing-session-id', options.existingSessionId); + } else if (options.reservedSessionId) { + args.push('--hapi-session-id', options.reservedSessionId); + } else if (options.sessionId && !hubUuid.test(options.sessionId)) { + args.push('--hapi-session-id', options.sessionId); } if (options.model) { args.push('--model', options.model); diff --git a/cli/src/runner/runner.integration.test.ts b/cli/src/runner/runner.integration.test.ts index d24aaed7..d0944316 100644 --- a/cli/src/runner/runner.integration.test.ts +++ b/cli/src/runner/runner.integration.test.ts @@ -230,7 +230,10 @@ describe.skipIf(!await isServerHealthy())('Runner Integration Tests', { timeout: expect(spawnedSession.happySessionId).toBeDefined(); expect(await stopRunnerSession(spawnedSession.happySessionId)).toBe('stopped'); expect(await stopRunnerSession(spawnedSession.happySessionId)).toBe('already_gone'); - expect(await stopRunnerSession('unknown-session-id')).toBe('still_alive'); + // Distinct from 'still_alive': no PID matched this id and there is no + // verified-exit tombstone (and argv orphan scan found nothing), so the + // runner has no basis to call it either alive or dead. + expect(await stopRunnerSession('unknown-session-id')).toBe('unknown'); }); it.skipIf(process.env.HAPI_RUN_STRESS_TESTS !== 'true')( diff --git a/cli/src/runner/sharedSessionStop.test.ts b/cli/src/runner/sharedSessionStop.test.ts new file mode 100644 index 00000000..5530403e --- /dev/null +++ b/cli/src/runner/sharedSessionStop.test.ts @@ -0,0 +1,243 @@ +import { describe, expect, it } from 'vitest' +import { + decideKeepWrapperArchive, + decideRawPidStop, + detachSharedRootFromWrapper, + keepWrapperForSharedSiblings, + pidHasActiveSharedRoots, + sessionRegistryBindingState, + sessionRuntimeHasActiveSiblings, + trackedSharedWrapperPidsWithSiblings, + wrapperHasActiveSiblingRoots, +} from './sharedSessionStop' + +describe('detachSharedRootFromWrapper', () => { + it('keeps the wrapper when sibling shared roots remain', () => { + const session = { + happySessionId: 'root-a', + sharedSessions: { + 'root-a': {}, + 'root-b': {}, + }, + } + expect(detachSharedRootFromWrapper(session, 'root-a')).toEqual({ kind: 'keep_wrapper' }) + expect(session.sharedSessions).toEqual({ 'root-b': {} }) + }) + + it('keeps the wrapper when primary is a different live root', () => { + const session = { + happySessionId: 'root-primary', + sharedSessions: { + 'root-archived': {}, + }, + } + expect(detachSharedRootFromWrapper(session, 'root-archived')).toEqual({ kind: 'keep_wrapper' }) + expect(session.sharedSessions).toBeUndefined() + }) + + it('allows kill when the last shared root is the primary being stopped', () => { + const session = { + happySessionId: 'root-only', + sharedSessions: { + 'root-only': {}, + }, + } + expect(detachSharedRootFromWrapper(session, 'root-only')).toEqual({ kind: 'allow_kill' }) + expect(session.sharedSessions).toBeUndefined() + }) + + it('allows kill when session id is not in sharedSessions', () => { + const session = { + happySessionId: 'root-a', + sharedSessions: { 'root-b': {} }, + } + expect(detachSharedRootFromWrapper(session, 'root-missing')).toEqual({ kind: 'allow_kill' }) + expect(session.sharedSessions).toEqual({ 'root-b': {} }) + }) +}) + +describe('keepWrapperForSharedSiblings', () => { + it('returns true and drops the archived root when siblings remain', () => { + const session = { + sharedSessions: { + 'root-a': {}, + 'root-b': {}, + }, + } + expect(keepWrapperForSharedSiblings(session, 'root-a')).toBe(true) + expect(session.sharedSessions).toEqual({ 'root-b': {} }) + }) + + it('returns false when no siblings remain', () => { + const session = { + sharedSessions: { 'root-a': {} }, + } + expect(keepWrapperForSharedSiblings(session, 'root-a')).toBe(false) + expect(session.sharedSessions).toEqual({ 'root-a': {} }) + }) +}) + +describe('runtime registry sibling guards (post-restart)', () => { + const runtimes = [ + { + pid: 4242, + sessions: { + 'root-a': { active: false }, + 'root-b': { active: true }, + }, + }, + ] + + it('keeps the wrapper when archiving the original root after tracking loss', () => { + // KillSession / stopSession already marked root-a inactive; TrackedSession + // is gone after runner restart — persisted-PID and argv paths must not kill. + expect(sessionRuntimeHasActiveSiblings(runtimes, 'root-a')).toBe(true) + expect(wrapperHasActiveSiblingRoots(runtimes, 'root-a', 4242)).toBe(true) + }) + + it('allows kill when no other root is active on the wrapper', () => { + const lastRoot = [ + { + pid: 4242, + sessions: { + 'root-a': { active: false }, + 'root-b': { active: false }, + }, + }, + ] + expect(sessionRuntimeHasActiveSiblings(lastRoot, 'root-a')).toBe(false) + expect(wrapperHasActiveSiblingRoots(lastRoot, 'root-a', 4242)).toBe(false) + }) + + it('ignores unrelated wrapper PIDs', () => { + expect(wrapperHasActiveSiblingRoots(runtimes, 'root-a', 9999)).toBe(false) + }) + + it('PID-filters shared wrappers while leaving other orphan PIDs killable', () => { + // Older untracked CLI (9999) and current shared wrapper (4242) both + // match the same HAPI session id. Session-wide sibling presence must + // not skip the argv scan — only the wrapper PID is excluded. + const orphanPids = [4242, 9999] + const filtered = orphanPids.filter( + (pid) => !wrapperHasActiveSiblingRoots(runtimes, 'root-a', pid) + ) + expect(filtered).toEqual([9999]) + expect(sessionRuntimeHasActiveSiblings(runtimes, 'root-a')).toBe(true) + }) + + it('protects tracked shared wrappers when the runtime registry is empty', () => { + const tracked = new Map([ + [4242, { + happySessionId: 'root-a', + sharedSessions: { + 'root-a': {}, + 'root-b': {}, + }, + }], + ]) + const protectedPids = trackedSharedWrapperPidsWithSiblings(tracked.entries(), 'root-a') + expect([...protectedPids]).toEqual([4242]) + + // Registry unavailable: empty runtimes must not leave the tracked wrapper killable. + const orphanPids = [4242, 9999] + const filtered = orphanPids.filter((pid) => ( + !protectedPids.has(pid) + && !wrapperHasActiveSiblingRoots([], 'root-a', pid) + )) + expect(filtered).toEqual([9999]) + }) + + it('keeps recovered shared wrapper when only the new root is tracked (restart + webhook + archive)', () => { + // Runner restart wiped TrackedSession. A later /new webhook adopts only + // the newly reported root onto the live shared Codex PID. Older roots + // remain active solely in the durable registry. Archiving the new root + // must not fall through to killProcess on that PID. + const tracked = { + happySessionId: 'new-root', + sharedSessions: { + 'new-root': {}, + }, + } + const runtimesAfterArchive = [ + { + pid: 4242, + sessions: { + 'old-root': { active: true }, + 'new-root': { active: false }, + }, + }, + ] + + // Solo in-memory entry (adoption of the new root only) does not protect the PID: + expect(trackedSharedWrapperPidsWithSiblings( + new Map([[4242, { ...tracked, sharedSessions: { ...tracked.sharedSessions } }]]).entries(), + 'new-root' + ).size).toBe(0) + + // Detach + keepWrapper in-memory path alone would allow killing the wrapper: + expect(detachSharedRootFromWrapper(tracked, 'new-root')).toEqual({ kind: 'allow_kill' }) + expect(keepWrapperForSharedSiblings(tracked, 'new-root')).toBe(false) + + // Registry siblings on the same PID must keep the wrapper alive: + expect(wrapperHasActiveSiblingRoots(runtimesAfterArchive, 'new-root', 4242)).toBe(true) + expect(sessionRuntimeHasActiveSiblings(runtimesAfterArchive, 'new-root')).toBe(true) + expect(pidHasActiveSharedRoots(runtimesAfterArchive, 4242)).toBe(true) + }) + + it('refuses raw PID kill when the start marker is missing or mismatched', () => { + expect(decideRawPidStop({ + alive: true, + expectedMarker: undefined, + currentMarker: 'gen-a', + hasActiveSharedRoots: false, + })).toBe('unknown') + expect(decideRawPidStop({ + alive: true, + expectedMarker: 'gen-a', + currentMarker: 'gen-b', + hasActiveSharedRoots: false, + })).toBe('unknown') + expect(decideRawPidStop({ + alive: true, + expectedMarker: 'gen-a', + currentMarker: 'gen-a', + hasActiveSharedRoots: false, + })).toBe('allow_kill') + expect(decideRawPidStop({ + alive: false, + expectedMarker: 'gen-a', + currentMarker: null, + hasActiveSharedRoots: false, + })).toBe('already_gone') + }) + + it('treats inactive registry binding as stop proof while siblings keep the wrapper', () => { + expect(sessionRegistryBindingState(runtimes, 'root-a', 4242)).toBe('inactive') + expect(sessionRegistryBindingState(runtimes, 'root-b', 4242)).toBe('active') + expect(sessionRegistryBindingState(runtimes, 'missing', 4242)).toBe('absent') + expect(decideKeepWrapperArchive('inactive')).toBe('stopped') + expect(decideKeepWrapperArchive('active')).toBe('still_alive') + expect(decideKeepWrapperArchive('absent')).toBe('unknown') + }) + + it('does not claim stopped from siblings alone on retry (no binding evidence)', () => { + // First StopSession detached in-memory tracking and returned unknown. + // Retry: argv scan skips the sibling-protected wrapper; without an + // inactive registry row we must stay unknown — not archive the live root. + const siblingsOnly = [ + { + pid: 4242, + sessions: { + // Target never made it into the durable registry (or was + // never written). Sibling is still active. + 'root-sibling': { active: true }, + }, + }, + ] + expect(wrapperHasActiveSiblingRoots(siblingsOnly, 'root-unconfirmed', 4242)).toBe(true) + expect(sessionRegistryBindingState(siblingsOnly, 'root-unconfirmed')).toBe('absent') + expect(decideKeepWrapperArchive( + sessionRegistryBindingState(siblingsOnly, 'root-unconfirmed') + )).toBe('unknown') + }) +}) diff --git a/cli/src/runner/sharedSessionStop.ts b/cli/src/runner/sharedSessionStop.ts new file mode 100644 index 00000000..4311ac88 --- /dev/null +++ b/cli/src/runner/sharedSessionStop.ts @@ -0,0 +1,207 @@ +/** + * Shared Codex executions host multiple HAPI roots in one wrapper PID. + * Archiving one root must detach that root without tree-killing the wrapper + * while sibling roots (or a different primary) still use it. + */ + +export type SharedStopDecision = + | { kind: 'keep_wrapper' } + | { kind: 'allow_kill' } + +/** Minimal runtime shape used when TrackedSession was lost (e.g. runner restart). */ +export type RuntimeSiblingSnapshot = { + pid: number + sessions: Record +} + +/** + * True when any root on this wrapper PID is still active in the durable + * registry. Used when StopSession is asked to confirm a raw OS pid (PID-N) + * from KillSession — tree-killing would end sibling shared Codex roots. + */ +export function pidHasActiveSharedRoots( + runtimes: RuntimeSiblingSnapshot[], + wrapperPid: number +): boolean { + for (const runtime of runtimes) { + if (runtime.pid !== wrapperPid) continue + return Object.values(runtime.sessions).some((binding) => binding.active) + } + return false +} + +/** + * Decide whether a KillSession-reported OS pid may be tree-killed. + * Requires a matching process-start marker so PID reuse cannot nuke a stranger. + */ +export type RawPidStopDecision = + | 'already_gone' + | 'unknown' + | 'keep_shared' + | 'allow_kill' + +export function decideRawPidStop(opts: { + alive: boolean + expectedMarker?: string + currentMarker: string | null + hasActiveSharedRoots: boolean +}): RawPidStopDecision { + if (!opts.alive) return 'already_gone' + if (!opts.expectedMarker) return 'unknown' + if (opts.currentMarker === null || opts.currentMarker !== opts.expectedMarker) { + return 'unknown' + } + if (opts.hasActiveSharedRoots) return 'keep_shared' + return 'allow_kill' +} + +/** + * Registry evidence for a shared root: Codex KillSession marks the binding + * inactive before replying. findRuntime only returns active rows, so StopSession + * must read this directly when deciding whether siblings-alone may claim stopped. + */ +export type RegistryBindingState = 'active' | 'inactive' | 'absent' + +export function sessionRegistryBindingState( + runtimes: RuntimeSiblingSnapshot[], + sessionId: string, + wrapperPid?: number +): RegistryBindingState { + for (const runtime of runtimes) { + if (wrapperPid !== undefined && runtime.pid !== wrapperPid) continue + const binding = runtime.sessions[sessionId] + if (!binding) continue + return binding.active ? 'active' : 'inactive' + } + return 'absent' +} + +/** + * After detaching a shared root while keeping the wrapper for siblings: + * inactive binding = acknowledged archive; absent = unconfirmed (unknown); + * active = still running. + */ +export function decideKeepWrapperArchive( + binding: RegistryBindingState +): 'stopped' | 'still_alive' | 'unknown' { + if (binding === 'active') return 'still_alive' + if (binding === 'inactive') return 'stopped' + return 'unknown' +} + +/** + * True when another root on the same wrapper PID is still active in the + * durable Codex runtime registry — even if this session's binding is inactive + * and the runner has no in-memory TrackedSession. + */ +export function wrapperHasActiveSiblingRoots( + runtimes: RuntimeSiblingSnapshot[], + sessionId: string, + wrapperPid: number +): boolean { + for (const runtime of runtimes) { + if (runtime.pid !== wrapperPid) continue + return Object.entries(runtime.sessions).some( + ([id, binding]) => id !== sessionId && binding.active + ) + } + return false +} + +/** + * True when any runtime that still lists `sessionId` (active or not) has at + * least one other active root. Used before persisted-PID / argv kills after + * KillSession marked the archived root inactive. + */ +export function sessionRuntimeHasActiveSiblings( + runtimes: RuntimeSiblingSnapshot[], + sessionId: string +): boolean { + for (const runtime of runtimes) { + if (!(sessionId in runtime.sessions)) continue + if (Object.entries(runtime.sessions).some( + ([id, binding]) => id !== sessionId && binding.active + )) { + return true + } + } + return false +} + +/** + * PIDs from in-memory runner tracking that still host other shared roots for + * this session id. Used when the durable runtime registry is missing/unreadable + * so argv orphan sweeps do not tree-kill a live shared wrapper. + */ +export function trackedSharedWrapperPidsWithSiblings( + tracked: Iterable<[number, { + happySessionId?: string + sharedSessions?: Record + }]>, + sessionId: string +): Set { + const protectedPids = new Set() + for (const [pid, session] of tracked) { + const shared = session.sharedSessions + if (!shared) continue + const otherShared = Object.keys(shared).filter((id) => id !== sessionId) + if (otherShared.length > 0) { + protectedPids.add(pid) + continue + } + // Target may already have been detached from sharedSessions while the + // primary happySessionId is a different live root on this wrapper. + if (typeof session.happySessionId === 'string' + && session.happySessionId !== sessionId) { + protectedPids.add(pid) + } + } + return protectedPids +} + +/** + * Mutates `sharedSessions` to drop `sessionId`. Returns whether the wrapper + * PID must stay alive for remaining roots. + */ +export function detachSharedRootFromWrapper( + session: { + happySessionId?: string + sharedSessions?: Record + }, + sessionId: string +): SharedStopDecision { + const shared = session.sharedSessions + if (!shared || !Object.prototype.hasOwnProperty.call(shared, sessionId)) { + return { kind: 'allow_kill' } + } + + delete shared[sessionId] + const remainingShared = Object.keys(shared) + if (remainingShared.length === 0) { + delete session.sharedSessions + } + + const primaryIsOther = typeof session.happySessionId === 'string' + && session.happySessionId !== sessionId + if (remainingShared.length > 0 || primaryIsOther) { + return { kind: 'keep_wrapper' } + } + return { kind: 'allow_kill' } +} + +/** + * When stop matched the primary `happySessionId`, keep the wrapper if other + * shared roots are still registered on this PID. + */ +export function keepWrapperForSharedSiblings( + session: { + sharedSessions?: Record + }, + sessionId: string +): boolean { + const siblings = Object.keys(session.sharedSessions ?? {}) + .filter((id) => id !== sessionId) + if (siblings.length === 0) return false + delete session.sharedSessions?.[sessionId] + return true +} diff --git a/cli/src/utils/process.test.ts b/cli/src/utils/process.test.ts index 52ae0d48..5e2f6f9a 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 } from './process' +import { getHapiRunnerProcessIdentity, killProcess } from './process' const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform') @@ -50,6 +50,11 @@ describe('getHapiRunnerProcessIdentity on Windows', () => { beforeEach(() => { setPlatform('win32') spawnSyncMock.mockReset() + // Prefer signal-0 probe in these identity tests: tasklist falls through. + spawnSyncMock.mockImplementation((cmd: string, ...rest: unknown[]) => { + if (cmd === 'tasklist') return unavailable('tasklist') + return completed('') + }) vi.spyOn(process, 'kill').mockReturnValue(true) }) @@ -64,77 +69,85 @@ describe('getHapiRunnerProcessIdentity on Windows', () => { }) it('reports a foreign process when CIM identifies it', () => { - spawnSyncMock.mockReturnValueOnce(completed('C:\\Windows\\System32\\conhost.exe')) + spawnSyncMock.mockImplementation((cmd: string, args?: string[]) => { + if (cmd === 'tasklist') return unavailable('tasklist') + if (cmd === 'powershell') return completed('C:\\Windows\\System32\\conhost.exe') + return completed('') + }) expect(getHapiRunnerProcessIdentity(8328)).toBe('foreign') - expect(spawnSyncMock).toHaveBeenCalledTimes(1) - expect(spawnSyncMock).toHaveBeenNthCalledWith( - 1, - 'powershell', - [ - '-NoProfile', - '-NonInteractive', - '-Command', - '(Get-CimInstance Win32_Process -Filter "ProcessId = 8328").CommandLine' - ], - { stdio: 'pipe', windowsHide: true } - ) + expect(spawnSyncMock.mock.calls.some((call) => call[0] === 'powershell')).toBe(true) }) it('reports the runner when CIM identifies it', () => { - spawnSyncMock.mockReturnValueOnce(completed('hapi-local.exe runner start-sync')) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return unavailable('tasklist') + if (cmd === 'powershell') return completed('hapi-local.exe runner start-sync') + return completed('') + }) expect(getHapiRunnerProcessIdentity(9124)).toBe('runner') }) it('falls back to WMIC when PowerShell is unavailable', () => { - spawnSyncMock - .mockReturnValueOnce(unavailable('powershell')) - .mockReturnValueOnce(completed('hapi-local.exe runner start-sync')) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return unavailable('tasklist') + if (cmd === 'powershell') return unavailable('powershell') + if (cmd === 'wmic') return completed('hapi-local.exe runner start-sync') + return completed('') + }) expect(getHapiRunnerProcessIdentity(9124)).toBe('runner') - expect(spawnSyncMock).toHaveBeenNthCalledWith( - 2, - 'wmic', - ['process', 'where', 'ProcessId=9124', 'get', 'CommandLine'], - { stdio: 'pipe', windowsHide: true } - ) + expect(spawnSyncMock.mock.calls.some((call) => call[0] === 'wmic')).toBe(true) }) it('falls back to WMIC when CIM reports no command line', () => { - spawnSyncMock - .mockReturnValueOnce(completed('')) - .mockReturnValueOnce(completed('CommandLine\r\nhapi-local.exe runner start-sync\r\n')) + let powershellCalls = 0 + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return unavailable('tasklist') + if (cmd === 'powershell') { + powershellCalls += 1 + return completed('') + } + if (cmd === 'wmic') return completed('CommandLine\r\nhapi-local.exe runner start-sync\r\n') + return completed('') + }) expect(getHapiRunnerProcessIdentity(9124)).toBe('runner') - expect(spawnSyncMock).toHaveBeenCalledTimes(2) + expect(spawnSyncMock.mock.calls.some((call) => call[0] === 'wmic')).toBe(true) }) it('reports unknown when WMIC prints only the column header', () => { - spawnSyncMock - .mockReturnValueOnce(completed('')) - .mockReturnValueOnce(completed('CommandLine\r\n\r\n')) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return unavailable('tasklist') + if (cmd === 'powershell') return completed('') + if (cmd === 'wmic') return completed('CommandLine\r\n\r\n') + return completed('') + }) expect(getHapiRunnerProcessIdentity(8328)).toBe('unknown') - expect(spawnSyncMock).toHaveBeenCalledTimes(2) }) it('falls back to WMIC when PowerShell exits non-zero', () => { - spawnSyncMock - .mockReturnValueOnce(completed('', 1)) - .mockReturnValueOnce(completed('hapi-local.exe runner start-sync')) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return unavailable('tasklist') + if (cmd === 'powershell') return completed('', 1) + if (cmd === 'wmic') return completed('hapi-local.exe runner start-sync') + return completed('') + }) expect(getHapiRunnerProcessIdentity(9124)).toBe('runner') - expect(spawnSyncMock).toHaveBeenCalledTimes(2) }) it('reports unknown when no probe reports a command line', () => { - spawnSyncMock - .mockReturnValueOnce(completed('')) - .mockReturnValueOnce(unavailable('wmic')) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return unavailable('tasklist') + if (cmd === 'powershell') return completed('') + if (cmd === 'wmic') return unavailable('wmic') + return completed('') + }) expect(getHapiRunnerProcessIdentity(8328)).toBe('unknown') - expect(spawnSyncMock).toHaveBeenCalledTimes(2) }) it('reports dead when the pid exits while the probes run', () => { @@ -143,9 +156,10 @@ describe('getHapiRunnerProcessIdentity on Windows', () => { .mockImplementationOnce(() => { throw new Error('ESRCH') }) - spawnSyncMock - .mockReturnValueOnce(unavailable('powershell')) - .mockReturnValueOnce(unavailable('wmic')) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return unavailable('tasklist') + return unavailable(cmd) + }) expect(getHapiRunnerProcessIdentity(8328)).toBe('dead') }) @@ -154,9 +168,514 @@ describe('getHapiRunnerProcessIdentity on Windows', () => { vi.spyOn(process, 'kill').mockImplementation(() => { throw new Error('ESRCH') }) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'tasklist') return unavailable('tasklist') + return completed('') + }) expect(getHapiRunnerProcessIdentity(8328)).toBe('dead') - expect(spawnSyncMock).not.toHaveBeenCalled() + expect(spawnSyncMock.mock.calls.every((call) => call[0] === 'tasklist')).toBe(true) + }) +}) + +describe('killProcess on Windows (orphanReap / stopSession)', () => { + beforeAll(() => { + if (!originalPlatformDescriptor?.configurable) { + throw new Error('process.platform is not configurable in this runtime') + } + }) + + beforeEach(() => { + setPlatform('win32') + spawnSyncMock.mockReset() + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + afterAll(() => { + if (originalPlatformDescriptor) { + Object.defineProperty(process, 'platform', originalPlatformDescriptor) + } + }) + + it('escalates soft taskkill to /F when the process stays alive (mirrors SIGTERM→SIGKILL)', async () => { + // Soft taskkill on win32 console trees often fails with + // "can only be terminated forcefully" — orphanReap must escalate. + let alive = true + // Match @types/node process.kill(pid, signal?: string | number): true + vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (!alive) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + return true + }) + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'tasklist') { + if (!alive) { + return completed('INFO: No tasks are running which match the specified criteria.') + } + return completed(`hapi.exe 5544 Console 1 5,000 K`) + } + if (cmd !== 'taskkill') { + return completed('') + } + if (args.includes('/F')) { + alive = false + return completed('', 0) + } + // Soft refuse — process still alive (real Windows console-tree behavior) + return { + status: 1, + stdout: Buffer.from(''), + stderr: Buffer.from('ERROR: This process can only be terminated forcefully (with /F option).') + } + }) + + const done = killProcess(5544, false) + // Soft fails → immediate /F; then brief death-poll timers + await vi.advanceTimersByTimeAsync(500) + await expect(done).resolves.toBe(true) + + const taskkills = spawnSyncMock.mock.calls.filter((call) => call[0] === 'taskkill') + expect(taskkills.length).toBeGreaterThanOrEqual(2) + expect(taskkills[0]![1]).toEqual(['/T', '/PID', '5544']) + expect(taskkills.some((call) => (call[1] as string[]).includes('/F'))).toBe(true) + }) + + it('waits for grace when soft taskkill succeeds before escalating to /F', async () => { + // Soft status=0 but PID still draining archive flush — do not /F immediately. + let alive = true + let softCalls = 0 + vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (!alive) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + return true + }) + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'tasklist') { + if (!alive) { + return completed('INFO: No tasks are running which match the specified criteria.') + } + return completed(`hapi.exe 7788 Console 1 5,000 K`) + } + if (cmd === 'taskkill' && args.includes('/F')) { + alive = false + return completed('', 0) + } + if (cmd === 'taskkill') { + softCalls += 1 + // Succeeds, but process remains alive until grace elapses + return completed('', 0) + } + return completed('') + }) + + const done = killProcess(7788, false) + // During grace, process exits without needing /F + await vi.advanceTimersByTimeAsync(100) + alive = false + await vi.advanceTimersByTimeAsync(2_500) + await expect(done).resolves.toBe(true) + + expect(softCalls).toBeGreaterThanOrEqual(1) + const forceKills = spawnSyncMock.mock.calls.filter( + (call) => call[0] === 'taskkill' && (call[1] as string[]).includes('/F') + ) + expect(forceKills).toHaveLength(0) + }) + + it('uses forced taskkill immediately when force=true', async () => { + let alive = true + vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (!alive) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + return true + }) + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'tasklist') { + if (!alive) { + return completed('INFO: No tasks are running which match the specified criteria.') + } + return completed(`hapi.exe 9901 Console 1 5,000 K`) + } + if (cmd === 'taskkill' && args.includes('/F')) { + alive = false + return completed('', 0) + } + return completed('', 1) + }) + + const done = killProcess(9901, true) + await vi.advanceTimersByTimeAsync(500) + await expect(done).resolves.toBe(true) + + const taskkills = spawnSyncMock.mock.calls.filter((call) => call[0] === 'taskkill') + expect(taskkills).toHaveLength(1) + expect(taskkills[0]![1]).toEqual(['/F', '/T', '/PID', '9901']) + }) + + it('killProcessTreeByPid signals surviving descendants after taskkill /T misses them', async () => { + // #1911 bot Major: taskkill /T exit 0 is "signalled", not "tree gone". + // When the root dies but a grandchild survives (broken intermediate link), + // individually signal survivors from the pre-kill snapshot — but only when + // the process-generation marker still matches (PID reuse guard). + const { killProcessTreeByPid } = await import('./process') + const alive = new Set([100, 200]) // 100=root, 200=descendant + const markers = new Map([[100, 'gen-100'], [200, 'gen-200']]) + const taskkillPids: number[] = [] + vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (!alive.has(pid)) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + return true + }) + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'powershell') { + const script = String(args[args.length - 1] ?? '') + if (script.includes('ParentProcessId')) { + return completed('OK:200,100') + } + // getProcessStartMarker CIM probe + const filterMatch = /ProcessId = (\d+)/.exec(script) + if (filterMatch) { + const pid = Number(filterMatch[1]) + if (!alive.has(pid)) return completed('') + return completed(markers.get(pid) ?? '') + } + return completed('') + } + if (cmd === 'tasklist') { + const filter = args.find((a) => a.startsWith('PID eq ')) + const pid = filter ? Number(filter.replace('PID eq ', '')) : NaN + if (!alive.has(pid)) { + return completed('INFO: No tasks are running which match the specified criteria.') + } + return completed(`proc.exe ${pid} Console 1 1,000 K`) + } + if (cmd === 'taskkill') { + const idx = args.indexOf('/PID') + const pid = Number(args[idx + 1]) + taskkillPids.push(pid) + alive.delete(pid) + return completed('', 0) + } + return completed('') + }) + + const done = killProcessTreeByPid(100, true) + await vi.advanceTimersByTimeAsync(500) + await expect(done).resolves.toBe(true) + expect(taskkillPids).toContain(100) + expect(taskkillPids).toContain(200) + expect(alive.size).toBe(0) + }) + + it('killProcessTreeByPid does not kill a surviving PID that was reused', async () => { + const { killProcessTreeByPid } = await import('./process') + const alive = new Set([100, 200]) + // After root kill, PID 200 is recycled with a new generation marker. + let rootGone = false + const taskkillPids: number[] = [] + vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (!alive.has(pid)) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + return true + }) + spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => { + if (cmd === 'powershell') { + const script = String(args[args.length - 1] ?? '') + if (script.includes('ParentProcessId')) { + return completed('OK:200,100') + } + const filterMatch = /ProcessId = (\d+)/.exec(script) + if (filterMatch) { + const pid = Number(filterMatch[1]) + if (!alive.has(pid)) return completed('') + if (pid === 200 && rootGone) return completed('gen-200-reused') + return completed(pid === 100 ? 'gen-100' : 'gen-200') + } + return completed('') + } + if (cmd === 'tasklist') { + const filter = args.find((a) => a.startsWith('PID eq ')) + const pid = filter ? Number(filter.replace('PID eq ', '')) : NaN + if (!alive.has(pid)) { + return completed('INFO: No tasks are running which match the specified criteria.') + } + return completed(`proc.exe ${pid} Console 1 1,000 K`) + } + if (cmd === 'taskkill') { + const idx = args.indexOf('/PID') + const pid = Number(args[idx + 1]) + taskkillPids.push(pid) + if (pid === 100) { + alive.delete(100) + rootGone = true + } else { + alive.delete(pid) + } + return completed('', 0) + } + return completed('') + }) + + const done = killProcessTreeByPid(100, true) + await vi.advanceTimersByTimeAsync(500) + // Root signalled; reused descendant left alone → tree verify fails closed. + await expect(done).resolves.toBe(false) + expect(taskkillPids).toEqual([100]) + expect(alive.has(200)).toBe(true) + }) + + it('windowsProcessTreeCimCommand is newline-separated (WinPS-parseable)', async () => { + // #1911 bot Major: `.join(' ')` yields `$seen=@{} $bfs=@()` — parse error. + // Assert generated command text, not mocked stdout (mocks never parse PS). + const { windowsProcessTreeCimCommand } = await import('./process') + const cmd = windowsProcessTreeCimCommand(4242) + expect(cmd).toContain('$root=4242') + expect(cmd).toContain('ParentProcessId=$p') + // Statements must be on separate lines — spaces between `$x=@{}` tokens fail. + expect(cmd).toContain('\n$seen=@{}') + expect(cmd).toContain('\n$bfs=@()') + expect(cmd).toContain('\n$queue=@($root)') + expect(cmd).toContain('\nwhile($queue.Count -gt 0){') + // Space-join regression: adjacent statement tokens on one line (not newline). + expect(cmd).not.toMatch(/\$seen=@\{\}[ ]+\$bfs=@\(\)/) + expect(cmd).not.toMatch(/\$bfs=@\(\)[ ]+\$queue=@/) + // Do not terminate `while(...){` with `;` (also invalid). + expect(cmd).not.toMatch(/while\(\$queue\.Count -gt 0\)\{\s*;/) + // #1911 B1: never SilentlyContinue — CIM failure must not look like childless root. + expect(cmd).toContain("$ErrorActionPreference='Stop'") + expect(cmd).toContain('trap { exit 1 }') + expect(cmd).not.toContain('SilentlyContinue') + expect(cmd).toContain('Write-Output ("OK:" + ($bfs -join ","))') + }) + + it('parseWindowsProcessTreeStdout requires OK: sentinel (B1 root-only is scan_failed)', async () => { + const { parseWindowsProcessTreeStdout } = await import('./process') + // Overseer measured: CIM failure with SilentlyContinue prints "1234" exit 0 — + // byte-identical to healthy childless. Without OK: that must be scan_failed. + expect(parseWindowsProcessTreeStdout('1234', 1234)).toBe('scan_failed') + expect(parseWindowsProcessTreeStdout('4000,3000,2000,1234', 1234)).toBe('scan_failed') + expect(parseWindowsProcessTreeStdout('', 1234)).toBe('scan_failed') + expect(parseWindowsProcessTreeStdout('OK:', 1234)).toBe('scan_failed') + expect(parseWindowsProcessTreeStdout('OK:1234', 1234)).toEqual([1234]) + expect(parseWindowsProcessTreeStdout('OK:4000,3000,2000,1234', 1234)).toEqual([ + 4000, 3000, 2000, 1234, + ]) + expect(parseWindowsProcessTreeStdout('OK:200,100', 100)).toEqual([200, 100]) + expect(parseWindowsProcessTreeStdout('OK:200,100', 999)).toBe('scan_failed') + }) + + it('killProcessTreeByPid treats bare root stdout (B1 fail-open shape) as scan_failed', async () => { + const { killProcessTreeByPid } = await import('./process') + let alive = true + vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (!alive) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + return true + }) + spawnSyncMock.mockImplementation((cmd: string) => { + // Status 0 + root-only — the measured CIM-failure shape under SilentlyContinue. + if (cmd === 'powershell') return completed('1234') + if (cmd === 'tasklist') { + if (!alive) { + return completed('INFO: No tasks are running which match the specified criteria.') + } + return completed(`proc.exe 1234 Console 1 1,000 K`) + } + if (cmd === 'taskkill') { + alive = false + return completed('', 0) + } + return completed('') + }) + const done = killProcessTreeByPid(1234, true) + await vi.advanceTimersByTimeAsync(500) + await expect(done).resolves.toBe(false) + expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true) + }) + + it('killProcessTreeByPid signals root but returns false when Windows tree scan fails', async () => { + const { killProcessTreeByPid } = await import('./process') + let alive = true + vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (!alive) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + return true + }) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'powershell') { + return { status: 1, stdout: Buffer.from(''), stderr: Buffer.from('parse error') } + } + if (cmd === 'tasklist') { + if (!alive) { + return completed('INFO: No tasks are running which match the specified criteria.') + } + return completed(`proc.exe 100 Console 1 1,000 K`) + } + if (cmd === 'taskkill') { + alive = false + return completed('', 0) + } + return completed('') + }) + const done = killProcessTreeByPid(100, true) + await vi.advanceTimersByTimeAsync(500) + await expect(done).resolves.toBe(false) + // Partial kill: root signalled, but never claim stopped without tree verify. + expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true) + }) + + it('killProcessTreeByPid signals root but returns false when Windows tree scan returns empty stdout', async () => { + const { killProcessTreeByPid } = await import('./process') + let alive = true + vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (!alive) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + return true + }) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'powershell') return completed('') // status 0, empty — scan_failed + if (cmd === 'tasklist') { + if (!alive) { + return completed('INFO: No tasks are running which match the specified criteria.') + } + return completed(`proc.exe 100 Console 1 1,000 K`) + } + if (cmd === 'taskkill') { + alive = false + return completed('', 0) + } + return completed('') + }) + const done = killProcessTreeByPid(100, true) + await vi.advanceTimersByTimeAsync(500) + await expect(done).resolves.toBe(false) + expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true) + }) +}) + +describe('killProcessTreeByPid on POSIX (pgrep tree scan)', () => { + beforeEach(() => { + setPlatform('linux') + spawnSyncMock.mockReset() + vi.spyOn(process, 'kill').mockReturnValue(true) + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + afterAll(() => { + if (originalPlatformDescriptor) { + Object.defineProperty(process, 'platform', originalPlatformDescriptor) + } + }) + + it('returns false when pgrep is missing (signal root, never claim stopped)', async () => { + const { killProcessTreeByPid } = await import('./process') + let dead = false + vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (dead) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + dead = true + return true + }) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'pgrep') return unavailable('pgrep') + return completed('') + }) + const done = killProcessTreeByPid(4242, true) + await vi.advanceTimersByTimeAsync(3000) + await expect(done).resolves.toBe(false) + // Root still signalled — partial kill > zero kill on hosts without pgrep. + expect(process.kill).toHaveBeenCalledWith(4242, 'SIGKILL') + }) + + it('returns false when pgrep is signalled (status null — partial tree)', async () => { + const { killProcessTreeByPid } = await import('./process') + let dead = false + vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => { + if (signal === 0 || signal === undefined) { + if (dead) { + const err = new Error('ESRCH') as NodeJS.ErrnoException + err.code = 'ESRCH' + throw err + } + return true + } + dead = true + return true + }) + spawnSyncMock.mockImplementation((cmd: string) => { + if (cmd === 'pgrep') { + return { status: null, stdout: '999\n', stderr: '', error: null } + } + return completed('') + }) + const done = killProcessTreeByPid(4242, true) + await vi.advanceTimersByTimeAsync(3000) + await expect(done).resolves.toBe(false) + expect(process.kill).toHaveBeenCalledWith(4242, 'SIGKILL') }) }) diff --git a/cli/src/utils/process.ts b/cli/src/utils/process.ts index 21681f7c..5acea9b8 100644 --- a/cli/src/utils/process.ts +++ b/cli/src/utils/process.ts @@ -3,11 +3,33 @@ import spawn from 'cross-spawn'; 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 { if (!Number.isFinite(pid) || pid <= 0) { return false; } + // Windows: prefer tasklist. Bun/Node `process.kill(pid, 0)` is unreliable as a + // liveness probe on win32 and can disagree with the console tree taskkill sees. + if (isWindows()) { + try { + const result = spawn.sync( + 'tasklist', + ['/FI', `PID eq ${pid}`, '/NH'], + { stdio: 'pipe', windowsHide: true, encoding: 'utf8', timeout: SPAWN_SYNC_TIMEOUT_MS } + ); + 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); + } + } catch { + // fall through to signal-0 probe + } + } + try { process.kill(pid, 0); return true; @@ -16,28 +38,59 @@ export function isProcessAlive(pid: number): boolean { } } +/** + * Shared Win32 generation marker: CIM CreationDate as UTC round-trip ISO. + * Must match orphan list + recheck — ConvertTo-Json of a raw DateTime emits + * `/Date(...)/` on Windows PowerShell 5.1 (#1911 bot Major). + */ +export const WINDOWS_CIM_CREATION_DATE_MARKER_EXPR = + "$_.CreationDate.ToUniversalTime().ToString('o')"; + +/** PowerShell -Command body for the argv orphan process list (CIM + JSON). */ +export function windowsProcessListCimCommand(): string { + // Fail closed: non-terminating CIM errors must not yield empty stdout with + // exit 0 (that was misread as "no orphans" → false archive-ok). #1911 B2. + // Note: Stop on the whole enumeration means one transient per-instance WMI + // error aborts the scan → still_alive until it clears (availability trap, + // fail-closed; #1911 Overseer non-blocker). + return [ + "$ErrorActionPreference='Stop'", + 'trap { exit 1 }', + 'Get-CimInstance Win32_Process | Select-Object ProcessId,Name,CommandLine,' + + `@{N='CreationDate';E={if ($_.CreationDate) { ${WINDOWS_CIM_CREATION_DATE_MARKER_EXPR} } else { $null }}}` + + ' | ConvertTo-Json -Compress', + ].join('\n') +} + +/** PowerShell -Command body for a single-PID start-marker probe. */ +export function windowsProcessMarkerCimCommand(pid: number): string { + const expr = WINDOWS_CIM_CREATION_DATE_MARKER_EXPR.replace(/\$_/g, '$p'); + return ( + `$p = Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; ` + + `if ($p -and $p.CreationDate) { ${expr} }` + ); +} + /** Stable marker for one OS PID generation; null means the platform probe failed. */ export function getProcessStartMarker(pid: number): string | null { if (!isProcessAlive(pid)) return null; if (isWindows()) { + // Same UTC ISO 'o' string as orphanReap listWindowsProcessesWithCommandLine. + // Do not print raw DateTime or use WMIC DMTF (format mismatch skips reap). const powershell = spawn.sync('powershell', [ '-NoProfile', '-NonInteractive', '-Command', - `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CreationDate` - ], { stdio: 'pipe', windowsHide: true }); + windowsProcessMarkerCimCommand(pid), + ], { stdio: 'pipe', windowsHide: true, timeout: SPAWN_SYNC_TIMEOUT_MS }); if (!powershell.error && powershell.status === 0) { const marker = powershell.stdout?.toString().trim(); if (marker) return marker; } - const result = spawn.sync('wmic', [ - 'process', 'where', `ProcessId=${pid}`, 'get', 'CreationDate', '/value' - ], { stdio: 'pipe', windowsHide: true }); - if (result.error || result.status !== 0) return null; - const match = (result.stdout?.toString() ?? '').match(/CreationDate=([^\r\n]+)/); - return match?.[1]?.trim() || null; + return null; } const result = spawn.sync('ps', ['-p', String(pid), '-o', 'lstart='], { stdio: 'pipe', - env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' } + env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' }, + timeout: SPAWN_SYNC_TIMEOUT_MS, }); if (result.error || result.status !== 0) return null; return result.stdout?.toString().trim() || null; @@ -56,7 +109,7 @@ function getWindowsProcessCommandLine(pid: number): string | null { '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine` - ], { stdio: 'pipe', windowsHide: true }); + ], { stdio: 'pipe', windowsHide: true, timeout: SPAWN_SYNC_TIMEOUT_MS }); if (!powershell.error && powershell.status === 0) { const commandLine = powershell.stdout?.toString() ?? ''; if (commandLine.trim()) return commandLine; @@ -64,7 +117,7 @@ function getWindowsProcessCommandLine(pid: number): string | null { const wmic = spawn.sync('wmic', [ 'process', 'where', `ProcessId=${pid}`, 'get', 'CommandLine' - ], { stdio: 'pipe', windowsHide: true }); + ], { stdio: 'pipe', windowsHide: true, timeout: SPAWN_SYNC_TIMEOUT_MS }); if (!wmic.error && wmic.status === 0) { const commandLine = readWmicCommandLine(wmic.stdout?.toString() ?? ''); if (commandLine) return commandLine; @@ -106,7 +159,10 @@ export function getHapiRunnerProcessIdentity(pid: number): RunnerProcessIdentity } function getPosixProcessCommandLine(pid: number): string | null { - const result = spawn.sync('ps', ['-p', String(pid), '-o', 'command='], { stdio: 'pipe' }); + const result = spawn.sync('ps', ['-p', String(pid), '-o', 'command='], { + stdio: 'pipe', + timeout: SPAWN_SYNC_TIMEOUT_MS, + }); if (result.error || result.status !== 0) return null; const commandLine = result.stdout?.toString() ?? ''; return commandLine.trim() ? commandLine : null; @@ -124,7 +180,8 @@ function killProcessWindows(pid: number, force: boolean): boolean { try { const result = spawn.sync('taskkill', args, { stdio: 'pipe', - windowsHide: true + windowsHide: true, + timeout: SPAWN_SYNC_TIMEOUT_MS, }); if (result.error) { return false; @@ -143,18 +200,110 @@ function killProcessWindows(pid: number, force: boolean): boolean { } } +/** + * Collect a win32 process tree (children first, root last) via CIM ParentProcessId. + * Used to verify taskkill /T actually cleared descendants — exit 0 is "signalled", + * not "gone" (#1911 B2). + * + * Returns `'scan_failed'` when PowerShell errors or returns nothing usable — + * callers must fail closed (never fall back to root-only verify). + * + * Success is a positive sentinel (`OK:`), not "exit 0 + somehow looks like + * PIDs". With `-ErrorAction SilentlyContinue`, a CIM failure exited 0 printing + * only the root — byte-identical to a healthy childless tree (#1911 B1). + */ +export function windowsProcessTreeCimCommand(pid: number): string { + // Newlines between statements — `.join(' ')` is a parse error on WinPS + // (`$seen=@{} $bfs=@()`). Do not join with `;` either: `while(...){;` is invalid. + return [ + "$ErrorActionPreference='Stop'", + 'trap { exit 1 }', + `$root=${pid}`, + '$seen=@{}', + '$bfs=@()', + '$queue=@($root)', + 'while($queue.Count -gt 0){', + ' $p=$queue[0]; if($queue.Count -eq 1){$queue=@()}else{$queue=$queue[1..($queue.Count-1)]}', + ' if($seen.ContainsKey($p)){continue}', + ' $seen[$p]=$true', + ' $bfs+=$p', + ' Get-CimInstance Win32_Process -Filter "ParentProcessId=$p" |', + ' ForEach-Object { $queue+=,[int]$_.ProcessId }', + '}', + // children-first: reverse BFS so root is last; OK: marks clean completion + 'if($bfs.Count -gt 0){ [array]::Reverse($bfs); Write-Output ("OK:" + ($bfs -join ",")) }', + ].join('\n') +} + +/** Parse tree-scan stdout. Requires the `OK:` success sentinel (#1911 B1). */ +export function parseWindowsProcessTreeStdout( + raw: string, + rootPid: number +): number[] | 'scan_failed' { + const text = raw.trim() + if (!text.startsWith('OK:')) return 'scan_failed' + const body = text.slice('OK:'.length).trim() + if (!body) return 'scan_failed' + const pids = body.split(',').map((s) => Number(s.trim())).filter((p) => Number.isFinite(p) && p > 0) + if (pids.length === 0 || !pids.includes(rootPid)) return 'scan_failed' + return pids +} + +export function collectWindowsProcessTree(pid: number): number[] | 'scan_failed' { + const n = typeof pid === 'number' ? pid : Number(pid) + if (!Number.isFinite(n) || n <= 0) return 'scan_failed' + + const result = spawn.sync( + 'powershell', + [ + '-NoProfile', + '-NonInteractive', + '-Command', + windowsProcessTreeCimCommand(n), + ], + { encoding: 'utf8', windowsHide: true, maxBuffer: 16 * 1024 * 1024, timeout: SPAWN_SYNC_TIMEOUT_MS } + ) + if (result.error || result.status !== 0) { + return 'scan_failed' + } + return parseWindowsProcessTreeStdout((result.stdout ?? '').toString(), n) +} + +async function signalAndWaitWindowsRoot(pid: number, force: boolean): Promise { + if (force) { + killProcessWindows(pid, true); + await waitForProcessToDie(pid, true); + return; + } + const softOk = killProcessWindows(pid, false); + if (!softOk && isProcessAlive(pid)) { + killProcessWindows(pid, true); + await waitForProcessToDie(pid, true); + return; + } + await waitForProcessToDie(pid, false); +} + export async function killProcess(pid: number, force: boolean = false): Promise { - if (!Number.isFinite(pid) || pid <= 0) { + const n = typeof pid === 'number' ? pid : Number(pid) + if (!Number.isFinite(n) || n <= 0) { return false; } if (isWindows()) { - return killProcessWindows(pid, force); + // Soft taskkill (/T without /F) is routinely refused on win32 console trees + // ("can only be terminated forcefully"). Mirror POSIX SIGTERM→SIGKILL: + // escalate immediately only when soft kill is *refused*; when soft succeeds + // but the PID is still draining, honor the grace wait before /F so archive + // flush can finish. + // Root-only verify — callers that need full-tree proof use killProcessTreeByPid. + await signalAndWaitWindowsRoot(n, force); + return !isProcessAlive(n); } try { - process.kill(pid, force ? 'SIGKILL' : 'SIGTERM'); - await waitForProcessToDie(pid, force); + process.kill(n, force ? 'SIGKILL' : 'SIGTERM'); + await waitForProcessToDie(n, force); return true; } catch { return false; @@ -163,21 +312,34 @@ export async function killProcess(pid: number, force: boolean = false): Promise< /** * Recursively collects all descendant PIDs of a process (depth-first). - * Returns PIDs in child-first order (leaves first, root last). + * Returns PIDs in child-first order (leaves first, root last), or + * `'scan_failed'` when pgrep could not be run (so callers fail closed + * instead of verifying root-only — #1911 Opus / Overseer). */ -function collectProcessTree(pid: number): number[] { +function collectProcessTree(pid: number): number[] | 'scan_failed' { const pids: number[] = []; - try { - const result = spawn.sync('pgrep', ['-P', pid.toString()], { encoding: 'utf8' }); - if (result.stdout) { - const childPids = result.stdout.trim().split('\n').filter(Boolean).map(Number); - for (const childPid of childPids) { - pids.push(...collectProcessTree(childPid)); - } + const result = spawn.sync('pgrep', ['-P', pid.toString()], { + encoding: 'utf8', + timeout: SPAWN_SYNC_TIMEOUT_MS, + }); + // spawn.sync returns {error} rather than throwing when the binary is missing. + if (result.error) { + return 'scan_failed'; + } + // pgrep: 0 = matches, 1 = no children. null = signalled / aborted → partial + // stdout is not a trustworthy tree (#1911 Overseer POSIX B1 twin). + if (result.status !== 0 && result.status !== 1) { + return 'scan_failed'; + } + if (result.stdout) { + const childPids = result.stdout.trim().split('\n').filter(Boolean).map(Number); + for (const childPid of childPids) { + if (!Number.isFinite(childPid) || childPid <= 0) continue; + const nested = collectProcessTree(childPid); + if (nested === 'scan_failed') return 'scan_failed'; + pids.push(...nested); } - } catch { - // pgrep may not be available } pids.push(pid); @@ -192,6 +354,18 @@ function collectProcessTree(pid: number): number[] { async function killProcessTree(pid: number, force: boolean): Promise { // Collect all PIDs first (sync) - returns in child-first order const pids = collectProcessTree(pid); + if (pids === 'scan_failed') { + // Signal the known root anyway (partial kill > zero kill), but never claim + // stopped without a full-tree verify (#1911 Opus Major / debian-slim no pgrep). + const signal = force ? 'SIGKILL' : 'SIGTERM'; + try { + process.kill(pid, signal); + } catch { + // already gone + } + await waitForProcessToDie(pid, force); + return false; + } // Signal all processes synchronously (children first, then root) const signal = force ? 'SIGKILL' : 'SIGTERM'; @@ -213,17 +387,48 @@ async function killProcessTree(pid: number, force: boolean): Promise { /** Kill a PID and all descendants, verifying the complete tree is gone. */ export async function killProcessTreeByPid(pid: number, force: boolean = false): Promise { - if (!Number.isFinite(pid) || pid <= 0) return false; - if (isWindows()) return killProcess(pid, force); - return killProcessTree(pid, force); + const n = typeof pid === 'number' ? pid : Number(pid) + if (!Number.isFinite(n) || n <= 0) return false; + if (isWindows()) { + // taskkill /T exit 0 means "signalled", not "every descendant is dead". + // Collect the tree + generation markers first, signal the root with /T, + // then individually signal any surviving pre-kill PIDs whose generation + // still matches (PID reuse must not be killed) (#1911 bot Major). + const treePids = collectWindowsProcessTree(n); + if (treePids === 'scan_failed') { + // Still signal the (known) root — scan failure must not mean zero kill — + // but never claim stopped without a full-tree verify (#1911 Opus Major). + await signalAndWaitWindowsRoot(n, force); + return false; + } + const markers = new Map(); + for (const candidate of treePids) { + markers.set(candidate, getProcessStartMarker(candidate)); + } + await signalAndWaitWindowsRoot(n, force); + for (const survivor of treePids) { + if (survivor === n) continue; + if (!isProcessAlive(survivor)) continue; + const expected = markers.get(survivor); + const current = getProcessStartMarker(survivor); + // Unverifiable or reused PID — leave alone; final every() fails closed. + if (!expected || !current || current !== expected) continue; + await signalAndWaitWindowsRoot(survivor, true); + } + return treePids.every((candidate) => !isProcessAlive(candidate)); + } + return killProcessTree(n, force); } /** - * Waits for a process to die, escalating to SIGKILL if SIGTERM doesn't work. + * Waits for a process to die, escalating if the graceful signal didn't work. + * POSIX: SIGTERM → SIGKILL. Windows: taskkill /T → taskkill /F /T. */ async function waitForProcessToDie(pid: number, force: boolean): Promise { const maxWait = 2000; - const pollInterval = 20; + // Windows isProcessAlive shells out to tasklist; keep the poll coarse so a + // stop cannot burn the runner event loop for seconds (#1911 Overseer). + const pollInterval = isWindows() ? 100 : 20; let waited = 0; while (isProcessAlive(pid) && waited < maxWait) { @@ -231,10 +436,14 @@ async function waitForProcessToDie(pid: number, force: boolean): Promise { waited += pollInterval; } - // If SIGTERM didn't work and we haven't tried SIGKILL yet, escalate + // Graceful kill didn't finish — escalate (same structure on both platforms). if (!force && isProcessAlive(pid)) { try { - process.kill(pid, 'SIGKILL'); + if (isWindows()) { + killProcessWindows(pid, true); + } else { + process.kill(pid, 'SIGKILL'); + } } catch { return; } @@ -255,11 +464,6 @@ export async function killProcessByChildProcess( return false; } - if (isWindows()) { - // Windows taskkill /T already kills the entire process tree - return killProcess(pid, force); - } - - // Kill entire process tree on Unix to prevent orphan processes + // Both platforms: tree-kill + full-tree verify (win32 must not trust root-only). return killProcessTreeByPid(pid, force); } diff --git a/cli/src/utils/windowsProcessTree.pwsh.test.ts b/cli/src/utils/windowsProcessTree.pwsh.test.ts new file mode 100644 index 00000000..607bbf35 --- /dev/null +++ b/cli/src/utils/windowsProcessTree.pwsh.test.ts @@ -0,0 +1,100 @@ +/** + * Executes the generated Windows tree-scan PowerShell under Docker pwsh. + * Mocks agree with themselves; this is the structural antidote to #1911 B1 + * (CIM failure looking like a healthy childless root). + * + * Locally: skips when docker/image missing. + * In CI (`CI=true`): fails hard — silent skip is fake coverage (#1911 Overseer). + */ +import { execFileSync } from 'node:child_process' +import { describe, expect, it } from 'vitest' +import { windowsProcessListCimCommand, windowsProcessTreeCimCommand } from './process' + +const POWERSHELL_IMAGE = 'mcr.microsoft.com/powershell:latest' + +function dockerPwshAvailable(): boolean { + try { + execFileSync('docker', ['image', 'inspect', POWERSHELL_IMAGE], { + stdio: 'ignore', + }) + return true + } catch { + return false + } +} + +function ensureDockerPwsh(): void { + if (dockerPwshAvailable()) return + if (process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true') { + throw new Error( + `CI requires ${POWERSHELL_IMAGE} for windowsProcessTree.pwsh.test.ts — ` + + 'pull it in the workflow before bun run test (silent skip is not coverage)' + ) + } +} + +function runPwsh(script: string): { status: number; stdout: string; stderr: string } { + try { + const stdout = execFileSync( + 'docker', + ['run', '--rm', POWERSHELL_IMAGE, 'pwsh', '-NoProfile', '-Command', script], + { encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 } + ) + return { status: 0, stdout: stdout.toString(), stderr: '' } + } catch (error) { + const err = error as { status?: number; stdout?: string; stderr?: string } + return { + status: typeof err.status === 'number' ? err.status : 1, + stdout: err.stdout?.toString() ?? '', + stderr: err.stderr?.toString() ?? '', + } + } +} + +ensureDockerPwsh() +const describePwsh = dockerPwshAvailable() ? describe : describe.skip + +describePwsh('windowsProcessTreeCimCommand under real pwsh (#1911 B1)', () => { + it('fails closed when Get-CimInstance is missing (Linux container)', () => { + // Measured pre-fix: SilentlyContinue printed root-only with exit 0. + const result = runPwsh(windowsProcessTreeCimCommand(1234)) + expect(result.status).not.toBe(0) + expect(result.stdout.trim()).not.toMatch(/^OK:/) + expect(result.stdout.trim()).not.toBe('1234') + }) + + it('emits OK: children-first tree when Get-CimInstance is mocked healthy', () => { + const mock = ` +function Get-CimInstance { + param($ClassName, $Filter) + $ppid = [int](($Filter -split "=")[1]) + if ($ppid -eq 1234) { + [pscustomobject]@{ ProcessId = 2000 } + [pscustomobject]@{ ProcessId = 3000 } + } elseif ($ppid -eq 2000) { + [pscustomobject]@{ ProcessId = 4000 } + } +} +${windowsProcessTreeCimCommand(1234)} +` + const result = runPwsh(mock) + expect(result.status).toBe(0) + expect(result.stdout.trim()).toBe('OK:4000,3000,2000,1234') + }) + + it('emits OK:root alone when the mocked tree has no children', () => { + const mock = ` +function Get-CimInstance { param($ClassName, $Filter) } +${windowsProcessTreeCimCommand(1234)} +` + const result = runPwsh(mock) + expect(result.status).toBe(0) + expect(result.stdout.trim()).toBe('OK:1234') + }) + + it('list command fails closed when Get-CimInstance is missing', () => { + const result = runPwsh(windowsProcessListCimCommand()) + expect(result.status).not.toBe(0) + expect(result.stdout.trim()).toBe('') + }) +}) diff --git a/hub/src/store/sessionStore.ts b/hub/src/store/sessionStore.ts index 0efd403e..f0ec18d5 100644 --- a/hub/src/store/sessionStore.ts +++ b/hub/src/store/sessionStore.ts @@ -4,6 +4,7 @@ import type { StoredSession, VersionedUpdateResult } from './types' import { deleteSession, getOrCreateSession, + adoptPreallocatedSession, getSession, getSessionByNamespace, getSessions, @@ -44,12 +45,27 @@ export class SessionStore { return getOrCreateSession(this.db, tag, metadata, agentState, namespace, model, effort, modelReasoningEffort, requestedId) } + adoptPreallocatedSession( + id: string, + tag: string, + metadata: unknown, + agentState: unknown, + namespace: string, + model?: string, + effort?: string, + modelReasoningEffort?: string + ): StoredSession { + return adoptPreallocatedSession( + this.db, id, tag, metadata, agentState, namespace, model, effort, modelReasoningEffort + ) + } + updateSessionMetadata( id: string, metadata: unknown, expectedVersion: number, namespace: string, - options?: { touchUpdatedAt?: boolean } + options?: { touchUpdatedAt?: boolean; allowUnarchive?: boolean } ): VersionedUpdateResult { return updateSessionMetadata(this.db, id, metadata, expectedVersion, namespace, options) } diff --git a/hub/src/store/sessions.test.ts b/hub/src/store/sessions.test.ts index 94762c86..79082b43 100644 --- a/hub/src/store/sessions.test.ts +++ b/hub/src/store/sessions.test.ts @@ -114,6 +114,354 @@ describe('getOrCreateSession: requested identity', () => { )).toThrow(SessionIdentityConflictError) store.close() }) + + it('reproduces hub-prealloc vs CLI-tag conflict (machine-spawn stub, #1911)', () => { + // Hub preallocates with tag machine-spawn:; CLI create used a random + // tag + the same id → 409. This documents the bug adopt must fix. + const store = makeStore() + const allocatedId = randomUUID() + store.sessions.getOrCreateSession( + `machine-spawn:${allocatedId}`, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + machineId: 'machine-1', + startedBy: 'runner', + startedFromRunner: true, + }, + null, + 'default', + undefined, + undefined, + undefined, + allocatedId + ) + + expect(() => store.sessions.getOrCreateSession( + randomUUID(), // CLI bootstrap tag + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + machineId: 'machine-1', + startedBy: 'runner', + hostPid: 12345, + }, + {}, + 'default', + undefined, + undefined, + undefined, + allocatedId + )).toThrow(SessionIdentityConflictError) + store.close() + }) + + it('adopts a machine-spawn preallocated stub and overwrites tag + metadata', () => { + const store = makeStore() + const allocatedId = randomUUID() + const cliTag = randomUUID() + store.sessions.getOrCreateSession( + `machine-spawn:${allocatedId}`, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + machineId: 'machine-1', + startedBy: 'runner', + startedFromRunner: true, + }, + null, + 'default', + 'stub-model', + undefined, + undefined, + allocatedId + ) + + const adopted = store.sessions.adoptPreallocatedSession( + allocatedId, + cliTag, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + machineId: 'machine-1', + startedBy: 'runner', + startedFromRunner: true, + hostPid: 4242, + }, + { controlledByUser: false }, + 'default', + 'claude-sonnet', + undefined, + undefined + ) + + expect(adopted.id).toBe(allocatedId) + expect(adopted.tag).toBe(cliTag) + expect(adopted.model).toBe('claude-sonnet') + const meta = adopted.metadata as { hostPid?: number } + expect(meta.hostPid).toBe(4242) + // Idempotent adopt with same tag returns the row + const again = store.sessions.adoptPreallocatedSession( + allocatedId, + cliTag, + { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + {}, + 'default' + ) + expect(again.id).toBe(allocatedId) + expect(again.tag).toBe(cliTag) + store.close() + }) + + it('rejects adopt when the row is not a preallocated stub', () => { + const store = makeStore() + const id = randomUUID() + store.sessions.getOrCreateSession( + 'live-terminal-tag', + { path: '/tmp', startedBy: 'terminal' }, + null, + 'default', + undefined, + undefined, + undefined, + id + ) + + expect(() => store.sessions.adoptPreallocatedSession( + id, + randomUUID(), + { path: '/tmp', startedBy: 'runner' }, + {}, + 'default' + )).toThrow(/not a preallocated stub|not adoptable/i) + store.close() + }) + + it('releases machine-spawn stub tag on metadata update (reopen-flavor path)', () => { + // codex/cursor/pi/… use --existing-session-id → bootstrapExistingSession + // → updateMetadata, never adopt. Stub tag must not stick forever. + const store = makeStore() + const allocatedId = randomUUID() + const created = store.sessions.getOrCreateSession( + `machine-spawn:${allocatedId}`, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'cursor', + machineId: 'm1', + startedBy: 'runner', + startedFromRunner: true, + }, + null, + 'default', + undefined, + undefined, + undefined, + allocatedId + ) + expect(created.tag).toBe(`machine-spawn:${allocatedId}`) + + const updated = store.sessions.updateSessionMetadata( + allocatedId, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'cursor', + machineId: 'm1', + startedBy: 'runner', + startedFromRunner: true, + hostPid: 999, + }, + created.metadataVersion, + 'default' + ) + expect(updated.result).toBe('success') + const row = store.sessions.getSession(allocatedId) + expect(row?.tag).not.toMatch(/^machine-spawn:/) + expect((row?.metadata as { hostPid?: number } | null)?.hostPid).toBe(999) + + // Live row must no longer be adoptable. + expect(() => store.sessions.adoptPreallocatedSession( + allocatedId, + randomUUID(), + { path: '/tmp', flavor: 'cursor' }, + {}, + 'default' + )).toThrow(/not a preallocated stub|not adoptable/i) + store.close() + }) + + it('rejects adopt of an archived preallocated stub', () => { + const store = makeStore() + const allocatedId = randomUUID() + store.sessions.getOrCreateSession( + `machine-spawn:${allocatedId}`, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + startedBy: 'runner', + startedFromRunner: true, + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'user archived while booting', + }, + null, + 'default', + undefined, + undefined, + undefined, + allocatedId + ) + + expect(() => store.sessions.adoptPreallocatedSession( + allocatedId, + randomUUID(), + { path: '/tmp/project', host: 'localhost', flavor: 'claude' }, + {}, + 'default' + )).toThrow(/archived|not adoptable/i) + const row = store.sessions.getSession(allocatedId) + expect(row?.tag).toBe(`machine-spawn:${allocatedId}`) + expect((row?.metadata as { lifecycleState?: string } | null)?.lifecycleState).toBe('archived') + store.close() + }) +}) + +describe('updateSessionMetadata: refuse un-archive (#1911 M1)', () => { + it('merge-preserves hub archive on unauthorized running write (success, not mismatch)', () => { + const store = makeStore() + const allocatedId = randomUUID() + const session = store.sessions.getOrCreateSession( + `machine-spawn:${allocatedId}`, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'KillSession miss', + startedBy: 'runner', + startedFromRunner: true, + }, + null, + 'default', + undefined, + undefined, + undefined, + allocatedId + ) + + const preserved = store.sessions.updateSessionMetadata( + session.id, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + lifecycleState: 'running', + }, + session.metadataVersion, + 'default' + ) + expect(preserved.result).toBe('success') + if (preserved.result !== 'success') throw new Error('expected success') + expect((preserved.value as { lifecycleState?: string; archivedBy?: string } | null)?.lifecycleState) + .toBe('archived') + expect((preserved.value as { archivedBy?: string } | null)?.archivedBy).toBe('hub') + expect(getMetadata(store, session.id)?.lifecycleState).toBe('archived') + expect(getMetadata(store, session.id)?.archivedBy).toBe('hub') + // Tag may already be released by archive-via-metadata; assert archive held. + expect(store.sessions.getSession(session.id)?.tag).toBe(`machine-spawn:${allocatedId}`) + + const allowed = store.sessions.updateSessionMetadata( + session.id, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + lifecycleStateSince: Date.now(), + }, + // version advanced by preserve write + (preserved.version), + 'default', + { allowUnarchive: true } + ) + expect(allowed.result).toBe('success') + expect(getMetadata(store, session.id)?.lifecycleState).toBeUndefined() + store.close() + }) + + it('does not preserve CLI self-archive (archivedBy=cli) when writing running', () => { + const store = makeStore() + const session = store.sessions.getOrCreateSession( + 'cli-self-archive', + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + lifecycleState: 'archived', + archivedBy: 'cli', + archiveReason: 'clean exit', + }, + null, + 'default' + ) + + const result = store.sessions.updateSessionMetadata( + session.id, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + lifecycleState: 'running', + }, + session.metadataVersion, + 'default' + ) + expect(result.result).toBe('success') + expect(getMetadata(store, session.id)?.lifecycleState).toBe('running') + store.close() + }) + + it('still allows non-lifecycle updates while hub-archived', () => { + const store = makeStore() + const session = store.sessions.getOrCreateSession( + 'archived-keep-fields', + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'inactivity', + }, + null, + 'default' + ) + + const result = store.sessions.updateSessionMetadata( + session.id, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'inactivity', + hostPid: 4242, + }, + session.metadataVersion, + 'default' + ) + expect(result.result).toBe('success') + expect(getMetadata(store, session.id)?.lifecycleState).toBe('archived') + expect(getMetadata(store, session.id)?.hostPid).toBe(4242) + store.close() + }) }) describe('updateSessionMetadata: protocol resume token preservation', () => { diff --git a/hub/src/store/sessions.ts b/hub/src/store/sessions.ts index 8d2ad418..c26c38c2 100644 --- a/hub/src/store/sessions.ts +++ b/hub/src/store/sessions.ts @@ -276,27 +276,174 @@ export class SessionIdentityConflictError extends Error { } } +export class SessionNotAdoptableError extends Error { + constructor(message: string) { + super(message) + this.name = 'SessionNotAdoptableError' + } +} + +/** Hub-internal stub tag for fresh machine spawn preallocation (#1911). */ +export function machineSpawnPreallocTag(sessionId: string): string { + return `machine-spawn:${sessionId}` +} + +export function isMachineSpawnPreallocatedStub(session: Pick): boolean { + return session.tag === machineSpawnPreallocTag(session.id) +} + +function isArchivedSessionMetadata(metadata: unknown): boolean { + if (!isPlainObject(metadata)) return false + return metadata.lifecycleState === 'archived' +} + +/** Hub-authored archive only — CLI may archive itself on clean exit. */ +function isHubArchivedSessionMetadata(metadata: unknown): boolean { + if (!isPlainObject(metadata)) return false + return metadata.lifecycleState === 'archived' && metadata.archivedBy === 'hub' +} + +/** + * When a CLI write would clear a hub archive, keep the forensic archive fields + * on the merged payload so the CAS ack returns success + still-archived + * (version-mismatch / error would spin forever in client backoff). + */ +function preserveHubArchiveOnMerged(prior: unknown, merged: unknown): unknown { + if (!isPlainObject(prior) || !isPlainObject(merged)) return prior + const next: Record = { ...merged } + next.lifecycleState = prior.lifecycleState + next.archivedBy = prior.archivedBy + if (prior.archiveReason !== undefined) next.archiveReason = prior.archiveReason + else delete next.archiveReason + if (prior.lifecycleStateSince !== undefined) next.lifecycleStateSince = prior.lifecycleStateSince + return next +} + +/** + * Bind a CLI create bootstrap to a hub-preallocated stub row. + * Overwrites tag + metadata (create-time fields) without minting a new id. + * Rejects rows that are not machine-spawn stubs — live sessions stay protected. + * Rejects archived stubs so adopt cannot resurrect and wipe archive metadata. + */ +export function adoptPreallocatedSession( + db: Database, + id: string, + tag: string, + metadata: unknown, + agentState: unknown, + namespace: string, + model?: string, + effort?: string, + modelReasoningEffort?: string +): StoredSession { + return db.transaction(() => { + const existing = getSessionByNamespace(db, id, namespace) + if (!existing) { + throw new SessionNotAdoptableError('Session not found') + } + + // Already adopted with this tag — idempotent reload (same as getOrCreate match). + if (existing.tag === tag) { + return existing + } + + if (!isMachineSpawnPreallocatedStub(existing)) { + throw new SessionNotAdoptableError('Session is not a preallocated stub') + } + + if (isArchivedSessionMetadata(existing.metadata)) { + throw new SessionNotAdoptableError('Session is archived') + } + + // New tag must not already belong to another session in this namespace. + const tagOwner = prepareCached(db, + 'SELECT id FROM sessions WHERE tag = ? AND namespace = ? LIMIT 1' + ).get(tag, namespace) as { id: string } | undefined + if (tagOwner && tagOwner.id !== id) { + throw new SessionIdentityConflictError('Session tag is already bound to a different id') + } + + const now = Date.now() + const metadataJson = JSON.stringify(metadata) + const agentStateJson = agentState === null || agentState === undefined ? null : JSON.stringify(agentState) + const stubTag = machineSpawnPreallocTag(id) + + // CAS on the stub tag — concurrent adopt / metadata release cannot win a race. + const changed = prepareCached(db, ` + UPDATE sessions SET + tag = @tag, + metadata = @metadata, + metadata_version = metadata_version + 1, + agent_state = @agent_state, + agent_state_version = agent_state_version + 1, + model = @model, + model_reasoning_effort = @model_reasoning_effort, + effort = @effort, + updated_at = @updated_at, + seq = seq + 1 + WHERE id = @id AND namespace = @namespace AND tag = @stub_tag + `).run({ + id, + namespace, + tag, + stub_tag: stubTag, + metadata: metadataJson, + agent_state: agentStateJson, + model: model ?? null, + model_reasoning_effort: modelReasoningEffort ?? null, + effort: effort ?? null, + updated_at: now, + }) + + if (changed.changes !== 1) { + throw new SessionNotAdoptableError('Session is not a preallocated stub') + } + + const updated = getSessionByNamespace(db, id, namespace) + if (!updated) { + throw new Error('Failed to adopt preallocated session') + } + return updated + })() +} + export function updateSessionMetadata( db: Database, id: string, metadata: unknown, expectedVersion: number, namespace: string, - options?: { touchUpdatedAt?: boolean } + options?: { touchUpdatedAt?: boolean; allowUnarchive?: boolean } ): VersionedUpdateResult { const now = Date.now() const touchUpdatedAt = options?.touchUpdatedAt !== false + const allowUnarchive = options?.allowUnarchive === true try { return db.transaction((): VersionedUpdateResult => { - const priorRow = prepareCached(db, - 'SELECT metadata FROM sessions WHERE id = ? AND namespace = ?' - ).get(id, namespace) as { metadata: string | null } | undefined + const existing = getSessionByNamespace(db, id, namespace) + if (!existing) { + return { result: 'error' } + } - const prior = priorRow ? safeJsonParse(priorRow.metadata) : null - const merged = mergeSessionMetadata(prior, metadata) + const prior = existing.metadata + let merged = mergeSessionMetadata(prior, metadata) - return updateVersionedField({ + // #1911 M1: unauthorized un-archive of hub-archived rows. + // Return success + merge-preserved archive fields — NOT version-mismatch + // or error (both spin forever in CLI updateMetadata backoff). + // Authorized revive uses allowUnarchive (clearSessionArchiveMetadata + // before spawn). Narrow to archivedBy=hub so CLI self-archive still + // transitions to running on clean reopen paths. + if ( + isHubArchivedSessionMetadata(prior) + && !isArchivedSessionMetadata(merged) + && !allowUnarchive + ) { + merged = preserveHubArchiveOnMerged(prior, merged) + } + + const result = updateVersionedField({ db, table: 'sessions', id, @@ -319,6 +466,37 @@ export function updateSessionMetadata( touch_updated_at: touchUpdatedAt ? 1 : 0 } }) + + // Reopen flavors (--existing-session-id) never call adopt; they only + // updateMetadata. Release the machine-spawn stub tag here so live + // sessions are not permanently adoptable (#1911 Overseer Major). + // Skip when the write was a hub-archive preserve (still archived) — + // that is refuse-in-place, not live adopt (#1911 M1). + if ( + result.result === 'success' + && isMachineSpawnPreallocatedStub(existing) + && !isHubArchivedSessionMetadata(merged) + ) { + const liveTag = randomUUID() + prepareCached(db, ` + UPDATE sessions + SET tag = @tag, + updated_at = CASE WHEN @touch_updated_at = 1 THEN @updated_at ELSE updated_at END, + seq = seq + 1 + WHERE id = @id + AND namespace = @namespace + AND tag = @stub_tag + `).run({ + id, + namespace, + tag: liveTag, + stub_tag: existing.tag, + updated_at: now, + touch_updated_at: touchUpdatedAt ? 1 : 0, + }) + } + + return result })() } catch { return { result: 'error' } diff --git a/hub/src/sync/opencodeClear.test.ts b/hub/src/sync/opencodeClear.test.ts index ec1aecb1..193ed3d5 100644 --- a/hub/src/sync/opencodeClear.test.ts +++ b/hub/src/sync/opencodeClear.test.ts @@ -641,6 +641,9 @@ describe('SyncEngine.clearOpenCodeSession', () => { undefined, undefined, // startingMode — not applicable to an OpenCode clear replacement + undefined, + // forkSession / reservedSessionId — clear uses reopen existingSessionId + undefined, undefined ) expect(engine.getSessionByNamespace(replacementSessionId, 'default')?.metadata).toMatchObject({ diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index f8e74e13..5eea422a 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -185,14 +185,28 @@ export class RpcGateway { return await this.sessionRpc(sessionId, RPC_METHODS.SetSessionConfig, config) } - async killSession(sessionId: string): Promise { - await this.sessionRpc(sessionId, RPC_METHODS.KillSession, {}) + async killSession(sessionId: string): Promise<{ pid?: number; processStartMarker?: string }> { + const result = await this.sessionRpc(sessionId, RPC_METHODS.KillSession, {}) + if (!result || typeof result !== 'object') return {} + const pid = (result as { pid?: unknown }).pid + const processStartMarker = (result as { processStartMarker?: unknown }).processStartMarker + return { + ...(typeof pid === 'number' ? { pid } : {}), + ...(typeof processStartMarker === 'string' ? { processStartMarker } : {}), + } } - async stopRunnerSession(machineId: string, sessionId: string): Promise<'stopped' | 'already_gone' | 'still_alive'> { - const result = await this.machineRpc(machineId, RPC_METHODS.StopSession, { sessionId }) + async stopRunnerSession( + machineId: string, + sessionId: string, + opts?: { processStartMarker?: string } + ): Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'> { + const result = await this.machineRpc(machineId, RPC_METHODS.StopSession, { + sessionId, + ...(opts?.processStartMarker ? { processStartMarker: opts.processStartMarker } : {}), + }) const status = result && typeof result === 'object' ? (result as { status?: unknown }).status : undefined - if (status === 'stopped' || status === 'already_gone' || status === 'still_alive') return status + if (status === 'stopped' || status === 'already_gone' || status === 'still_alive' || status === 'unknown') return status throw new Error('Unexpected stop-session response') } @@ -217,10 +231,12 @@ export class RpcGateway { collaborationMode?: CodexCollaborationMode, copilotAgentMode?: CopilotAgentMode, startingMode?: 'remote' | 'pty', - // Hub session id to reuse for this spawn. When set, the runner boots the - // CLI with `--hapi-session-id`, so the child reuses the existing hub - // session row (same id) instead of minting a new one. - forkSession?: boolean + // Hub session id for this spawn (preallocated stub or reopen). Runner + // stamps `--existing-session-id` or `--hapi-session-id` by flavor; the + // latter is adopt-stub (create/getOrCreate with id), not reopen. + forkSession?: boolean, + /** Fresh machine-spawn stub — distinct from reopen existingSessionId. */ + reservedSessionId?: string ): Promise< | { type: 'success'; sessionId: string } | { @@ -228,6 +244,8 @@ export class RpcGateway { message: string code?: 'agent_unavailable' | 'outside_workspace_roots' agent?: AgentFlavor + /** Explicit false = no OS child; stub safe to delete (#1911 B3). */ + childStarted?: boolean } > { try { @@ -248,7 +266,10 @@ export class RpcGateway { permissionMode, serviceTier, existingSessionId, - sessionId: existingSessionId, + reservedSessionId, + // Local HTTP / tracking may still read sessionId; prefer + // reserved stub id, then reopen id. + sessionId: reservedSessionId ?? existingSessionId, collaborationMode, copilotAgentMode, startingMode, @@ -265,15 +286,21 @@ export class RpcGateway { ? obj.code : undefined const unavailableAgent = typeof obj.agent === 'string' ? obj.agent as AgentFlavor : undefined + const childStarted = obj.childStarted === false ? false : undefined return { type: 'error', message: obj.errorMessage, ...(code ? { code } : {}), ...(unavailableAgent ? { agent: unavailableAgent } : {}), + ...(childStarted === false ? { childStarted: false } : {}), } } if (obj.type === 'requestToApproveDirectoryCreation' && typeof obj.directory === 'string') { - return { type: 'error', message: `Directory creation requires approval: ${obj.directory}` } + return { + type: 'error', + message: `Directory creation requires approval: ${obj.directory}`, + childStarted: false, + } } if (typeof obj.error === 'string') { return { type: 'error', message: obj.error } @@ -293,6 +320,8 @@ export class RpcGateway { })() return { type: 'error', message: `Unexpected spawn result: ${details}` } } catch (error) { + // Ambiguous: the machine RPC may have started a child before failing. + // Do not claim childStarted: false — hub keeps the stub. return { type: 'error', message: error instanceof Error ? error.message : String(error) } } } diff --git a/hub/src/sync/sessionCache.ts b/hub/src/sync/sessionCache.ts index 5a83f10c..cba8c5f3 100644 --- a/hub/src/sync/sessionCache.ts +++ b/hub/src/sync/sessionCache.ts @@ -101,6 +101,29 @@ export class SessionCache { return this.refreshSession(stored.id) ?? (() => { throw new Error('Failed to load session') })() } + adoptPreallocatedSession( + id: string, + tag: string, + metadata: unknown, + agentState: unknown, + namespace: string, + model?: string, + effort?: string, + modelReasoningEffort?: string + ): Session { + const stored = this.store.sessions.adoptPreallocatedSession( + id, + tag, + metadata, + agentState, + namespace, + model, + effort, + modelReasoningEffort + ) + return this.refreshSession(stored.id) ?? (() => { throw new Error('Failed to load adopted session') })() + } + /** * After fork hydrate / rewind truncate, re-scan the transcript for the * latest TodoWrite (or clear todos). Bypasses the one-shot backfill flag @@ -1084,7 +1107,8 @@ export class SessionCache { next, session.metadataVersion, session.namespace, - { touchUpdatedAt: false } + // #1911 M1: store rejects un-archive unless hub reopen opts in. + { touchUpdatedAt: false, allowUnarchive: true } ) if (result.result === 'error') { diff --git a/hub/src/sync/sessionModel.test.ts b/hub/src/sync/sessionModel.test.ts index 989649c2..9f3979f5 100644 --- a/hub/src/sync/sessionModel.test.ts +++ b/hub/src/sync/sessionModel.test.ts @@ -580,21 +580,57 @@ describe('session model', () => { _machineId: string, _directory: string, agent: string, - model?: string + model?: string, + _modelReasoningEffort?: string, + _yolo?: boolean, + _sessionType?: string, + _worktreeName?: string, + _resumeSessionId?: string, + _effort?: string, + _permissionMode?: string, + _serviceTier?: string, + existingSessionId?: string, + _collaborationMode?: string, + _copilotAgentMode?: string, + _startingMode?: string, + _forkSession?: boolean, + reservedSessionId?: string ) => { capturedModel = model - return { type: 'success', sessionId: 'spawned-cursor-session' } + return { + type: 'success', + sessionId: reservedSessionId ?? existingSessionId ?? 'spawned-cursor-session', + } } const result = await engine.spawnSession( 'machine-cursor', '/tmp/project', 'cursor', - 'composer-2.5[fast=false]' + 'composer-2.5[fast=false]', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' ) - expect(result).toEqual({ type: 'success', sessionId: 'spawned-cursor-session' }) + expect(result.type).toBe('success') expect(capturedModel).toBe('composer-2.5[fast=false]') + if (result.type === 'success') { + expect(typeof result.sessionId).toBe('string') + expect(result.sessionId.length).toBeGreaterThan(0) + const meta = store.sessions.getSession(result.sessionId)?.metadata as { flavor?: string } | null + expect(meta?.flavor).toBe('cursor') + } } finally { engine.stop() } @@ -2396,9 +2432,9 @@ describe('session model', () => { const result = await engine.reopenSession(session.id, 'default') expect(result).toMatchObject({ type: 'error', message: expect.stringContaining('still active') }) expect(engine.getSessionByNamespace(session.id, 'default')?.active).toBe(true) - // Pi keeps the persisted archive snapshot until bootstrap succeeds, - // so a failed stop never needs to reconstruct it from memory. - expect(engine.getSessionByNamespace(session.id, 'default')?.metadata?.lifecycleState).toBe('archived') + // #1911 M1: reopen clears archive before spawn; a live Pi child that + // failed stop stays active and must not be re-archived from memory. + expect(engine.getSessionByNamespace(session.id, 'default')?.metadata?.lifecycleState).not.toBe('archived') expect(engine.getSessionByNamespace(session.id, 'default')?.metadata?.piResumeAttempt?.state).toBe('quarantined') expect(await engine.reopenSession(session.id, 'default')).toMatchObject({ type: 'error', message: 'Pi resume is already in progress' }) @@ -2450,7 +2486,11 @@ describe('session model', () => { type: 'error', message: 'webhook timeout' }) expect(engine.getSessionByNamespace(session.id, 'default')?.metadata?.piResumeAttempt?.state).toBe('quarantined') - expect(engine.getSessionByNamespace(session.id, 'default')?.metadata?.lifecycleState).toBe('archived') + // #1911 M1: archive cleared before spawn; quarantine refuses reopen + // rollback (rollbackSafe:false). Snapshot lives on the attempt. + expect(engine.getSessionByNamespace(session.id, 'default')?.metadata?.lifecycleState).not.toBe('archived') + expect(engine.getSessionByNamespace(session.id, 'default')?.metadata?.piResumeAttempt?.archiveSnapshot) + .toMatchObject({ lifecycleState: 'archived', archivedBy: 'cli' }) expect(await engine.reopenSession(session.id, 'default')).toMatchObject({ type: 'error', message: 'Pi resume is already in progress' }) diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 56552ed8..e20e0de1 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -32,6 +32,7 @@ import { MessageService, type RetryIndeterminateMessageResult } from './messageS import { createTitleSuggestionService, type TitleSuggestionService } from './titleSuggestion' import { selectForkTranscriptPrefix } from './forkTranscript' import { buildForkSessionSummary } from './forkSessionSummary' +import { isMachineSpawnPreallocatedStub } from '../store/sessions' import { RpcGateway, RpcTargetMissingError, @@ -575,6 +576,7 @@ export class SyncEngine { (session) => session.metadata?.piResumeAttempt?.childSessionId === payload.sid ) const restorePiArchive = ownsPiAttempt && !this.sessionReadyIds.has(payload.sid) + const restorePtyArchive = ownsPtyAttempt && !this.sessionReadyIds.has(payload.sid) const isCursorAcp = before?.metadata?.flavor === 'cursor' && before.metadata.cursorSessionProtocol === 'acp' const shouldRetryDedup = !ownsPiAttempt && !isPiAttemptChild && (!isCursorAcp || this.sessionReadyIds.has(payload.sid)) @@ -598,7 +600,7 @@ export class SyncEngine { void this.clearPiAttemptForEndedSession(payload.sid, restorePiArchive) } if (ownsPtyAttempt) { - void this.writePtyResumeAttempt(payload.sid, before!.namespace, null).catch(() => {}) + void this.writePtyResumeAttempt(payload.sid, before!.namespace, null, restorePtyArchive).catch(() => {}) } // Notify agent-terminal subscribers so the web UI shows a clear @@ -1020,6 +1022,28 @@ export class SyncEngine { ) } + adoptPreallocatedSession( + id: string, + tag: string, + metadata: unknown, + agentState: unknown, + namespace: string, + model?: string, + effort?: string, + modelReasoningEffort?: string + ): Session { + return this.sessionCache.adoptPreallocatedSession( + id, + tag, + metadata, + agentState, + namespace, + model, + effort, + modelReasoningEffort + ) + } + getOrCreateMachine(id: string, metadata: unknown, runnerState: unknown, namespace: string): Machine { return this.machineCache.getOrCreateMachine(id, metadata, runnerState, namespace) } @@ -1604,7 +1628,7 @@ export class SyncEngine { ): Promise { if (spawnAttempted) { const status = await this.rpcGateway.stopRunnerSession(machineId, childId) - if (status === 'still_alive') { + if (status === 'still_alive' || status === 'unknown') { throw new Error('Fork child termination was not confirmed') } } @@ -1707,27 +1731,149 @@ export class SyncEngine { } async archiveSession(sessionId: string): Promise { - // tiann/hapi#916: when the CLI is already gone (e.g. after a - // hub-restart cascade SIGTERMed the runner but the in-memory - // `active` flag has not been reconciled yet) the kill-RPC throws - // and the route used to surface that as HTTP 500. Treat the - // missing target as a benign condition: still flip the session's - // lifecycleState to `archived` in the hub-side metadata so the - // UI does not see a half-cleaned zombie, and continue to mark - // it inactive in the cache. Real RPC errors (timeout, protocol - // failure) still propagate as 5xx. + // tiann/hapi#916 / #1910: KillSession is a session-socket RPC. A missing + // target does not prove the runner child is dead (stale registration, + // mid-reconnect, id rotation on resume). Always fall through to the + // machine-level StopSession RPC when we know a machineId, and refuse + // to archive while the runner reports still_alive / unknown. + let cliUnreachable = false + let killPid: number | undefined + let killProcessStartMarker: string | undefined try { - await this.rpcGateway.killSession(sessionId) + const killResult = (await this.rpcGateway.killSession(sessionId)) ?? {} + killPid = killResult.pid + killProcessStartMarker = killResult.processStartMarker } catch (error) { if (error instanceof RpcTargetMissingError) { - this.sessionCache.markSessionArchivedFromHub(sessionId, 'Archived from hub (CLI unreachable)') + cliUnreachable = true } else { throw error } } + + const sessionMeta = this.sessionCache.getSession(sessionId)?.metadata + const machineId = sessionMeta?.machineId + const runnerSpawned = sessionMeta?.startedBy === 'runner' + || sessionMeta?.startedFromRunner === true + if (machineId && runnerSpawned) { + let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' + try { + status = await this.rpcGateway.stopRunnerSession(machineId, sessionId) + } catch (stopError) { + // Machine RPC missing is NOT proof the detached CLI is gone + // (KillMode=process children survive runner death). Refuse to + // archive on any StopSession failure — including when KillSession + // was also unreachable. Both targets missing still leaves a + // possible live orphan; retry StopSession when the runner + // reconnects (#1911 bot Major). + void stopError + status = 'still_alive' + } + // KillSession acknowledges before cleanupAndExit finishes, and socket + // loss is not exit proof. When the runner cannot find the HAPI id, + // confirm the KillSession-reported OS pid + start marker. + const killPidConfirmable = ( + typeof killPid === 'number' + && killPid > 0 + && typeof killProcessStartMarker === 'string' + && killProcessStartMarker.length > 0 + ) + if (status === 'unknown' && killPidConfirmable) { + try { + status = await this.rpcGateway.stopRunnerSession(machineId, `PID-${killPid}`, { + processStartMarker: killProcessStartMarker, + }) + } catch (pidStopError) { + void pidStopError + status = 'still_alive' + } + } + // Estate dogfood (#1911 / Peer #1820): KillSession often supplies no + // pid+marker when the CLI socket is already gone. If session-id stop + // is unknown, ask the runner about metadata.hostPid as a tombstone — + // without a start marker the runner returns already_gone only when + // the OS pid is dead (alive → unknown; never tree-kills). Refuse + // still_alive / unknown on that confirm. + if (status === 'unknown' && !killPidConfirmable) { + const hostPid = sessionMeta?.hostPid + if (typeof hostPid === 'number' && hostPid > 0) { + try { + status = await this.rpcGateway.stopRunnerSession(machineId, `PID-${hostPid}`) + } catch (hostPidStopError) { + void hostPidStopError + status = 'still_alive' + } + } + } + // Ambiguous machine-spawn keep-stub: startedBy=runner, no hostPid, still + // tagged machine-spawn:. StopSession returns unknown forever (nothing + // tracked). There is no OS child to confirm — allow hub archive so the + // ghost is not permanent while the runner is online (#1911 Opus Major). + // A late-booting child that later hits reopen must not resurrect: CLI + // bootstrapExistingSession refuses archived rows (#1911 cold-read M1). + if (status === 'unknown') { + const stored = this.store.sessions.getSession(sessionId) + if ( + stored + && isMachineSpawnPreallocatedStub(stored) + && !(typeof sessionMeta?.hostPid === 'number' && sessionMeta.hostPid > 0) + ) { + status = 'already_gone' + } + } + if (status === 'still_alive' || status === 'unknown') { + throw new Error('Session process is still running and could not be stopped') + } + } else if (machineId && !runnerSpawned) { + // Terminal / non-runner sessions: KillSession is the primary stop. + // Best-effort machine StopSession when a runner is connected; do not + // refuse archive when no runner exists (#1911 bot Major). + try { + await this.rpcGateway.stopRunnerSession(machineId, sessionId) + } catch { + // ignore — terminal archive proceeds after KillSession + } + } + + // KillSession cleanup writes archive metadata asynchronously; StopSession + // may terminate the CLI mid-flush. If the row is still not archived, + // hub-author the metadata so we do not leave lifecycleState=running. + const lifecycleState = this.sessionCache.getSession(sessionId)?.metadata?.lifecycleState + if (lifecycleState !== 'archived') { + this.sessionCache.markSessionArchivedFromHub( + sessionId, + cliUnreachable + ? 'Archived from hub (CLI unreachable)' + : 'Archived from hub (CLI stopped before archive metadata)' + ) + this.emitCliSessionMetadataUpdate(sessionId) + } this.handleSessionEnd({ sid: sessionId, time: Date.now() }) } + /** + * Broadcast versioned session metadata to CLI sockets in `session:`. + * Mirrors the shape used by update-metadata handlers so ApiSessionClient + * applies the same hub-archived detection path. + */ + private emitCliSessionMetadataUpdate(sessionId: string): void { + const session = this.sessionCache.getSession(sessionId) + if (!session?.metadata) return + if (typeof this.io.of !== 'function') return + const update = { + id: randomUUID(), + seq: Date.now(), + createdAt: Date.now(), + body: { + t: 'update-session' as const, + sid: sessionId, + metadata: { version: session.metadataVersion, value: session.metadata }, + agentState: null as null + } + } + this.io.of('/cli').to(`session:${sessionId}`).emit('update', update) + } + /** * Apply the post-migration metadata flip in hapi.db: * - metadata.cursorSessionProtocol = 'acp' @@ -2032,26 +2178,127 @@ export class SyncEngine { existingSessionId?: string, collaborationMode?: CodexCollaborationMode, copilotAgentMode?: CopilotAgentMode, - startingMode?: 'remote' | 'pty' + startingMode?: 'remote' | 'pty', + // Required for fresh machine spawns so the runner stamps the HAPI id on + // argv before the first webhook (#1911 Major: unreapable window). + namespace?: string ): ReturnType { - return await this.rpcGateway.spawnSession( - machineId, - directory, - agent, - model, - modelReasoningEffort, - yolo, - sessionType, - worktreeName, - resumeSessionId, - effort, - permissionMode, - serviceTier, - existingSessionId, - collaborationMode, - copilotAgentMode, - startingMode - ) + // Fresh machine spawns historically omitted existingSessionId, so + // buildCliArgs could not stamp --hapi-session-id / --existing-session-id. + // A runner restart before the first webhook then left no persisted PID + // map and no argv id — StopSession returned unknown. Preallocate the + // hub row (same pattern as fork / OpenCode clear) and pass that id. + let allocatedSessionId = existingSessionId + let preallocated = false + if (!allocatedSessionId && namespace) { + const machine = this.getMachineByNamespace(machineId, namespace) + ?? this.getMachine(machineId) + allocatedSessionId = randomUUID() + this.sessionCache.getOrCreateSession( + `machine-spawn:${allocatedSessionId}`, + { + path: directory, + host: machine?.metadata?.host ?? 'unknown', + flavor: agent, + machineId, + startedBy: 'runner', + startedFromRunner: true, + }, + null, + namespace, + model, + effort, + modelReasoningEffort, + allocatedSessionId + ) + preallocated = true + } + + let result: Awaited> + try { + result = await this.rpcGateway.spawnSession( + machineId, + directory, + agent, + model, + modelReasoningEffort, + yolo, + sessionType, + worktreeName, + resumeSessionId, + effort, + permissionMode, + serviceTier, + // Fresh prealloc stubs must not go down reopen (--existing-session-id): + // Codex would demand a thread binding that does not exist yet (#1911). + preallocated ? undefined : allocatedSessionId, + collaborationMode, + copilotAgentMode, + startingMode, + undefined, + preallocated ? allocatedSessionId : undefined + ) + } catch (error) { + // Ambiguous post-dispatch failure — keep the stub (child may exist). + if (preallocated && allocatedSessionId) { + return { + type: 'error', + message: error instanceof Error ? error.message : String(error), + } + } + throw error + } + + if (result.type !== 'success' && preallocated && allocatedSessionId) { + const deleteStubIfStillPrealloc = async (): Promise => { + try { + // Session wire type has no tag — read the store row for stub check. + const stored = this.store.sessions.getSession(allocatedSessionId!) + if (!stored || !isMachineSpawnPreallocatedStub(stored)) return + const row = this.sessionCache.refreshSession(allocatedSessionId!) + if (!row) return + if (row.active) { + this.handleSessionEnd({ sid: allocatedSessionId!, time: Date.now(), reason: 'error' }) + } + await this.deleteSession(allocatedSessionId!) + } catch { + // Leave the stub visible rather than claiming cleanup succeeded. + } + } + + // Pre-exec rejection: runner never started an OS child — safe to delete. + if (result.childStarted === false) { + await deleteStubIfStillPrealloc() + return result + } + + // Ambiguous (RPC timeout, post-exec failure, etc.): keep the stub. + // Do NOT call stopRunnerSession — that would kill a healthy late-booting + // CLI — and do NOT deleteSession (ON DELETE CASCADE wipes transcript). + // Matches the throw-path keep-stub policy above (#1911 Critical). + // Archive of these stubs is allowed via isMachineSpawnPreallocatedStub + // hatch in archiveSession (no hostPid → no process to confirm). + return result + } + + // Runner must bind the preallocated id — a divergent success id leaves + // the stub as a silent ghost (#1911 Opus robustness note). + if ( + result.type === 'success' + && preallocated + && allocatedSessionId + && result.sessionId !== allocatedSessionId + ) { + console.warn( + `[spawn] runner reported sessionId ${result.sessionId} but prealloc was ${allocatedSessionId}; treating as error and keeping stub` + ) + return { + type: 'error', + message: `Runner reported unexpected session id ${result.sessionId} (expected ${allocatedSessionId})`, + } + } + + return result } /** @@ -2866,7 +3113,7 @@ export class SyncEngine { if (session.active || operation?.state !== 'reserved' || !machineId) return false try { const status = await this.rpcGateway.stopRunnerSession(machineId, session.id) - if (status === 'still_alive') return false + if (status === 'still_alive' || status === 'unknown') return false return this.abortOpenCodeClearSession( session.id, namespace, operation.replacementSessionId, 'reserved', true ).type === 'success' @@ -3044,6 +3291,12 @@ export class SyncEngine { state: 'resuming', machineId: targetMachine.id, startedAt: Date.now(), + archiveSnapshot: { + lifecycleState: metadata.lifecycleState, + lifecycleStateSince: metadata.lifecycleStateSince, + archivedBy: metadata.archivedBy, + archiveReason: metadata.archiveReason, + }, }) } catch { this.ptyResumeInFlightIds.delete(access.sessionId) @@ -3055,7 +3308,22 @@ export class SyncEngine { this.sessionReadyIds.delete(access.sessionId) } let piResumeSucceeded = false + let ptyResumeSucceeded = false try { + // #1911 M1: clear archived lifecycle immediately before spawn so the + // CLI is not refused / cannot CAS-resurrect. Pi/PTY attempt rows + // above already captured archiveSnapshot while the row was archived. + const liveBeforeSpawn = this.sessionCache.getSessionByNamespace(access.sessionId, namespace) + ?? this.sessionCache.refreshSession(access.sessionId) + if (liveBeforeSpawn?.metadata?.lifecycleState === 'archived') { + try { + await this.sessionCache.clearSessionArchiveMetadata(access.sessionId) + } catch (error) { + const message = error instanceof Error ? error.message : 'Failed to clear archive metadata' + return { type: 'error', message, code: 'resume_failed' } + } + } + const spawnResult = await this.rpcGateway.spawnSession( targetMachine.id, directory, @@ -3153,7 +3421,7 @@ export class SyncEngine { const readyResult = await this.waitForSessionReady(spawnResult.sessionId) if (readyResult !== 'ready') { if (resumedStartingMode === 'pty' && readyResult === 'timeout') { - let status: 'stopped' | 'already_gone' | 'still_alive' + let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' try { status = await this.rpcGateway.stopRunnerSession( targetMachine.id, @@ -3175,7 +3443,10 @@ export class SyncEngine { if (!inactive) { this.ptyResumeQuarantinedIds.add(access.sessionId) try { + const existingAttempt = this.sessionCache.getSession(access.sessionId) + ?.metadata?.ptyResumeAttempt await this.writePtyResumeAttempt(access.sessionId, namespace, { + ...existingAttempt, state: 'quarantined', machineId: targetMachine.id, startedAt: Date.now(), @@ -3205,7 +3476,9 @@ export class SyncEngine { } if (resumedStartingMode === 'pty') { try { - await this.writePtyResumeAttempt(access.sessionId, namespace, null) + // Child stopped after timeout — restore archive from + // the attempt snapshot (clear-before-spawn already ran). + await this.writePtyResumeAttempt(access.sessionId, namespace, null, true) } catch { this.ptyResumeQuarantinedIds.add(access.sessionId) return { @@ -3250,6 +3523,7 @@ export class SyncEngine { try { await this.writePtyResumeAttempt(access.sessionId, namespace, null) this.ptyResumeQuarantinedIds.delete(access.sessionId) + ptyResumeSucceeded = true } catch { this.ptyResumeQuarantinedIds.add(access.sessionId) return { @@ -3264,6 +3538,17 @@ export class SyncEngine { } finally { if (resumedStartingMode === 'pty') { this.ptyResumeInFlightIds.delete(access.sessionId) + // Do not clear a deliberate fail-closed `resuming` marker left + // when quarantine write failed or still_alive refused stop — + // those paths add ptyResumeQuarantinedIds and keep the durable + // attempt (with archiveSnapshot) as the restart-safe truth. + if ( + !ptyResumeSucceeded + && !this.ptyResumeQuarantinedIds.has(access.sessionId) + && this.sessionCache.getSession(access.sessionId)?.metadata?.ptyResumeAttempt?.state === 'resuming' + ) { + await this.writePtyResumeAttempt(access.sessionId, namespace, null, true).catch(() => {}) + } } if (requiresPiNativeReady) { this.piResumeInFlightIds.delete(access.sessionId) @@ -3389,23 +3674,10 @@ export class SyncEngine { lifecycleStateSince: metadata.lifecycleStateSince } - let applied: { cursorSessionProtocol?: 'acp' | 'stream-json' } = {} - // Pi and PTY resumes both reuse the original HAPI row. Keep the archive - // snapshot persisted until the CLI successfully bootstraps that row as - // running; this avoids an inactive, non-archived gap if the Hub restarts - // before spawn — the in-memory snapshot below cannot survive that, and - // ptyResumeAttempt carries no copy of it. The CLI's sessionFactory - // re-stamps lifecycleState='running' on boot and does not carry over - // archivedBy/archiveReason, so the row still leaves the archived state. - if (metadata.flavor !== 'pi' && !isPtyResume) { - try { - applied = await this.sessionCache.clearSessionArchiveMetadata(access.sessionId) - } catch (error) { - const message = error instanceof Error ? error.message : 'Failed to clear archive metadata' - return { type: 'error', message, code: 'metadata_conflict' } - } - } - + // #1911 M1: clear runs inside resumeSession immediately before spawn + // (after Pi/PTY attempt rows capture archiveSnapshot). Hub restart + // between clear and spawn leaves a non-archived inactive row; + // archiveSnapshot still rolls back on resume failure while alive. const resumeResult = await this.resumeSession(access.sessionId, namespace) if (resumeResult.type === 'error') { // Never restore archived metadata over a live Pi child. A live @@ -3421,11 +3693,17 @@ export class SyncEngine { return resumeResult } + const after = this.sessionCache.getSessionByNamespace(access.sessionId, namespace)?.metadata + const cursorSessionProtocol = after?.flavor === 'cursor' + && (after.cursorSessionProtocol === 'acp' || after.cursorSessionProtocol === 'stream-json') + ? after.cursorSessionProtocol + : undefined + return { type: 'success', sessionId: resumeResult.sessionId, resumed: true, - ...(applied.cursorSessionProtocol ? { cursorSessionProtocol: applied.cursorSessionProtocol } : {}) + ...(cursorSessionProtocol ? { cursorSessionProtocol } : {}) } } @@ -3674,7 +3952,7 @@ export class SyncEngine { machineId, startedAt: Date.now(), }) - let status: 'stopped' | 'already_gone' | 'still_alive' + let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' try { status = await this.rpcGateway.stopRunnerSession(machineId, sessionId) } catch { @@ -3684,7 +3962,7 @@ export class SyncEngine { await new Promise((resolve) => setTimeout(resolve, 0)) const session = this.sessionCache.refreshSession(sessionId) ?? this.sessionCache.getSession(sessionId) const attemptClearedByEnd = session?.metadata?.piResumeAttempt === undefined - if (status === 'still_alive') { + if (status === 'still_alive' || status === 'unknown') { if (attemptClearedByEnd) return true return false } @@ -3708,7 +3986,7 @@ export class SyncEngine { startedAt: Date.now(), childSessionId: sessionId, }) - let status: 'stopped' | 'already_gone' | 'still_alive' + let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' try { status = await this.rpcGateway.stopRunnerSession(machineId, sessionId) } catch { @@ -3719,7 +3997,7 @@ export class SyncEngine { const session = this.sessionCache.refreshSession(sessionId) ?? this.sessionCache.getSession(sessionId) const original = this.sessionCache.refreshSession(originalSessionId) ?? this.sessionCache.getSession(originalSessionId) const attemptClearedByEnd = original?.metadata?.piResumeAttempt === undefined - if (status === 'still_alive' && !attemptClearedByEnd) { + if ((status === 'still_alive' || status === 'unknown') && !attemptClearedByEnd) { await this.writePiResumeAttempt(originalSessionId, namespace, { ...existingAttempt, state: 'quarantined', @@ -3808,7 +4086,8 @@ export class SyncEngine { private async writePtyResumeAttempt( sessionId: string, namespace: string, - attempt: PtyResumeAttempt | null + attempt: PtyResumeAttempt | null, + restoreArchive = false ): Promise { for (let i = 0; i < 5; i += 1) { const current = this.sessionCache.getSessionByNamespace(sessionId, namespace) @@ -3816,7 +4095,20 @@ export class SyncEngine { if (!current?.metadata) throw new Error('PTY resume attempt session metadata is unavailable') const next = { ...current.metadata } if (attempt) next.ptyResumeAttempt = attempt - else delete next.ptyResumeAttempt + else { + const snapshot = current.metadata.ptyResumeAttempt?.archiveSnapshot + delete next.ptyResumeAttempt + if (restoreArchive && snapshot) { + if (snapshot.lifecycleState === undefined) delete next.lifecycleState + else next.lifecycleState = snapshot.lifecycleState + if (snapshot.lifecycleStateSince === undefined) delete next.lifecycleStateSince + else next.lifecycleStateSince = snapshot.lifecycleStateSince + if (snapshot.archivedBy === undefined) delete next.archivedBy + else next.archivedBy = snapshot.archivedBy + if (snapshot.archiveReason === undefined) delete next.archiveReason + else next.archiveReason = snapshot.archiveReason + } + } const result = this.store.sessions.updateSessionMetadata( sessionId, next, @@ -3837,20 +4129,22 @@ export class SyncEngine { private async reconcilePersistedPtyResumeAttempt(session: Session): Promise { const attempt = session.metadata?.ptyResumeAttempt if (!attempt) return true - let status: 'stopped' | 'already_gone' | 'still_alive' + let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' try { status = await this.rpcGateway.stopRunnerSession(attempt.machineId, session.id) } catch { return false } - if (status === 'still_alive') return false + if (status === 'still_alive' || status === 'unknown') return false const current = this.sessionCache.getSession(session.id) if (current?.active) { this.handleSessionEnd({ sid: session.id, time: Date.now(), reason: 'error' }) } try { - await this.writePtyResumeAttempt(session.id, session.namespace, null) + // Restore archive from the attempt snapshot when cleaning a failed + // resume (clear-before-spawn already dropped live archive fields). + await this.writePtyResumeAttempt(session.id, session.namespace, null, true) this.ptyResumeQuarantinedIds.delete(session.id) return true } catch { @@ -3863,13 +4157,13 @@ export class SyncEngine { const attempt = session.metadata?.piResumeAttempt if (!attempt) return true const childSessionId = attempt.childSessionId ?? session.id - let status: 'stopped' | 'already_gone' | 'still_alive' + let status: 'stopped' | 'already_gone' | 'still_alive' | 'unknown' try { status = await this.rpcGateway.stopRunnerSession(attempt.machineId, childSessionId) } catch { return false } - if (status === 'still_alive') return false + if (status === 'still_alive' || status === 'unknown') return false const child = this.sessionCache.getSession(childSessionId) if (child?.active) this.handleSessionEnd({ sid: childSessionId, time: Date.now(), reason: 'error' }) diff --git a/hub/src/sync/syncEngineArchiveSession.test.ts b/hub/src/sync/syncEngineArchiveSession.test.ts new file mode 100644 index 00000000..268c9af2 --- /dev/null +++ b/hub/src/sync/syncEngineArchiveSession.test.ts @@ -0,0 +1,388 @@ +import { describe, expect, it, beforeEach } from 'bun:test' +import { Store } from '../store' +import { RpcRegistry } from '../socket/rpcRegistry' +import { SyncEngine } from './syncEngine' +import { RpcTargetMissingError } from './rpcGateway' +import type { SessionCache } from './sessionCache' + +/** + * #1910 / #1705: `killSession` is a session-socket RPC. A missing target does + * not prove the runner child is dead. Archive must always ask the runner via + * `stopRunnerSession` when a machineId is known, and must refuse to archive + * when the runner reports the process still alive (or unknown). + */ +describe('SyncEngine.archiveSession runner reaping (#1910)', () => { + let store: Store + let engine: SyncEngine + const NAMESPACE = 'default' + + function cache(): SessionCache { + return (engine as unknown as { sessionCache: SessionCache }).sessionCache + } + + function insertActiveSession( + tag: string, + machineId?: string, + hostPid?: number, + opts?: { startedBy?: 'runner' | 'terminal'; startedFromRunner?: boolean } + ): string { + const startedBy = opts?.startedBy ?? 'runner' + const created = cache().getOrCreateSession( + tag, + { + path: '/tmp/proj', + host: 'localhost', + flavor: 'claude', + startedBy, + ...(opts?.startedFromRunner !== undefined + ? { startedFromRunner: opts.startedFromRunner } + : startedBy === 'runner' ? { startedFromRunner: true } : {}), + ...(machineId ? { machineId } : {}), + ...(typeof hostPid === 'number' ? { hostPid } : {}), + }, + null, + NAMESPACE + ) + cache().markSessionActive(created.id) + return created.id + } + + function setKillSessionMissingTarget(): void { + ;(engine as unknown as { rpcGateway: { killSession: unknown } }).rpcGateway.killSession = + async () => { throw new RpcTargetMissingError('KillSession', 'handler-not-registered') } + } + + function setKillSessionOk(opts?: { pid?: number; processStartMarker?: string }): void { + ;(engine as unknown as { rpcGateway: { killSession: unknown } }).rpcGateway.killSession = + async () => ({ + ...(typeof opts?.pid === 'number' ? { pid: opts.pid } : {}), + ...(opts?.processStartMarker ? { processStartMarker: opts.processStartMarker } : {}), + }) + } + + beforeEach(() => { + store = new Store(':memory:') + engine = new SyncEngine(store, {} as never, new RpcRegistry(), { broadcast() {} } as never) + }) + + it('does not archive when the runner confirms still_alive after KillSession miss', async () => { + const sessionId = insertActiveSession('sess-still-alive', 'machine-x') + setKillSessionMissingTarget() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => 'still_alive' + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + const session = cache().getSession(sessionId) + expect(session?.active).toBe(true) + expect(session?.metadata?.lifecycleState).not.toBe('archived') + }) + + it('always calls stopRunnerSession after a successful KillSession', async () => { + const sessionId = insertActiveSession('sess-kill-ok', 'machine-x') + setKillSessionOk() + let calledWith: [string, string] | undefined + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async (machineId: string, sid: string) => { + calledWith = [machineId, sid] + return 'already_gone' + } + + await engine.archiveSession(sessionId) + + expect(calledWith).toEqual(['machine-x', sessionId]) + expect(cache().getSession(sessionId)?.active).toBe(false) + // Stop confirmed before CLI could flush — hub must author archive metadata. + expect(cache().getSession(sessionId)?.metadata?.lifecycleState).toBe('archived') + expect(cache().getSession(sessionId)?.metadata?.archivedBy).toBe('hub') + }) + + it('archives once the runner confirms the process is gone', async () => { + const sessionId = insertActiveSession('sess-confirmed-gone', 'machine-x') + setKillSessionMissingTarget() + let calledWith: [string, string] | undefined + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async (machineId: string, sid: string) => { + calledWith = [machineId, sid] + return 'already_gone' + } + + await engine.archiveSession(sessionId) + + expect(calledWith).toEqual(['machine-x', sessionId]) + const session = cache().getSession(sessionId) + expect(session?.active).toBe(false) + expect(session?.metadata?.lifecycleState).toBe('archived') + }) + + it('falls back to archiving when the session has no known machine', async () => { + const sessionId = insertActiveSession('sess-no-machine') + setKillSessionMissingTarget() + let stopRunnerSessionCalled = false + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => { stopRunnerSessionCalled = true; return 'already_gone' } + + await engine.archiveSession(sessionId) + + expect(stopRunnerSessionCalled).toBe(false) + const session = cache().getSession(sessionId) + expect(session?.active).toBe(false) + expect(session?.metadata?.lifecycleState).toBe('archived') + }) + + it('emits Socket.IO update-session when hub-authoring archive without a machine (#1910)', async () => { + const emitted: Array<{ room: string; event: string; payload: unknown }> = [] + const io = { + of: (ns: string) => ({ + to: (room: string) => ({ + emit: (event: string, payload: unknown) => { + if (ns === '/cli') { + emitted.push({ room, event, payload }) + } + } + }) + }) + } + engine = new SyncEngine(store, io as never, new RpcRegistry(), { broadcast() {} } as never) + const sessionId = insertActiveSession('sess-hub-archive-socket') + setKillSessionMissingTarget() + + await engine.archiveSession(sessionId) + + expect(emitted).toHaveLength(1) + expect(emitted[0]?.room).toBe(`session:${sessionId}`) + expect(emitted[0]?.event).toBe('update') + const body = (emitted[0]?.payload as { body: { t: string; metadata: { version: number; value: { archivedBy?: string; lifecycleState?: string } } } }).body + expect(body.t).toBe('update-session') + expect(body.metadata.value.lifecycleState).toBe('archived') + expect(body.metadata.value.archivedBy).toBe('hub') + expect(body.metadata.version).toBeGreaterThan(0) + }) + + it('does NOT archive when both KillSession and machine StopSession targets are missing', async () => { + // #1911 bot Major: both RPC targets missing is not proof the detached + // CLI exited (KillMode=process orphans survive). Keep the row + // unconfirmed until StopSession can run after the runner reconnects. + const sessionId = insertActiveSession('sess-machine-unreachable', 'machine-x') + setKillSessionMissingTarget() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => { throw new RpcTargetMissingError('StopSession', 'handler-not-registered') } + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + const session = cache().getSession(sessionId) + expect(session?.active).toBe(true) + expect(session?.metadata?.lifecycleState).not.toBe('archived') + }) + + it('does NOT archive when machine StopSession is missing but KillSession was reachable', async () => { + // Machine socket alone missing is not proof the detached child is gone + // (KillMode=process). KillSession succeeded → refuse without confirm. + const sessionId = insertActiveSession('sess-machine-only-missing', 'machine-x') + setKillSessionOk() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => { throw new RpcTargetMissingError('StopSession', 'handler-not-registered') } + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + const session = cache().getSession(sessionId) + expect(session?.active).toBe(true) + expect(session?.metadata?.lifecycleState).not.toBe('archived') + }) + + it('does NOT archive when the runner reports unknown after KillSession miss', async () => { + const sessionId = insertActiveSession('sess-unknown-to-runner', 'machine-x') + setKillSessionMissingTarget() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => 'unknown' + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + const session = cache().getSession(sessionId) + expect(session?.active).toBe(true) + expect(session?.metadata?.lifecycleState).not.toBe('archived') + }) + + it('does NOT archive when KillSession succeeded but StopSession stays unknown without a confirmable pid', async () => { + // KillSession ack alone is not exit proof; without a pid the runner + // cannot confirm termination of an untracked CLI (#1910). + const sessionId = insertActiveSession('sess-kill-ok-unknown-no-pid', 'machine-x') + setKillSessionOk() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => 'unknown' + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + const session = cache().getSession(sessionId) + expect(session?.active).toBe(true) + expect(session?.metadata?.lifecycleState).not.toBe('archived') + }) + + it('does NOT archive when KillSession pid confirm lacks a start marker (PID reuse guard)', async () => { + const sessionId = insertActiveSession('sess-kill-ok-pid-no-marker', 'machine-x') + setKillSessionOk({ pid: 4242 }) + const stopCalls: Array<{ sid: string; marker?: string }> = [] + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async (_machineId: string, sid: string, opts?: { processStartMarker?: string }) => { + stopCalls.push({ sid, marker: opts?.processStartMarker }) + return 'unknown' + } + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + // Without a marker, do not attempt the raw-PID confirm kill. + expect(stopCalls).toEqual([{ sid: sessionId, marker: undefined }]) + expect(cache().getSession(sessionId)?.active).toBe(true) + }) + + it('does NOT archive when KillSession pid confirm still reports unknown (socket drop is not exit)', async () => { + const sessionId = insertActiveSession('sess-kill-ok-pid-unknown', 'machine-x') + setKillSessionOk({ pid: 4242, processStartMarker: 'started-at-1' }) + const stopCalls: Array<{ sid: string; marker?: string }> = [] + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async (_machineId: string, sid: string, opts?: { processStartMarker?: string }) => { + stopCalls.push({ sid, marker: opts?.processStartMarker }) + return 'unknown' + } + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + expect(stopCalls).toEqual([ + { sid: sessionId, marker: undefined }, + { sid: 'PID-4242', marker: 'started-at-1' }, + ]) + const session = cache().getSession(sessionId) + expect(session?.active).toBe(true) + expect(session?.metadata?.lifecycleState).not.toBe('archived') + }) + + it('archives when KillSession pid confirm returns already_gone after session-id unknown', async () => { + const sessionId = insertActiveSession('sess-kill-ok-pid-gone', 'machine-x') + setKillSessionOk({ pid: 4242, processStartMarker: 'started-at-1' }) + const stopCalls: Array<{ sid: string; marker?: string }> = [] + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async (_machineId: string, sid: string, opts?: { processStartMarker?: string }) => { + stopCalls.push({ sid, marker: opts?.processStartMarker }) + return sid.startsWith('PID-') ? 'already_gone' : 'unknown' + } + + await engine.archiveSession(sessionId) + + expect(stopCalls).toEqual([ + { sid: sessionId, marker: undefined }, + { sid: 'PID-4242', marker: 'started-at-1' }, + ]) + expect(cache().getSession(sessionId)?.active).toBe(false) + }) + + it('archives via metadata.hostPid tombstone when KillSession supplies no confirmable pid (#1911 dogfood)', async () => { + // Peer #1820 estate gap: StopSession(hapiId)=unknown, process already dead, + // KillSession missed — hub must check metadata.hostPid before 409. + const sessionId = insertActiveSession('sess-hostpid-tombstone', 'machine-x', 3704400) + setKillSessionMissingTarget() + const stopCalls: Array<{ sid: string; marker?: string }> = [] + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async (_machineId: string, sid: string, opts?: { processStartMarker?: string }) => { + stopCalls.push({ sid, marker: opts?.processStartMarker }) + return sid === 'PID-3704400' ? 'already_gone' : 'unknown' + } + + await engine.archiveSession(sessionId) + + expect(stopCalls).toEqual([ + { sid: sessionId, marker: undefined }, + { sid: 'PID-3704400', marker: undefined }, + ]) + expect(cache().getSession(sessionId)?.active).toBe(false) + expect(cache().getSession(sessionId)?.metadata?.lifecycleState).toBe('archived') + }) + + it('does NOT archive when metadata.hostPid confirm reports still_alive', async () => { + const sessionId = insertActiveSession('sess-hostpid-alive', 'machine-x', 3704400) + setKillSessionMissingTarget() + const stopCalls: string[] = [] + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async (_machineId: string, sid: string) => { + stopCalls.push(sid) + return sid === 'PID-3704400' ? 'still_alive' : 'unknown' + } + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + expect(stopCalls).toEqual([sessionId, 'PID-3704400']) + expect(cache().getSession(sessionId)?.active).toBe(true) + expect(cache().getSession(sessionId)?.metadata?.lifecycleState).not.toBe('archived') + }) + + it('does NOT archive when StopSession fails ambiguously', async () => { + const sessionId = insertActiveSession('sess-machine-ambiguous-failure', 'machine-x') + setKillSessionMissingTarget() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => { throw new Error('ack timeout') } + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + + const session = cache().getSession(sessionId) + expect(session?.active).toBe(true) + expect(session?.metadata?.lifecycleState).not.toBe('archived') + }) + + it('archives a terminal session when no runner is connected', async () => { + const sessionId = insertActiveSession('sess-terminal-no-runner', 'machine-x', undefined, { + startedBy: 'terminal', + }) + setKillSessionOk() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => { throw new Error('machine offline') } + + await engine.archiveSession(sessionId) + + expect(cache().getSession(sessionId)?.active).toBe(false) + expect(cache().getSession(sessionId)?.metadata?.lifecycleState).toBe('archived') + }) + + it('archives a never-started machine-spawn stub when StopSession returns unknown (no hostPid)', async () => { + // #1911 Opus Major: keep-stub after ambiguous spawn has startedBy=runner, + // no hostPid → StopSession unknown forever while runner online. + const stubId = crypto.randomUUID() + const created = cache().getOrCreateSession( + `machine-spawn:${stubId}`, + { + path: '/tmp/proj', + host: 'localhost', + flavor: 'claude', + startedBy: 'runner', + startedFromRunner: true, + machineId: 'machine-x', + }, + null, + NAMESPACE, + undefined, + undefined, + undefined, + stubId + ) + cache().markSessionActive(created.id) + expect(created.id).toBe(stubId) + expect(store.sessions.getSession(stubId)?.tag).toBe(`machine-spawn:${stubId}`) + + setKillSessionMissingTarget() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => 'unknown' + + await engine.archiveSession(stubId) + + expect(cache().getSession(stubId)?.active).toBe(false) + expect(cache().getSession(stubId)?.metadata?.lifecycleState).toBe('archived') + }) + + it('does NOT archive a non-stub runner session on unknown without hostPid', async () => { + const sessionId = insertActiveSession('sess-live-unknown-no-pid', 'machine-x') + setKillSessionMissingTarget() + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }).rpcGateway.stopRunnerSession = + async () => 'unknown' + + await expect(engine.archiveSession(sessionId)).rejects.toThrow() + expect(cache().getSession(sessionId)?.active).toBe(true) + }) +}) diff --git a/hub/src/sync/syncEngineReopenPreservesPtyId.test.ts b/hub/src/sync/syncEngineReopenPreservesPtyId.test.ts index 1f328d3b..0c78cf7a 100644 --- a/hub/src/sync/syncEngineReopenPreservesPtyId.test.ts +++ b/hub/src/sync/syncEngineReopenPreservesPtyId.test.ts @@ -131,15 +131,12 @@ describe('SyncEngine reopen/resume PTY session id preservation', () => { - it('keeps the archive snapshot persisted across a PTY reopen so a hub restart can still recover it', async () => { - // The snapshot used for rollback lives only in memory, so clearing the - // archive metadata before the resume is durably recorded leaves an - // inactive, non-archived ghost row if the hub restarts in between. The - // CLI's sessionFactory re-stamps lifecycleState='running' on boot (and - // drops archivedBy/archiveReason, which it never preserves), so keeping - // the snapshot until then is safe — this is the same reason Pi defers it. + it('clears archive metadata on PTY reopen before spawn (#1911 M1)', async () => { + // Hub store rejects un-archive without allowUnarchive, so reopen must + // clear archive before spawn (same as non-PTY). Attempt row carries + // archiveSnapshot for rollback / quarantine durability. const sessionId = insertSession( - 'pty-session-archive-durable', + 'pty-session-archive-clear', baseMetadata({ lifecycleState: 'archived', archivedBy: 'hub', archiveReason: 'inactivity' }), { startingMode: 'pty' } ).id @@ -148,11 +145,110 @@ describe('SyncEngine reopen/resume PTY session id preservation', () => { expect(result).toEqual({ type: 'success', sessionId, resumed: true }) const metadata = store.sessions.getSession(sessionId)?.metadata as Record | undefined + expect(metadata?.lifecycleState).not.toBe('archived') + expect(metadata?.archivedBy).toBeUndefined() + expect(metadata?.archiveReason).toBeUndefined() + }) + + it('keeps archiveSnapshot on PTY quarantine after clear-before-spawn (#1911 Major 2)', async () => { + // Clear-before-spawn + rollbackSafe:false must not lose archive fields — + // they live on ptyResumeAttempt.archiveSnapshot (mirror Pi). + const sessionId = insertSession( + 'pty-session-archive-durable', + baseMetadata({ lifecycleState: 'archived', archivedBy: 'hub', archiveReason: 'inactivity' }), + { startingMode: 'pty' } + ).id + ;(engine as any).rpcGateway.spawnSession = async () => { + engine.handleSessionAlive({ sid: sessionId, time: Date.now() }) + return { type: 'success', sessionId } + } + ;(engine as any).waitForSessionReady = async () => 'timeout' + ;(engine as any).rpcGateway.stopRunnerSession = async () => 'still_alive' + + const first = await engine.reopenSession(sessionId, NAMESPACE) + + expect(first).toMatchObject({ type: 'error', code: 'resume_failed', rollbackSafe: false }) + const metadata = engine.getSessionByNamespace(sessionId, NAMESPACE)?.metadata as any + expect(metadata?.lifecycleState).not.toBe('archived') + expect(metadata?.ptyResumeAttempt).toMatchObject({ + state: 'quarantined', + machineId: 'machine-x', + archiveSnapshot: { + lifecycleState: 'archived', + archivedBy: 'hub', + archiveReason: 'inactivity', + }, + }) + }) + + it('restores archive from PTY archiveSnapshot when a failed resume child is gone', async () => { + // Clear-before-spawn drops live archive fields; when the child is then + // confirmed gone, writePtyResumeAttempt(..., restoreArchive) must put + // them back from the attempt snapshot (mirror Pi). + const sessionId = insertSession( + 'pty-session-archive-restore', + baseMetadata({ lifecycleState: 'archived', archivedBy: 'hub', archiveReason: 'inactivity' }), + { startingMode: 'pty' } + ).id + ;(engine as any).rpcGateway.spawnSession = async () => ({ type: 'success', sessionId }) + ;(engine as any).waitForSessionActive = async () => false + ;(engine as any).rpcGateway.stopRunnerSession = async () => 'already_gone' + + const result = await engine.reopenSession(sessionId, NAMESPACE) + + expect(result).toMatchObject({ type: 'error', code: 'resume_failed' }) + expect((engine.getSessionByNamespace(sessionId, NAMESPACE)?.metadata as any)?.ptyResumeAttempt) + .toBeUndefined() + const metadata = engine.getSessionByNamespace(sessionId, NAMESPACE)?.metadata as any expect(metadata?.lifecycleState).toBe('archived') expect(metadata?.archivedBy).toBe('hub') expect(metadata?.archiveReason).toBe('inactivity') }) + it('restores archive from a persisted PTY quarantine snapshot when the child is already gone', async () => { + const sessionId = insertSession( + 'pty-session-archive-restore-persisted', + baseMetadata({ + lifecycleState: 'running', + ptyResumeAttempt: { + state: 'quarantined', + machineId: 'machine-x', + startedAt: 1, + archiveSnapshot: { + lifecycleState: 'archived', + lifecycleStateSince: 100, + archivedBy: 'hub', + archiveReason: 'inactivity', + }, + }, + }), + { startingMode: 'pty' } + ).id + engine.handleSessionAlive({ sid: sessionId, time: Date.now() }) + let spawnCalls = 0 + ;(engine as any).rpcGateway.stopRunnerSession = async () => 'already_gone' + ;(engine as any).rpcGateway.spawnSession = async () => { + spawnCalls += 1 + // After reconcile restores archive, reopen continues into resume — + // refuse spawn so we can assert the restored archive stuck. + return { type: 'error', message: 'spawn refused for assert' } + } + + const result = await engine.reopenSession(sessionId, NAMESPACE) + + expect(result).toMatchObject({ type: 'error', message: 'spawn refused for assert' }) + expect(spawnCalls).toBe(1) + const metadata = engine.getSessionByNamespace(sessionId, NAMESPACE)?.metadata as any + // resumeSession clear-before-spawn will have cleared again after the + // reconcile restore; the attempt snapshot must still re-restore on the + // failed spawn finally path. + expect(metadata?.ptyResumeAttempt).toBeUndefined() + expect(metadata?.lifecycleState).toBe('archived') + expect(metadata?.lifecycleStateSince).toBe(100) + expect(metadata?.archivedBy).toBe('hub') + expect(metadata?.archiveReason).toBe('inactivity') + }) + it('stops a same-id PTY child when the active-state barrier times out', async () => { const sessionId = insertSession( 'pty-session-active-timeout', diff --git a/hub/src/sync/syncEngineSpawnPrealloc.test.ts b/hub/src/sync/syncEngineSpawnPrealloc.test.ts new file mode 100644 index 00000000..5b7e586e --- /dev/null +++ b/hub/src/sync/syncEngineSpawnPrealloc.test.ts @@ -0,0 +1,745 @@ +import { describe, expect, it } from 'bun:test' +import { Store } from '../store' +import { RpcRegistry } from '../socket/rpcRegistry' +import { SyncEngine } from './syncEngine' + +/** + * #1911 Major: fresh machine spawns must preallocate a HAPI row id and pass it + * to the runner so buildCliArgs can stamp argv before the first webhook. + */ +describe('SyncEngine.spawnSession preallocates HAPI id for fresh machine spawns', () => { + it('creates a hub row and forwards that id as reservedSessionId', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-prealloc', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + engine.handleMachineAlive({ machineId: 'machine-prealloc', time: Date.now() }) + + let forwardedExistingId: string | undefined + ;(engine as unknown as { rpcGateway: { spawnSession: unknown } }).rpcGateway.spawnSession = + async ( + _machineId: string, + _directory: string, + _agent?: string, + _model?: string, + _modelReasoningEffort?: string, + _yolo?: boolean, + _sessionType?: string, + _worktreeName?: string, + _resumeSessionId?: string, + _effort?: string, + _permissionMode?: string, + _serviceTier?: string, + existingSessionId?: string, + _collaborationMode?: string, + _copilotAgentMode?: string, + _startingMode?: string, + _forkSession?: boolean, + reservedSessionId?: string + ) => { + forwardedExistingId = reservedSessionId ?? existingSessionId + return { type: 'success' as const, sessionId: forwardedExistingId! } + } + + const result = await engine.spawnSession( + 'machine-prealloc', + '/tmp/project', + 'claude', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('success') + expect(typeof forwardedExistingId).toBe('string') + expect(forwardedExistingId!.length).toBeGreaterThan(0) + if (result.type === 'success') { + expect(result.sessionId).toBe(forwardedExistingId!) + } + const row = store.sessions.getSession(forwardedExistingId!) + expect(row?.id).toBe(forwardedExistingId) + const meta = row?.metadata as { flavor?: string; machineId?: string } | null + expect(meta?.flavor).toBe('claude') + expect(meta?.machineId).toBe('machine-prealloc') + } finally { + engine.stop() + } + }) + + it('rejects success when runner reports a different id than the prealloc stub', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-id-mismatch', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + engine.handleMachineAlive({ machineId: 'machine-id-mismatch', time: Date.now() }) + + let reserved: string | undefined + ;(engine as unknown as { rpcGateway: { spawnSession: unknown } }).rpcGateway.spawnSession = + async ( + _m: string, _d: string, _a?: string, _mo?: string, _mr?: string, _y?: boolean, + _st?: string, _wn?: string, _rs?: string, _e?: string, _pm?: string, _svc?: string, + _existing?: string, _cm?: string, _ca?: string, _sm?: string, _fs?: boolean, + reservedSessionId?: string + ) => { + reserved = reservedSessionId + return { type: 'success' as const, sessionId: 'totally-different-id' } + } + + const result = await engine.spawnSession( + 'machine-id-mismatch', + '/tmp/project', + 'claude', + undefined, undefined, undefined, undefined, undefined, undefined, + undefined, undefined, undefined, undefined, undefined, undefined, + undefined, 'default' + ) + + expect(result.type).toBe('error') + expect(typeof reserved).toBe('string') + expect(store.sessions.getSession(reserved!)?.tag).toBe(`machine-spawn:${reserved}`) + } finally { + engine.stop() + } + }) + + it('forwards fresh Codex prealloc as reservedSessionId (not existingSessionId)', async () => { + // #1911 Critical: existingSessionId → reopen → "no Codex thread binding". + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-codex-prealloc', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + engine.handleMachineAlive({ machineId: 'machine-codex-prealloc', time: Date.now() }) + + let forwardedExisting: string | undefined + let forwardedReserved: string | undefined + ;(engine as unknown as { rpcGateway: { spawnSession: unknown } }).rpcGateway.spawnSession = + async ( + _machineId: string, + _directory: string, + _agent?: string, + _model?: string, + _modelReasoningEffort?: string, + _yolo?: boolean, + _sessionType?: string, + _worktreeName?: string, + _resumeSessionId?: string, + _effort?: string, + _permissionMode?: string, + _serviceTier?: string, + existingSessionId?: string, + _collaborationMode?: string, + _copilotAgentMode?: string, + _startingMode?: string, + _forkSession?: boolean, + reservedSessionId?: string + ) => { + forwardedExisting = existingSessionId + forwardedReserved = reservedSessionId + return { type: 'success' as const, sessionId: (reservedSessionId ?? existingSessionId)! } + } + + const result = await engine.spawnSession( + 'machine-codex-prealloc', + '/tmp/project', + 'codex', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('success') + expect(forwardedExisting).toBeUndefined() + expect(typeof forwardedReserved).toBe('string') + expect(forwardedReserved!.length).toBeGreaterThan(0) + const row = store.sessions.getSession(forwardedReserved!) + expect(row?.tag).toBe(`machine-spawn:${forwardedReserved}`) + expect((row?.metadata as { flavor?: string } | null)?.flavor).toBe('codex') + } finally { + engine.stop() + } + }) + + it('does not mint a second id when existingSessionId is already supplied', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-reuse', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + const existing = engine.getOrCreateSession( + 'already-reserved', + { path: '/tmp/project', host: 'localhost', flavor: 'opencode', machineId: 'machine-reuse' }, + null, + 'default', + undefined, + undefined, + undefined, + 'already-reserved-id' + ) + + let forwardedExistingId: string | undefined + let callCount = 0 + ;(engine as unknown as { rpcGateway: { spawnSession: unknown } }).rpcGateway.spawnSession = + async ( + ...args: unknown[] + ) => { + callCount++ + forwardedExistingId = (args[17] ?? args[12]) as string | undefined + return { type: 'success' as const, sessionId: forwardedExistingId! } + } + + const result = await engine.spawnSession( + 'machine-reuse', + '/tmp/project', + 'opencode', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + existing.id, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result).toEqual({ type: 'success', sessionId: 'already-reserved-id' }) + expect(forwardedExistingId).toBe('already-reserved-id') + expect(callCount).toBe(1) + } finally { + engine.stop() + } + }) + + it('keeps the preallocated stub on ambiguous spawn failure even if StopSession would say gone', async () => { + // Critical: never call stop+delete on ambiguous errors — stop kills healthy + // late-booting children and delete CASCADE-wipes transcripts. + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-fail', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + + let forwardedExistingId: string | undefined + let stopCalls = 0 + ;(engine as unknown as { rpcGateway: { spawnSession: unknown; stopRunnerSession: unknown } }) + .rpcGateway.spawnSession = async ( + ...args: unknown[] + ) => { + forwardedExistingId = (args[17] ?? args[12]) as string | undefined + return { type: 'error' as const, message: 'spawn blew up' } + } + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }) + .rpcGateway.stopRunnerSession = async () => { + stopCalls++ + return 'already_gone' + } + + const result = await engine.spawnSession( + 'machine-fail', + '/tmp/project', + 'claude', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('error') + expect(typeof forwardedExistingId).toBe('string') + expect(stopCalls).toBe(0) + expect(store.sessions.getSession(forwardedExistingId!)?.id).toBe(forwardedExistingId) + } finally { + engine.stop() + } + }) + + it('keeps the preallocated stub when StopSession cannot confirm the child is gone', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-fail-alive', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + + let forwardedExistingId: string | undefined + let stopCalls = 0 + ;(engine as unknown as { rpcGateway: { spawnSession: unknown; stopRunnerSession: unknown } }) + .rpcGateway.spawnSession = async ( + ...args: unknown[] + ) => { + forwardedExistingId = (args[17] ?? args[12]) as string | undefined + return { type: 'error' as const, message: 'webhook timeout' } + } + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }) + .rpcGateway.stopRunnerSession = async () => { + stopCalls++ + return 'still_alive' + } + + const result = await engine.spawnSession( + 'machine-fail-alive', + '/tmp/project', + 'claude', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('error') + expect(typeof forwardedExistingId).toBe('string') + // Ambiguous spawn: never poke StopSession (would kill a healthy child). + expect(stopCalls).toBe(0) + expect(store.sessions.getSession(forwardedExistingId!)?.id).toBe(forwardedExistingId) + } finally { + engine.stop() + } + }) + + it('deletes the stub on pre-exec rejection without StopSession (childStarted:false)', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-preexec', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + + let forwardedExistingId: string | undefined + let stopCalls = 0 + ;(engine as unknown as { rpcGateway: { spawnSession: unknown; stopRunnerSession: unknown } }) + .rpcGateway.spawnSession = async ( + ...args: unknown[] + ) => { + forwardedExistingId = (args[17] ?? args[12]) as string | undefined + return { + type: 'error' as const, + message: 'claude is not installed', + code: 'agent_unavailable' as const, + childStarted: false as const, + } + } + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }) + .rpcGateway.stopRunnerSession = async () => { + stopCalls++ + return 'unknown' + } + + const result = await engine.spawnSession( + 'machine-preexec', + '/tmp/project', + 'claude', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('error') + expect(stopCalls).toBe(0) + expect(store.sessions.getSession(forwardedExistingId!)).toBeFalsy() + } finally { + engine.stop() + } + }) + + it('deletes the stub on directory-approval pre-exec (childStarted:false)', async () => { + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-dir-approve', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + + let forwardedExistingId: string | undefined + ;(engine as unknown as { rpcGateway: { spawnSession: unknown; stopRunnerSession: unknown } }) + .rpcGateway.spawnSession = async ( + ...args: unknown[] + ) => { + forwardedExistingId = (args[17] ?? args[12]) as string | undefined + return { + type: 'error' as const, + message: 'Directory creation requires approval: /tmp/new-project', + childStarted: false as const, + } + } + + const result = await engine.spawnSession( + 'machine-dir-approve', + '/tmp/new-project', + 'claude', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('error') + expect(store.sessions.getSession(forwardedExistingId!)).toBeFalsy() + } finally { + engine.stop() + } + }) + + it('CLI adopt binds preallocated stub under a new tag (create request path)', async () => { + // End-to-end of the real machine-spawn path: hub preallocates, then CLI + // create with adopt=true overwrites tag/metadata without 409. + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-adopt', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + + let allocatedId: string | undefined + ;(engine as unknown as { rpcGateway: { spawnSession: unknown } }).rpcGateway.spawnSession = + async (...args: unknown[]) => { + allocatedId = (args[17] ?? args[12]) as string | undefined + // Simulate CLI create/adopt before webhook success + const cliTag = crypto.randomUUID() + const adopted = engine.adoptPreallocatedSession( + allocatedId!, + cliTag, + { + path: '/tmp/project', + host: 'localhost', + flavor: 'claude', + machineId: 'machine-adopt', + startedBy: 'runner', + startedFromRunner: true, + hostPid: 999, + }, + { controlledByUser: false }, + 'default', + 'claude-sonnet' + ) + expect(adopted.id).toBe(allocatedId!) + expect((adopted.metadata as { hostPid?: number } | null)?.hostPid).toBe(999) + const stored = store.sessions.getSession(allocatedId!) + expect(stored?.tag).toBe(cliTag) + return { type: 'success' as const, sessionId: allocatedId! } + } + + const result = await engine.spawnSession( + 'machine-adopt', + '/tmp/project', + 'claude', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('success') + expect(typeof allocatedId).toBe('string') + const row = store.sessions.getSession(allocatedId!) + expect(row?.id).toBe(allocatedId) + expect(row?.tag).not.toMatch(/^machine-spawn:/) + } finally { + engine.stop() + } + }) + + it('keeps the stub on ambiguous spawn error (no childStarted:false) without StopSession or delete', async () => { + // Critical: RPC timeout / post-dispatch error must not kill a healthy + // late-booting CLI or CASCADE-delete its transcript (#1911 Overseer). + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-ambiguous', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + + let forwardedExistingId: string | undefined + let stopCalls = 0 + ;(engine as unknown as { rpcGateway: { spawnSession: unknown; stopRunnerSession: unknown } }) + .rpcGateway.spawnSession = async (...args: unknown[]) => { + forwardedExistingId = (args[17] ?? args[12]) as string | undefined + // Same shape as rpcGateway catch/timeout: error, childStarted unset. + return { + type: 'error' as const, + message: 'RPC call timed out after 30000ms', + } + } + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }) + .rpcGateway.stopRunnerSession = async () => { + stopCalls++ + return 'stopped' + } + + const result = await engine.spawnSession( + 'machine-ambiguous', + '/tmp/project', + 'cursor', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('error') + expect(stopCalls).toBe(0) + expect(store.sessions.getSession(forwardedExistingId!)?.id).toBe(forwardedExistingId) + expect(store.sessions.getSession(forwardedExistingId!)?.tag).toMatch(/^machine-spawn:/) + } finally { + engine.stop() + } + }) + + it('does not delete after StopSession when the row is no longer a prealloc stub', async () => { + // Even if an older path called stop+delete, live rows must stay. + const store = new Store(':memory:') + const engine = new SyncEngine( + store, + {} as never, + new RpcRegistry(), + { broadcast() {} } as never + ) + + try { + engine.getOrCreateMachine( + 'machine-live-protect', + { host: 'localhost', platform: 'linux', happyCliVersion: '0.1.0' }, + null, + 'default' + ) + + let allocatedId: string | undefined + ;(engine as unknown as { rpcGateway: { spawnSession: unknown; stopRunnerSession: unknown } }) + .rpcGateway.spawnSession = async (...args: unknown[]) => { + allocatedId = (args[17] ?? args[12]) as string | undefined + // Simulate cursor/codex reopen path: metadata update releases stub tag. + const row = store.sessions.getSession(allocatedId!) + expect(row?.tag).toMatch(/^machine-spawn:/) + store.sessions.updateSessionMetadata( + allocatedId!, + { + ...(row!.metadata as object), + hostPid: 4242, + flavor: 'cursor', + }, + row!.metadataVersion, + 'default' + ) + const after = store.sessions.getSession(allocatedId!) + expect(after?.tag).not.toMatch(/^machine-spawn:/) + return { + type: 'error' as const, + message: 'spawn failed after child started', + // childStarted unset = ambiguous + } + } + ;(engine as unknown as { rpcGateway: { stopRunnerSession: unknown } }) + .rpcGateway.stopRunnerSession = async () => 'stopped' + + const result = await engine.spawnSession( + 'machine-live-protect', + '/tmp/project', + 'cursor', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'default' + ) + + expect(result.type).toBe('error') + expect(store.sessions.getSession(allocatedId!)?.id).toBe(allocatedId) + } finally { + engine.stop() + } + }) +}) diff --git a/hub/src/web/routes/cli.ts b/hub/src/web/routes/cli.ts index d52e9969..17d116ef 100644 --- a/hub/src/web/routes/cli.ts +++ b/hub/src/web/routes/cli.ts @@ -12,7 +12,7 @@ import { readSessionSummaryContractEnabled } from '../../config/sessionSummaryCo import { constantTimeEquals } from '../../utils/crypto' import { parseAccessToken } from '../../utils/accessToken' import type { Machine, Session, SyncEngine } from '../../sync/syncEngine' -import { SessionIdentityConflictError } from '../../store/sessions' +import { SessionIdentityConflictError, SessionNotAdoptableError } from '../../store/sessions' const bearerSchema = z.string().regex(/^Bearer\s+(.+)$/i) @@ -119,16 +119,27 @@ export function createCliRoutes(getSyncEngine: () => SyncEngine | null): Hono SyncEngine | null): Hono SyncEngine | null): Ho return c.json({ error: `${parsed.data.agent.toUpperCase()} only supports remote mode` }, 400) } const startingMode = parsed.data.startingMode + const namespace = c.get('namespace') const result = await engine.spawnSession( machineId, @@ -114,7 +115,8 @@ export function createMachinesRoutes(getSyncEngine: () => SyncEngine | null): Ho undefined, parsed.data.collaborationMode, parsed.data.copilotAgentMode, - startingMode + startingMode, + namespace ) return c.json(result) }) diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 50a707db..4851bb0a 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -26,6 +26,11 @@ export type CreateOrLoadMachineRequest = z.infer { + if (value.adopt === true && !value.id) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'adopt requires id', + path: ['id'], + }) + } }) export type CreateOrLoadSessionRequest = z.infer diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index a35260d8..40da2b47 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -101,6 +101,14 @@ export const MetadataSchema = z.object({ state: z.enum(['resuming', 'quarantined']), machineId: z.string(), startedAt: z.number(), + // Same durability as piResumeAttempt: clear-before-spawn + + // rollbackSafe:false quarantine must not lose archive fields (#1911). + archiveSnapshot: z.object({ + lifecycleState: z.string().optional(), + lifecycleStateSince: z.number().optional(), + archivedBy: z.string().optional(), + archiveReason: z.string().optional(), + }).optional(), }).optional(), tools: z.array(z.string()).optional(), slashCommands: z.array(z.string()).optional(), From 5153ff23c196c7b84818752f7a631420ef0eb25b Mon Sep 17 00:00:00 2001 From: Ananovo Date: Mon, 5 Oct 2026 08:35:53 +0800 Subject: [PATCH 20/34] test(ios): make SessionSplit width assertion responsive (#1907) --- ios/HapiTests/SessionSplitPresentationTests.swift | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/ios/HapiTests/SessionSplitPresentationTests.swift b/ios/HapiTests/SessionSplitPresentationTests.swift index 3dd7cfdd..c6da724c 100644 --- a/ios/HapiTests/SessionSplitPresentationTests.swift +++ b/ios/HapiTests/SessionSplitPresentationTests.swift @@ -94,9 +94,17 @@ final class SessionSplitPresentationTests: XCTestCase { navigation.open("a") try await settle { probe.instances["a"] != nil } let identity = try XCTUnwrap(probe.instances["a"]) - let sidebar = try XCTUnwrap(split.viewController(for: .primary).flatMap { self.findCollection(in: $0.view) }) - XCTAssertGreaterThanOrEqual(sidebar.bounds.width, 280) - XCTAssertLessThanOrEqual(sidebar.bounds.width, 360) + let primaryView = try XCTUnwrap(split.viewController(for: .primary)?.view) + let sidebar = try XCTUnwrap(self.findCollection(in: primaryView)) + let primaryFrame = primaryView.convert(primaryView.bounds, to: window) + let sidebarFrame = sidebar.convert(sidebar.bounds, to: window) + // NavigationSplitView treats the requested column width as a preferred + // range. The balanced iPad style may expand it beyond the 360pt request + // on a wide window, so assert the actual responsive invariant instead + // of coupling the test to one UIKit measurement or OS release. + XCTAssertEqual(sidebarFrame.width, primaryFrame.width, accuracy: 1) + XCTAssertGreaterThanOrEqual(primaryFrame.width, 280) + XCTAssertLessThanOrEqual(primaryFrame.width, window.bounds.width / 2) list.selectMachine("debian") try await settle { list.rows.map(\.id) == ["b"] } From c2d2cfe6f84fa20628ad8c394f14ce19fce9754f Mon Sep 17 00:00:00 2001 From: Dave Rapin Date: Mon, 5 Oct 2026 05:09:07 -0400 Subject: [PATCH 21/34] Add 130% app font size (#1975) --- .../settings/SettingsPrimitives.tsx | 10 ++-- web/src/hooks/useFontScale.test.ts | 47 +++++++++++++++++++ web/src/hooks/useFontScale.ts | 5 +- web/src/routes/settings/display.tsx | 2 +- 4 files changed, 56 insertions(+), 8 deletions(-) create mode 100644 web/src/hooks/useFontScale.test.ts diff --git a/web/src/components/settings/SettingsPrimitives.tsx b/web/src/components/settings/SettingsPrimitives.tsx index 4bc32f91..610b906c 100644 --- a/web/src/components/settings/SettingsPrimitives.tsx +++ b/web/src/components/settings/SettingsPrimitives.tsx @@ -82,13 +82,13 @@ export function SettingsChoiceGroup(props: { value: T options: ReadonlyArray<{ value: T; label: string; description?: string }> onChange: (value: T) => void - columns?: 2 | 4 | 5 + columns?: 2 | 4 | 5 | 6 }) { - const columns = props.columns === 5 ? 'grid-cols-5' : props.columns === 4 ? 'grid-cols-2 sm:grid-cols-4' : 'grid-cols-2' + const columns = props.columns === 6 ? 'grid-cols-6' : props.columns === 5 ? 'grid-cols-5' : props.columns === 4 ? 'grid-cols-2 sm:grid-cols-4' : 'grid-cols-2' return ( -
+
-
+
{props.options.map((option) => { const selected = props.value === option.value return ( @@ -98,7 +98,7 @@ export function SettingsChoiceGroup(props: { role="radio" aria-checked={selected} onClick={() => props.onChange(option.value)} - className={`min-w-0 rounded-lg border px-2 py-2 text-center text-sm transition-colors ${selected + className={`min-w-0 rounded-lg border ${props.columns === 6 ? 'px-0 text-xs tracking-tight sm:text-sm sm:tracking-normal' : 'px-2 text-sm'} py-2 text-center transition-colors ${selected ? 'border-[var(--app-link)] bg-[var(--app-subtle-bg)] text-[var(--app-link)]' : 'border-[var(--app-border)] text-[var(--app-fg)] hover:bg-[var(--app-subtle-bg)]'}`} > diff --git a/web/src/hooks/useFontScale.test.ts b/web/src/hooks/useFontScale.test.ts new file mode 100644 index 00000000..35882a80 --- /dev/null +++ b/web/src/hooks/useFontScale.test.ts @@ -0,0 +1,47 @@ +import { act, renderHook } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { getFontScaleOptions, initializeFontScale, useFontScale } from './useFontScale' + +describe('useFontScale', () => { + beforeEach(() => { + window.localStorage.clear() + }) + + afterEach(() => { + document.documentElement.style.removeProperty('--app-font-scale') + }) + + it('offers 130% alongside the existing sizes', () => { + expect(getFontScaleOptions()).toEqual([ + { value: 0.8, label: '80%' }, + { value: 0.9, label: '90%' }, + { value: 1, label: '100%' }, + { value: 1.1, label: '110%' }, + { value: 1.2, label: '120%' }, + { value: 1.3, label: '130%' }, + ]) + }) + + it.each([1.3] as const)('applies scale %s and restores it on startup and remount', (scale) => { + const { result, unmount } = renderHook(() => useFontScale()) + act(() => result.current.setFontScale(scale)) + + expect(document.documentElement.style.getPropertyValue('--app-font-scale')).toBe(String(scale)) + expect(window.localStorage.getItem('hapi-font-scale')).toBe(String(scale)) + unmount() + + document.documentElement.style.removeProperty('--app-font-scale') + initializeFontScale() + expect(document.documentElement.style.getPropertyValue('--app-font-scale')).toBe(String(scale)) + + const restored = renderHook(() => useFontScale()) + expect(restored.result.current.fontScale).toBe(scale) + restored.unmount() + }) + + it('falls back to 100% for an unsupported stored scale', () => { + window.localStorage.setItem('hapi-font-scale', '1.4') + initializeFontScale() + expect(document.documentElement.style.getPropertyValue('--app-font-scale')).toBe('1') + }) +}) diff --git a/web/src/hooks/useFontScale.ts b/web/src/hooks/useFontScale.ts index b4b038bc..976d3322 100644 --- a/web/src/hooks/useFontScale.ts +++ b/web/src/hooks/useFontScale.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useLayoutEffect, useState } from 'react' -export type FontScale = 0.8 | 0.9 | 1 | 1.1 | 1.2 +export type FontScale = 0.8 | 0.9 | 1 | 1.1 | 1.2 | 1.3 export function getFontScaleOptions(): ReadonlyArray<{ value: FontScale; label: string }> { return [ @@ -9,6 +9,7 @@ export function getFontScaleOptions(): ReadonlyArray<{ value: FontScale; label: { value: 1, label: '100%' }, { value: 1.1, label: '110%' }, { value: 1.2, label: '120%' }, + { value: 1.3, label: '130%' }, ] } @@ -57,7 +58,7 @@ function safeRemoveItem(key: string): void { function parseFontScale(raw: string | null): FontScale { const value = Number(raw) - if (value === 0.8 || value === 0.9 || value === 1 || value === 1.1 || value === 1.2) { + if (value === 0.8 || value === 0.9 || value === 1 || value === 1.1 || value === 1.2 || value === 1.3) { return value } return 1 diff --git a/web/src/routes/settings/display.tsx b/web/src/routes/settings/display.tsx index 92f23f50..5c71ca24 100644 --- a/web/src/routes/settings/display.tsx +++ b/web/src/routes/settings/display.tsx @@ -171,7 +171,7 @@ export default function SettingsDisplayPage() { - + From d3d8bf2620b9ccf08a7c3267fc975c28f9e4c465 Mon Sep 17 00:00:00 2001 From: Matvey Rudoy <75200069+mrudybtw@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:12:57 +0300 Subject: [PATCH 22/34] feat(ios): add Russian locale (#1964) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(ios): add Russian locale Add Russian translations to Localizable.xcstrings for all 591 catalog entries (reusing matching Android translations and translating the rest); zh-Hans and format placeholders are preserved. * fix(ios): make Russian selectable and use correct plural forms - add AppLanguage.russian ("ru"), its display name, the AppleLanguages override, and register ru in the Xcode project's knownRegions so the language picker can actually select Russian - add Russian one/few/many/other plural variations for %lld sessions, %lld attachments and %@, %lld sessions - use count-agnostic phrasing for the other dynamic counts (tools, edits, lines, chars, findings, notes, queued messages, questions, ...) - correct Input/Output to Ввод/Вывод - cover the new language case in ThemePrefsTests * fix(ios): use Russian plural forms for the remaining count labels * fix(ios): pass the step count to the plural localization * fix(ios): pass tool counts to the plural localization * fix(ios): keep the singular English tool-group labels --------- Co-authored-by: mrudy --- ios/Hapi.xcodeproj/project.pbxproj | 1 + .../Chat/Blocks/ToolCallBlockView.swift | 2 +- .../Chat/Blocks/ToolGroupBlockView.swift | 23 +- ios/Hapi/Features/Settings/SettingsView.swift | 2 + ios/Hapi/Resources/Localizable.xcstrings | 3762 +++++++++++++++++ .../HapiClient/Settings/SettingsPrefs.swift | 2 + .../Settings/ThemePrefsTests.swift | 5 + 7 files changed, 3788 insertions(+), 9 deletions(-) diff --git a/ios/Hapi.xcodeproj/project.pbxproj b/ios/Hapi.xcodeproj/project.pbxproj index 489c1dd2..76a2a6bc 100644 --- a/ios/Hapi.xcodeproj/project.pbxproj +++ b/ios/Hapi.xcodeproj/project.pbxproj @@ -248,6 +248,7 @@ en, Base, "zh-Hans", + ru, ); mainGroup = A100000000000000000000A1; minimizedProjectReferenceProxies = 1; diff --git a/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift b/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift index ce5ea01d..c67d40c5 100644 --- a/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift +++ b/ios/Hapi/Features/Chat/Blocks/ToolCallBlockView.swift @@ -48,7 +48,7 @@ struct ToolCallBlockView: View { if opensToolProcess(block) { Button { openTool?(block) } label: { Label( - String(format: String(localized: "View process · %lld steps"), Int64(block.children.count)), + String(localized: "View process · \(block.children.count) steps"), systemImage: "arrow.right" ) .font(typography.captionFont) diff --git a/ios/Hapi/Features/Chat/Blocks/ToolGroupBlockView.swift b/ios/Hapi/Features/Chat/Blocks/ToolGroupBlockView.swift index 295be5d0..a89ce181 100644 --- a/ios/Hapi/Features/Chat/Blocks/ToolGroupBlockView.swift +++ b/ios/Hapi/Features/Chat/Blocks/ToolGroupBlockView.swift @@ -31,16 +31,23 @@ struct ToolGroupPresentation: Identifiable, Equatable { let parts = ToolGroupActionKind.allCases.compactMap { kind -> String? in let count = countsByKind[kind] ?? 0 guard count > 0 else { return nil } - let format: String + // Interpolated lookups pass the count to the catalog so the Russian + // plural variations are selected; the explicit singular keys keep + // the English labels grammatical. switch kind { - case .read: format = count == 1 ? String(localized: "1 read") : String(localized: "%lld reads") - case .search: format = count == 1 ? String(localized: "1 search") : String(localized: "%lld searches") - case .command: format = count == 1 ? String(localized: "1 command") : String(localized: "%lld commands") - case .mutation: format = count == 1 ? String(localized: "1 edit") : String(localized: "%lld edits") - case .web: format = count == 1 ? String(localized: "1 web request") : String(localized: "%lld web requests") - case .other: format = count == 1 ? String(localized: "1 other tool") : String(localized: "%lld other tools") + case .read: + return count == 1 ? String(localized: "1 read") : String(localized: "\(count) reads") + case .search: + return count == 1 ? String(localized: "1 search") : String(localized: "\(count) searches") + case .command: + return count == 1 ? String(localized: "1 command") : String(localized: "\(count) commands") + case .mutation: + return count == 1 ? String(localized: "1 edit") : String(localized: "\(count) edits") + case .web: + return count == 1 ? String(localized: "1 web request") : String(localized: "\(count) web requests") + case .other: + return count == 1 ? String(localized: "1 other tool") : String(localized: "\(count) other tools") } - return String(format: format, Int64(count)) } return parts.joined(separator: " · ") } diff --git a/ios/Hapi/Features/Settings/SettingsView.swift b/ios/Hapi/Features/Settings/SettingsView.swift index f2db4525..789c7670 100644 --- a/ios/Hapi/Features/Settings/SettingsView.swift +++ b/ios/Hapi/Features/Settings/SettingsView.swift @@ -165,6 +165,8 @@ struct SettingsView: View { UserDefaults.standard.set(["en"], forKey: "AppleLanguages") case .simplifiedChinese: UserDefaults.standard.set(["zh-Hans"], forKey: "AppleLanguages") + case .russian: + UserDefaults.standard.set(["ru"], forKey: "AppleLanguages") } } ) diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 489dfb56..fb39a060 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -4,6 +4,12 @@ "%@\n\nOpen a session chat to browse its files." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@\n\nОткройте чат сессии, чтобы просмотреть её файлы." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -15,6 +21,12 @@ "%@ (%lld edits)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ (правки: %lld)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -26,6 +38,12 @@ "%@ (+%lld more)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ (+ещё %lld)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -37,6 +55,12 @@ "%@ (optional)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ (необязательно)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -48,6 +72,12 @@ "%@ is over the 50 MB upload limit" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ превышает лимит загрузки 50 МБ" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -59,6 +89,12 @@ "%@ log" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Журнал %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -70,6 +106,12 @@ "%@ rejected its stored credentials and was signed out. Pair it again from the hub menu." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ отклонил сохранённые учётные данные, и устройство вышло из аккаунта. Сопрягите его заново из меню хаба." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -81,6 +123,12 @@ "%@ tokens · %lld req · in %@ / out %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Токены: %@ · запросов: %lld · вход %@ / выход %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -97,12 +145,24 @@ "state" : "new", "value" : "%1$@ · %2$@ requests" } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ · %@ запросов" + } } } }, "%@ · %lld requests" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ · запросы: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -132,6 +192,36 @@ } } }, + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@, %lld сессия" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@, %lld сессии" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@, %lld сессий" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@, %lld сессий" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -143,6 +233,12 @@ "%lld Questions" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вопросы: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -154,6 +250,36 @@ "%lld agent steps" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld шаг агента" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld шага агента" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld шагов агента" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld шага агента" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -183,6 +309,36 @@ } } }, + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld вложение" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld вложения" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld вложений" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld вложений" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -194,6 +350,12 @@ "%lld chars" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Символы: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -205,6 +367,36 @@ "%lld commands" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld команда" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld команды" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld команд" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld команды" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -216,6 +408,12 @@ "%lld edits" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Правки: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -227,6 +425,12 @@ "%lld failed tools" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сбойные инструменты: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -238,6 +442,12 @@ "%lld findings" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Замечания: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -249,6 +459,12 @@ "%lld lines" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Строки: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -260,6 +476,36 @@ "%lld new messages ↓" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld новое сообщение ↓" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld новых сообщения ↓" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld новых сообщений ↓" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld новых сообщения ↓" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -271,6 +517,12 @@ "%lld notes" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Заметки: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -282,6 +534,12 @@ "%lld other tools" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Другие инструменты: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -293,6 +551,12 @@ "%lld queued messages" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщения в очереди: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -304,6 +568,36 @@ "%lld reads" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld чтение" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld чтения" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld чтений" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld чтения" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -315,6 +609,12 @@ "%lld requests · in %@ · out %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запросы: %lld · вход %@ · выход %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -326,6 +626,36 @@ "%lld searches" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld поиск" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld поиска" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld поисков" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld поиска" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -355,6 +685,36 @@ } } }, + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld сессия" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld сессии" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld сессий" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld сессий" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -366,6 +726,12 @@ "%lld staged · %lld unstaged" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld в индексе · %lld вне индекса" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -377,6 +743,12 @@ "%lld tool calls" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вызовы инструментов: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -388,6 +760,12 @@ "%lld tools" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Инструменты: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -399,6 +777,12 @@ "%lld web requests" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Веб-запросы: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -410,6 +794,12 @@ "(empty)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "(пусто)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -421,6 +811,12 @@ "0 tokens" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "0 токенов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -432,6 +828,12 @@ "1 agent step" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 шаг агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -443,6 +845,12 @@ "1 command" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 команда" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -454,6 +862,12 @@ "1 edit" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 правка" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -465,6 +879,12 @@ "1 finding" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 замечание" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -476,6 +896,12 @@ "1 new message ↓" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 новое сообщение ↓" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -487,6 +913,12 @@ "1 note" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 заметка" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -498,6 +930,12 @@ "1 other tool" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 другой инструмент" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -509,6 +947,12 @@ "1 queued message" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 сообщение в очереди" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -520,6 +964,12 @@ "1 read" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 чтение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -531,6 +981,12 @@ "1 search" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 поиск" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -542,6 +998,12 @@ "1 tool" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 инструмент" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -553,6 +1015,12 @@ "1 tool call" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 вызов инструмента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -564,6 +1032,12 @@ "1 web request" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 веб-запрос" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -575,6 +1049,12 @@ "30 days" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "30 дней" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -586,6 +1066,12 @@ "7 days" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "7 дней" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -597,6 +1083,12 @@ "A note can hold at most %lld attachments" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Максимум вложений в заметке: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -608,6 +1100,12 @@ "Abort" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Прервать" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -619,6 +1117,12 @@ "About" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "О программе" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -630,6 +1134,12 @@ "Access token" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Токен доступа" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -641,6 +1151,12 @@ "Action failed" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Действие не выполнено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -652,6 +1168,12 @@ "Active" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Активна" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -663,6 +1185,12 @@ "Add Hub" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить хаб" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -674,6 +1202,12 @@ "Add Hub…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить хаб…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -685,6 +1219,12 @@ "Add a note…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить примечание…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -696,6 +1236,12 @@ "Add another hub" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить ещё хаб" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -707,6 +1253,12 @@ "Add attachment" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить вложение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -718,6 +1270,12 @@ "Add photo" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить фото" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -729,6 +1287,12 @@ "Add to send queue" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить в очередь отправки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -740,6 +1304,12 @@ "After" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "После" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -751,6 +1321,12 @@ "Agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Агент" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -762,6 +1338,12 @@ "Agent Mode" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Режим агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -773,6 +1355,12 @@ "Agent process" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Процесс агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -784,6 +1372,12 @@ "Agent: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Агент: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -795,6 +1389,12 @@ "All" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Все" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -806,6 +1406,12 @@ "All Machines" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Все машины" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -817,6 +1423,12 @@ "All time" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "За всё время" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -828,6 +1440,12 @@ "Allow" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Разрешить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -839,6 +1457,12 @@ "Allow all edits" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Разрешить все правки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -850,6 +1474,12 @@ "Allow camera access in Settings to scan the pairing QR, or go back and use manual entry." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Разрешите доступ к камере в Настройках, чтобы сканировать QR для сопряжения, или вернитесь и введите данные вручную." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -861,6 +1491,12 @@ "Allow for this session" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Разрешить для этой сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -872,6 +1508,12 @@ "Already delivered to the agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Уже доставлено агенту" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -883,6 +1525,12 @@ "Already handled elsewhere" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Уже обработано в другом месте" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -894,6 +1542,12 @@ "Already handled elsewhere." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Уже обработано в другом месте." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -905,6 +1559,12 @@ "Already paired with %@ — switched to it." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Уже сопряжено с %@ — переключились на него." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -916,6 +1576,12 @@ "Already queued — couldn't remove the draft. Retry removal only." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Уже в очереди — не удалось удалить черновик. Повторите только удаление." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -927,6 +1593,12 @@ "Answer every question first" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сначала ответьте на все вопросы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -938,6 +1610,12 @@ "Answer every required question first" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сначала ответьте на все обязательные вопросы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -949,6 +1627,12 @@ "Answered" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отвечено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -960,6 +1644,12 @@ "Answers" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ответы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -971,6 +1661,12 @@ "App language" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Язык приложения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -982,6 +1678,12 @@ "App version" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Версия приложения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -993,6 +1695,12 @@ "Appearance" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Оформление" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1004,6 +1712,12 @@ "Append to input" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить к вводу" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1015,6 +1729,12 @@ "Applies after the app is relaunched." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Применится после перезапуска приложения." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1026,6 +1746,12 @@ "Apply changes" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Применить изменения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1037,6 +1763,12 @@ "Applying changes…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Применение изменений…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1048,6 +1780,12 @@ "Archive" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Архивировать" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1059,6 +1797,12 @@ "Archive failed: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось архивировать: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1070,6 +1814,12 @@ "Attach" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Прикрепить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1081,6 +1831,12 @@ "Attachment only" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Только вложение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1092,6 +1848,12 @@ "Attachments are still uploading — wait, or retry/remove the failed ones" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вложения ещё загружаются — подождите либо повторите или удалите неудачные" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1103,6 +1865,12 @@ "Audio recording failed" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка записи звука" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1114,6 +1882,12 @@ "Awaiting approval" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ожидает одобрения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1125,6 +1899,12 @@ "Awaiting response" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ожидание ответа" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1136,6 +1916,12 @@ "Back to chat" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Назад в чат" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1147,6 +1933,12 @@ "Back to latest" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "К последним" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1158,6 +1950,12 @@ "Background task" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Фоновая задача" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1169,6 +1967,12 @@ "Before" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "До" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1180,6 +1984,12 @@ "Beginning of conversation" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Начало разговора" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1191,6 +2001,12 @@ "Binary file not shown" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Двоичный файл не показан" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1202,6 +2018,12 @@ "Binary file — no preview available" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Двоичный файл — предпросмотр недоступен" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1213,6 +2035,12 @@ "Broadcast" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Широковещание" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1224,6 +2052,12 @@ "Browse" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Обзор" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1235,6 +2069,12 @@ "By agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "По агентам" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1246,6 +2086,12 @@ "By model" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "По моделям" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1257,6 +2103,12 @@ "Bypass approvals and sandbox" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Обойти подтверждения и песочницу" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1268,6 +2120,12 @@ "Cache creation" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создание кеша" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1279,6 +2137,12 @@ "Cache hit rate" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Доля попаданий в кеш" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1290,6 +2154,12 @@ "Cache read" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Чтение кеша" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1301,6 +2171,12 @@ "Camera" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Камера" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1312,6 +2188,12 @@ "Camera access denied" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Доступ к камере запрещён" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1323,6 +2205,12 @@ "Cancel" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отмена" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1334,6 +2222,12 @@ "Changes" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Изменения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1345,6 +2239,12 @@ "Chat" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Чат" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1356,6 +2256,12 @@ "Check the connection to your hub and try again." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Проверьте подключение к хабу и попробуйте снова." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1367,6 +2273,12 @@ "Check the hub address. HTTPS is recommended, for example https://hub.example.com." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Проверьте адрес хаба. Рекомендуется HTTPS, например https://hub.example.com." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1378,6 +2290,12 @@ "Checking directory…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Проверка каталога…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1389,6 +2307,12 @@ "Checking hub…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Проверка хаба…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1400,6 +2324,12 @@ "Checking installed Agents…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Проверка установленных агентов…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1411,6 +2341,12 @@ "Choose a session from the sidebar, or start a new one." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выберите сессию на боковой панели или создайте новую." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1422,6 +2358,12 @@ "Choose Directory" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбрать каталог" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1433,6 +2375,12 @@ "Clear Filters" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сбросить фильтры" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1444,6 +2392,12 @@ "Close" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закрыть" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1455,6 +2409,12 @@ "Close agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закрыть агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1466,6 +2426,12 @@ "Close details to approve or answer in the conversation." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закройте детали, чтобы одобрить или ответить в разговоре." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1477,6 +2443,12 @@ "Code review" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ревью кода" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1488,6 +2460,12 @@ "Collaboration Mode" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Режим совместной работы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1499,6 +2477,12 @@ "Collapsed" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Свёрнуто" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1510,6 +2494,12 @@ "Completed" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Завершено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1521,6 +2511,12 @@ "Connecting…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Подключение…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1532,6 +2528,12 @@ "Connection protocol" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Протокол подключения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1543,6 +2545,12 @@ "Connection: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Подключение: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1554,6 +2562,12 @@ "Continue command" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Продолжить команду" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1565,6 +2579,12 @@ "Continue loading history" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Продолжить загрузку истории" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1576,6 +2596,12 @@ "Continue planning" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Продолжить планирование" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1587,6 +2613,12 @@ "Copy" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Копировать" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1598,6 +2630,12 @@ "Copy Contents" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Копировать содержимое" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1609,6 +2647,12 @@ "Copy Path" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Копировать путь" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1620,6 +2664,12 @@ "Copy full content" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Копировать всё содержимое" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1631,6 +2681,12 @@ "Copy input" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Копировать ввод" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1642,6 +2698,12 @@ "Copy result" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Копировать результат" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1653,6 +2715,12 @@ "Copy text" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Копировать текст" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1664,6 +2732,12 @@ "Could not load this dashboard." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить эту панель." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1675,6 +2749,12 @@ "Could not reach the hub" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось связаться с хабом" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1686,6 +2766,12 @@ "Could not reach your hub. Open HAPI to respond." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось связаться с вашим хабом. Откройте HAPI, чтобы ответить." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1697,6 +2783,12 @@ "Could not save" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось сохранить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1708,6 +2800,12 @@ "Could not start recording" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось начать запись" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1719,6 +2817,12 @@ "Could not store the push key." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось сохранить ключ push-уведомлений." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1730,6 +2834,12 @@ "Couldn't attach the file — check the hub connection" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось прикрепить файл — проверьте подключение к хабу" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1741,6 +2851,12 @@ "Couldn't delete the note — check the hub connection" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось удалить заметку — проверьте подключение к хабу" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1752,6 +2868,12 @@ "Couldn't load history. Tap to retry." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить историю. Нажмите, чтобы повторить." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1763,6 +2885,12 @@ "Couldn't load the scratchlist" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить заметки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1774,6 +2902,12 @@ "Couldn't load this session" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить эту сессию" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1785,6 +2919,12 @@ "Couldn't park the draft — check the hub connection" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось отложить черновик — проверьте подключение к хабу" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1796,6 +2936,12 @@ "Couldn't prepare the attachments — retry or remove the failed files" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось подготовить вложения — повторите или удалите неудачные файлы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1807,6 +2953,12 @@ "Couldn't queue the draft — retry" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось поставить черновик в очередь — повторите" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1818,6 +2970,12 @@ "Couldn't read %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось прочитать %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1829,6 +2987,12 @@ "Couldn't read the selected photo" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось прочитать выбранное фото" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1840,6 +3004,12 @@ "Couldn't read the selected video" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось прочитать выбранное видео" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1851,6 +3021,12 @@ "Couldn't refresh — showing saved drafts" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось обновить — показаны сохранённые черновики" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1862,6 +3038,12 @@ "Couldn't remove the attachment — check the hub connection" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось убрать вложение — проверьте подключение к хабу" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1873,6 +3055,12 @@ "Couldn't save the draft — your changes are kept here" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось сохранить черновик — ваши изменения остались здесь" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1884,6 +3072,12 @@ "Couldn't save the note — check the hub connection" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось сохранить заметку — проверьте подключение к хабу" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1895,6 +3089,12 @@ "Create" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создать" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1906,6 +3106,12 @@ "Create Team" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создать команду" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1917,6 +3123,12 @@ "Create a new git worktree next to the repo" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создать новый git worktree рядом с репозиторием" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1928,6 +3140,12 @@ "Create and Make Directory" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создать и создать каталог" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1939,6 +3157,12 @@ "Creating…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создание…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1950,6 +3174,12 @@ "Current Directory" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Текущий каталог" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1961,6 +3191,12 @@ "Custom answer" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Свой ответ" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1972,6 +3208,12 @@ "Daily tokens" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Токены по дням" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1983,6 +3225,12 @@ "Dark" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Тёмная" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -1994,6 +3242,12 @@ "Database" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "База данных" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2005,6 +3259,12 @@ "Default" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "По умолчанию" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2016,6 +3276,12 @@ "Delete" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2027,6 +3293,12 @@ "Delete Team" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить команду" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2038,6 +3310,12 @@ "Delete this draft?" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить этот черновик?" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2049,6 +3327,12 @@ "Delivery outcome unknown" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Результат доставки неизвестен" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2060,6 +3344,12 @@ "Denied" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отклонено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2071,6 +3361,12 @@ "Deny" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отклонить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2082,6 +3378,12 @@ "Detached HEAD" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отсоединённый HEAD" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2093,6 +3395,12 @@ "Details" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Подробности" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2104,6 +3412,12 @@ "Dictate" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Диктовать" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2115,6 +3429,12 @@ "Diff" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Диф" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2126,6 +3446,12 @@ "Directory" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Каталог" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2137,6 +3463,12 @@ "Directory does not exist. Creating the session will create it automatically." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Каталог не существует. При создании сессии он будет создан автоматически." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2148,6 +3480,12 @@ "Directory does not exist. Tap Create again to create it automatically." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Каталог не существует. Нажмите «Создать» ещё раз, чтобы создать его автоматически." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2159,6 +3497,12 @@ "Directory must be inside one of this machine's workspace roots." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Каталог должен находиться внутри одного из корней рабочего пространства этой машины." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2170,6 +3514,12 @@ "Discard changes" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отменить изменения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2181,6 +3531,12 @@ "Discard your changes?" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отменить ваши изменения?" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2192,6 +3548,12 @@ "Disk footprint of the hub's SQLite database (database, write-ahead log, shared memory)." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Место на диске, занимаемое базой SQLite хаба (база, журнал упреждающей записи, общая память)." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2203,6 +3565,12 @@ "Dismiss" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закрыть" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2214,6 +3582,12 @@ "Domain or IP address" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Домен или IP-адрес" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2225,6 +3599,12 @@ "Done" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Готово" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2236,6 +3616,12 @@ "Draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Черновик" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2247,6 +3633,12 @@ "Draft actions" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Действия с черновиком" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2258,6 +3650,12 @@ "Draft added to the send queue" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Черновик добавлен в очередь отправки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2269,6 +3667,12 @@ "Draft no longer available" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Черновик больше недоступен" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2280,6 +3684,12 @@ "Draft parked to scratchlist" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Черновик отложен в заметки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2291,6 +3701,12 @@ "Draft text" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Текст черновика" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2302,6 +3718,12 @@ "Drafts can contain at most 10,000 characters — shorten the text before saving" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Черновик может содержать не более 10 000 символов — сократите текст перед сохранением" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2313,6 +3735,12 @@ "Earlier calls aren't loaded. Close this view and load older messages in the conversation." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Более ранние вызовы не загружены. Закройте этот просмотр и загрузите старые сообщения в разговоре." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2324,6 +3752,12 @@ "Edit" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Изменить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2335,6 +3769,12 @@ "Edit %lld/%lld" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Правка %lld/%lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2346,6 +3786,12 @@ "Edit draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Редактировать черновик" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2357,6 +3803,12 @@ "Edit file" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Правка файла" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2368,6 +3820,12 @@ "Edit note" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Редактировать заметку" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2379,6 +3837,12 @@ "Edit notebook" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Правка блокнота" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2390,6 +3854,12 @@ "Effort" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Усилие" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2401,6 +3871,12 @@ "Enable in system settings…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Включить в системных настройках…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2412,6 +3888,12 @@ "Enabled" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Включено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2423,6 +3905,12 @@ "Enter Hub Details" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Введите данные хаба" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2434,6 +3922,12 @@ "Enter Manually" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ввести вручную" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2445,6 +3939,12 @@ "Enter a valid hub domain or IP address, with an optional port." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Введите корректный домен или IP-адрес хаба, при необходимости с портом." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2456,6 +3956,12 @@ "Enter the access token printed by your hub." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Введите токен доступа, напечатанный вашим хабом." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2467,6 +3973,12 @@ "Enter your hub address without the protocol, or paste a full URL or pairing link." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Введите адрес хаба без протокола либо вставьте полный URL или ссылку для сопряжения." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2478,6 +3990,12 @@ "Error" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2489,6 +4007,12 @@ "Expanded" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Развёрнуто" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2500,6 +4024,12 @@ "Failed to abort" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось прервать" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2511,6 +4041,12 @@ "Failed to browse directories" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось просмотреть каталоги" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2522,6 +4058,12 @@ "Failed to cancel queued message" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось отменить сообщение в очереди" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2533,6 +4075,12 @@ "Failed to check directory" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось проверить каталог" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2544,6 +4092,12 @@ "Failed to check installed Agents" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось проверить установленных агентов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2555,6 +4109,12 @@ "Failed to create session" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось создать сессию" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2566,6 +4126,12 @@ "Failed to list directory" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось получить список каталога" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2577,6 +4143,12 @@ "Failed to load Codex models" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить модели Codex" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2588,6 +4160,12 @@ "Failed to load diff" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить диф" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2599,6 +4177,12 @@ "Failed to load models" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить модели" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2610,6 +4194,12 @@ "Failed to load models: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить модели: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2621,6 +4211,12 @@ "Failed to load older messages" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось загрузить старые сообщения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2632,6 +4228,12 @@ "Failed to read file" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось прочитать файл" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2643,6 +4245,12 @@ "Failed to search files" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось выполнить поиск файлов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2654,6 +4262,12 @@ "Failed to steer message" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось направить сообщение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2665,6 +4279,12 @@ "Failed to synchronize messages" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось синхронизировать сообщения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2676,6 +4296,12 @@ "Failed to update session" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось обновить сессию" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2687,6 +4313,12 @@ "Failed — tap to retry" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка — нажмите, чтобы повторить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2698,6 +4330,12 @@ "Fast" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Быстрый" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2709,6 +4347,12 @@ "Fast Mode" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Быстрый режим" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2720,6 +4364,12 @@ "Fetching the session list from the hub." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Получение списка сессий с хаба." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2731,6 +4381,12 @@ "File" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файл" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2742,6 +4398,12 @@ "File actions" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Действия с файлом" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2753,6 +4415,12 @@ "Files" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файлы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2764,6 +4432,12 @@ "Filters" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Фильтры" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2775,6 +4449,12 @@ "Follow system" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Как в системе" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2786,6 +4466,12 @@ "Full message" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщение целиком" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2797,6 +4483,12 @@ "Git status unavailable" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Статус Git недоступен" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2808,6 +4500,12 @@ "Git status unavailable for this session" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Статус Git недоступен для этой сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2819,6 +4517,12 @@ "HAPI is self-hosted: your agent sessions run on your own machine, served by a hub you operate. Start the hub on your computer, then pair this app with the QR code it prints — or enter the hub URL and access token by hand." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "HAPI размещается самостоятельно: ваши сессии агентов работают на вашей машине за хабом, которым управляете вы. Запустите хаб на компьютере, затем сопрягите это приложение по QR-коду, который он печатает, либо введите URL хаба и токен доступа вручную." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2830,6 +4534,12 @@ "HTTP is unencrypted and may be restricted by iOS. HTTPS is recommended." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "HTTP не шифруется и может блокироваться iOS. Рекомендуется HTTPS." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2841,6 +4551,12 @@ "Held — not sent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удержано — не отправлено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2852,6 +4568,12 @@ "Hide note" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Скрыть примечание" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2863,6 +4585,12 @@ "High risk" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Высокий риск" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2874,6 +4602,12 @@ "Hub" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2885,6 +4619,12 @@ "Hub URL" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "URL хаба" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2896,6 +4636,12 @@ "Hub already paired" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб уже сопряжён" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2907,6 +4653,12 @@ "Hub database size on disk" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Размер базы данных хаба на диске" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2918,6 +4670,12 @@ "Hub error" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка хаба" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2929,6 +4687,12 @@ "Hub unreachable" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб недоступен" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2940,6 +4704,12 @@ "Hub unreachable — tap to retry." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб недоступен — нажмите, чтобы повторить." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2951,6 +4721,12 @@ "Hubs" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хабы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2962,6 +4738,12 @@ "Image is too large even after compression" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Изображение слишком большое даже после сжатия" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2973,6 +4755,12 @@ "Implement plan" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Реализовать план" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2984,6 +4772,12 @@ "Inactive" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Неактивна" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -2995,6 +4789,12 @@ "Input" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ввод" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3006,6 +4806,12 @@ "Insights" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Аналитика" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3017,6 +4823,12 @@ "Inspecting task log" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Просмотр журнала задачи" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3028,6 +4840,12 @@ "Interrupt agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Прервать агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3039,6 +4857,12 @@ "Invalid hub URL" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Неверный URL хаба" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3050,6 +4874,12 @@ "Keep an instruction for later…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сохранить инструкцию на потом…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3061,6 +4891,12 @@ "Keep editing" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Продолжить редактирование" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3072,6 +4908,12 @@ "Language" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Язык" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3083,6 +4925,12 @@ "Latest tool" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Последний инструмент" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3094,6 +4942,12 @@ "Launch Agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запуск агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3105,6 +4959,12 @@ "Light" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Светлая" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3116,6 +4976,12 @@ "Line %lld" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Строка %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3127,6 +4993,12 @@ "List agents" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Список агентов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3138,6 +5010,12 @@ "List files" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Список файлов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3149,6 +5027,12 @@ "Live" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Онлайн" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3160,6 +5044,12 @@ "Live updates interrupted — reconnecting…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Живые обновления прерваны — переподключение…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3171,6 +5061,12 @@ "Load more content" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузить больше" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3182,6 +5078,12 @@ "Load older messages" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузить старые сообщения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3193,6 +5095,12 @@ "Loading machines…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка машин…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3204,6 +5112,12 @@ "Loading messages…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка сообщений…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3215,6 +5129,12 @@ "Loading models…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка моделей…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3226,6 +5146,12 @@ "Loading older messages…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка старых сообщений…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3237,6 +5163,12 @@ "Loading sessions…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка сессий…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3248,6 +5180,12 @@ "Loading…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3259,6 +5197,12 @@ "Machine" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Машина" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3270,6 +5214,12 @@ "Machine · %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Машина · %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3281,6 +5231,12 @@ "Machine: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Машина: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3292,6 +5248,12 @@ "Managed by agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Управляется агентом" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3303,6 +5265,12 @@ "Message" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3314,6 +5282,12 @@ "Message agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщение агенту" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3325,6 +5299,12 @@ "Message cancelled — kept your current draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщение отменено — текущий черновик сохранён" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3336,6 +5316,12 @@ "Message the agent…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщение агенту…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3347,6 +5333,12 @@ "Message: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщение: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3358,6 +5350,12 @@ "Messages will appear here as the agent works." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщения появятся здесь по мере работы агента." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3369,6 +5367,12 @@ "Microphone access is disabled — allow it in Settings to dictate" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Доступ к микрофону отключён — разрешите его в Настройках для диктовки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3380,6 +5384,12 @@ "Microphone permission is needed for dictation" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Для диктовки нужен доступ к микрофону" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3391,6 +5401,12 @@ "Model" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Модель" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3402,6 +5418,12 @@ "Model list unavailable for this session." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Список моделей недоступен для этой сессии." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3413,6 +5435,12 @@ "More approval options" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Больше вариантов одобрения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3424,6 +5452,12 @@ "Name needs at least one letter or digit" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Имя должно содержать хотя бы одну букву или цифру" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3435,6 +5469,12 @@ "Needs approval" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нужно одобрение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3446,6 +5486,12 @@ "Needs attention" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Требует внимания" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3457,6 +5503,12 @@ "Needs reply" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нужен ответ" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3468,6 +5520,12 @@ "New Session" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Новая сессия" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3479,6 +5537,12 @@ "New note" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Новая заметка" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3490,6 +5554,12 @@ "Next part" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Следующая часть" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3501,6 +5571,12 @@ "Next question" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Следующий вопрос" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3512,6 +5588,12 @@ "Next tool" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Следующий инструмент" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3523,6 +5605,12 @@ "No HAPI hub answered at this address. Check that the hub is running and that this device can reach it (same network, or the relay tunnel is up)." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "По этому адресу не ответил ни один хаб HAPI. Проверьте, что хаб запущен и это устройство может до него добраться (та же сеть или активный туннель реле)." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3534,6 +5622,12 @@ "No agent steps available yet." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Шагов агента пока нет." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3545,6 +5639,12 @@ "No audio was recorded" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Звук не записан" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3556,6 +5656,12 @@ "No changes in the working tree" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В рабочем дереве нет изменений" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3567,6 +5673,12 @@ "No changes in this file" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В этом файле нет изменений" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3578,6 +5690,12 @@ "No drafts yet" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Черновиков пока нет" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3589,6 +5707,12 @@ "No files matched" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файлы не найдены" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3600,6 +5724,12 @@ "No filters" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нет фильтров" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3611,6 +5741,12 @@ "No machines online" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нет машин онлайн" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3622,6 +5758,12 @@ "No matching directories" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Подходящих каталогов нет" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3633,6 +5775,12 @@ "No messages yet" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сообщений пока нет" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3644,6 +5792,12 @@ "No notes" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нет заметок" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3655,6 +5809,12 @@ "No notes yet" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Заметок пока нет" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3666,6 +5826,12 @@ "No output" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нет вывода" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3677,6 +5843,12 @@ "No sessions yet" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессий пока нет" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3688,6 +5860,12 @@ "No settings available for this session." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Для этой сессии нет доступных настроек." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3699,6 +5877,12 @@ "No storage data reported." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Данные о хранилище не переданы." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3710,6 +5894,12 @@ "No subdirectories" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Нет подкаталогов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3721,6 +5911,12 @@ "No supported Agents are installed on this machine." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "На этой машине не установлено ни одного поддерживаемого агента." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3732,6 +5928,12 @@ "No transcription provider configured on hub" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "На хабе не настроен провайдер транскрипции" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3743,6 +5945,12 @@ "No usage recorded in this period." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "За этот период использование не зафиксировано." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3754,6 +5962,12 @@ "None of the above" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ничего из перечисленного" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3765,6 +5979,12 @@ "Not delivered" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не доставлено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3776,6 +5996,12 @@ "Not delivered — tap to retry" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не доставлено — нажмите, чтобы повторить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3787,6 +6013,12 @@ "Not requested" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не запрошено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3798,6 +6030,12 @@ "Not selected" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не выбрано" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3809,6 +6047,12 @@ "Note" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Примечание" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3820,6 +6064,12 @@ "Note, draft, parking-lot idea…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Заметка, черновик, идея на потом…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3831,6 +6081,12 @@ "Notifications" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Уведомления" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3842,6 +6098,12 @@ "OK" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "ОК" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3853,6 +6115,12 @@ "OLED black" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Чёрная OLED" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3864,6 +6132,12 @@ "Offline" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Офлайн" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3875,6 +6149,12 @@ "Offline — showing cached sessions" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Офлайн — показаны кешированные сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3886,6 +6166,12 @@ "Open" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Открыть" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3897,6 +6183,12 @@ "Open Settings" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Открыть Настройки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3908,6 +6200,12 @@ "Open URL" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Открыть URL" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3919,6 +6217,12 @@ "Open link?" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Открыть ссылку?" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3930,6 +6234,12 @@ "Optional" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Необязательно" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3941,6 +6251,12 @@ "Optionally, add details in notes." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "При желании добавьте подробности в примечании." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3952,6 +6268,12 @@ "Options" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Варианты" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3963,6 +6285,12 @@ "Other answer" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Другой ответ" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3974,6 +6302,12 @@ "Other…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Другое…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3985,6 +6319,12 @@ "Output" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вывод" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -3996,6 +6336,12 @@ "Pair" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сопрячь" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4007,6 +6353,12 @@ "Pair with your hub" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сопряжение с хабом" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4018,6 +6370,12 @@ "Pairing details filled in. Review them, then tap Pair." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Данные для сопряжения заполнены. Проверьте их и нажмите «Сопрячь»." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4029,6 +6387,12 @@ "Pairing succeeded but the credentials could not be stored on this device. Try again." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сопряжение удалось, но учётные данные не удалось сохранить на этом устройстве. Попробуйте снова." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4040,6 +6404,12 @@ "Pairing…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сопряжение…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4051,6 +6421,12 @@ "Park current draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отложить текущий черновик" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4062,6 +6438,12 @@ "Park drafts from the header, or tap + to jot a note for this session." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Откладывайте черновики из шапки или нажмите +, чтобы записать заметку для этой сессии." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4073,6 +6455,12 @@ "Part %lld" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Часть %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4084,6 +6472,12 @@ "Path" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Путь" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4095,6 +6489,12 @@ "Path is outside workspace roots" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Путь вне корней рабочего пространства" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4106,6 +6506,12 @@ "Paused" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Приостановлено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4117,6 +6523,12 @@ "Permission Mode" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Режим разрешений" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4128,6 +6540,12 @@ "Permission mode" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Режим разрешений" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4139,6 +6557,12 @@ "Permission modes control how the agent requests approval. Behavior varies by agent." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Режимы разрешений определяют, как агент запрашивает одобрение. Поведение зависит от агента." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4150,6 +6574,12 @@ "Permission request" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запрос разрешения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4161,6 +6591,12 @@ "Permission: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Разрешение: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4172,6 +6608,12 @@ "Photo library" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Галерея" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4183,6 +6625,12 @@ "Pin Globally" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закрепить глобально" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4194,6 +6642,12 @@ "Pin failed: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось закрепить: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4205,6 +6659,12 @@ "Pin to Project" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закрепить за проектом" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4216,6 +6676,12 @@ "Pinned" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Закреплённые" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4227,6 +6693,12 @@ "Plan" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "План" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4238,6 +6710,12 @@ "Plan proposal" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Предложение плана" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4249,6 +6727,12 @@ "Point the camera at the pairing QR from the hub terminal or the web app's Companion Pairing settings." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Наведите камеру на QR-код сопряжения из терминала хаба или из настроек Companion Pairing веб-приложения." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4260,6 +6744,12 @@ "Preview" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Предпросмотр" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4271,6 +6761,12 @@ "Preview not available for this image format" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Предпросмотр для этого формата изображения недоступен" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4282,6 +6778,12 @@ "Previous part" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Предыдущая часть" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4293,6 +6795,12 @@ "Previous question" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Предыдущий вопрос" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4304,6 +6812,12 @@ "Previous tool" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Предыдущий инструмент" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4315,6 +6829,12 @@ "Printed by the hub at startup, or available in web Settings → Companion Pairing. You can also paste a pairing link here." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Печатается хабом при запуске или доступен в веб-Настройках → Companion Pairing. Здесь также можно вставить ссылку для сопряжения." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4326,6 +6846,12 @@ "Privacy Policy" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Политика конфиденциальности" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4337,6 +6863,12 @@ "Project root" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Корень проекта" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4348,6 +6880,12 @@ "Protocol version" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Версия протокола" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4359,6 +6897,12 @@ "Pull to retry once you are back online." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Потяните, чтобы повторить, когда вернётесь онлайн." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4370,6 +6914,12 @@ "Push notifications" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Push-уведомления" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4381,6 +6931,12 @@ "Pushes are end-to-end encrypted; only this device can read them." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Push-уведомления защищены сквозным шифрованием; прочитать их может только это устройство." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4392,6 +6948,12 @@ "Query" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запрос" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4403,6 +6965,12 @@ "Question" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вопрос" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4414,6 +6982,12 @@ "Question %lld of %lld" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вопрос %lld из %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4425,6 +6999,12 @@ "Question canceled" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вопрос отменён" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4436,6 +7016,12 @@ "Question failed" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вопрос не выполнен" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4447,6 +7033,12 @@ "Question handled" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вопрос обработан" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4458,6 +7050,12 @@ "Questions & Answers" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вопросы и ответы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4469,6 +7067,12 @@ "Range" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Диапазон" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4480,6 +7084,12 @@ "Re-register push" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Перерегистрировать push" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4491,6 +7101,12 @@ "Read file" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Чтение файла" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4502,6 +7118,12 @@ "Read notebook" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Чтение блокнота" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4513,6 +7135,12 @@ "Reasoning" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Рассуждения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4524,6 +7152,12 @@ "Reasoning Effort" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Усилие рассуждений" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4535,6 +7169,12 @@ "Reasoning…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Рассуждения…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4546,6 +7186,12 @@ "Recommended" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Рекомендуется" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4557,6 +7203,12 @@ "Reconnecting…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Переподключение…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4568,6 +7220,12 @@ "Refresh" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Обновить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4579,6 +7237,12 @@ "Refreshing…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Обновление…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4590,6 +7254,12 @@ "Registered hubs" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Зарегистрированные хабы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4601,6 +7271,12 @@ "Remove" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4612,6 +7288,12 @@ "Remove %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4623,6 +7305,12 @@ "Removes the stored access token for this hub. Pair again to reconnect." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удаляет сохранённый токен доступа для этого хаба. Сопрягите заново, чтобы переподключиться." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4634,6 +7322,12 @@ "Reply" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ответить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4645,6 +7339,12 @@ "Request failed" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запрос не выполнен" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4656,6 +7356,12 @@ "Request was already handled" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запрос уже обработан" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4667,6 +7373,12 @@ "Requests" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запросы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4678,6 +7390,12 @@ "Result" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Результат" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4689,6 +7407,12 @@ "Result · error" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Результат · ошибка" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4700,6 +7424,12 @@ "Resume agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Возобновить агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4711,6 +7441,12 @@ "Retry" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Повторить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4722,6 +7458,12 @@ "Retry removal" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Повторить удаление" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4733,6 +7475,12 @@ "Run script" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запустить скрипт" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4744,6 +7492,12 @@ "Run shell" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запуск оболочки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4755,6 +7509,12 @@ "Runner last spawn error: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Последняя ошибка запуска раннера: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4766,6 +7526,12 @@ "Running" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выполняется" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4777,6 +7543,12 @@ "SQLite files" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файлы SQLite" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4788,6 +7560,12 @@ "Save" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сохранить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4799,6 +7577,12 @@ "Save draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сохранить черновик" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4810,6 +7594,12 @@ "Save input, then take draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сохранить ввод, затем взять черновик" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4821,6 +7611,12 @@ "Scan Again" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сканировать снова" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4832,6 +7628,12 @@ "Scan QR Code" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сканировать QR-код" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4843,6 +7645,12 @@ "Scan to Pair" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сканировать для сопряжения" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4854,6 +7662,12 @@ "Scanning unavailable" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сканирование недоступно" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4865,6 +7679,12 @@ "Scheduled · %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "По расписанию · %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4876,6 +7696,12 @@ "Scratchlist" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Заметки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4887,6 +7713,12 @@ "Scratchlist (%lld)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Заметки (%lld)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4898,6 +7730,12 @@ "Scratchlist is full (200 entries)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Заметки заполнены (200 записей)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4909,6 +7747,12 @@ "Scratchlist is full (200 entries) — delete one first" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Заметки заполнены (200 записей) — сначала удалите одну" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4920,6 +7764,12 @@ "Search" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поиск" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4931,6 +7781,12 @@ "Search content" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поиск по содержимому" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4942,6 +7798,12 @@ "Search drafts" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поиск черновиков" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4953,6 +7815,12 @@ "Search files" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поиск файлов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4964,6 +7832,12 @@ "Search files…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поиск файлов…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4975,6 +7849,12 @@ "Searching directories…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поиск каталогов…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4986,6 +7866,12 @@ "Section" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Раздел" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -4997,6 +7883,12 @@ "Select" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбрать" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5008,6 +7900,12 @@ "Select a session" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выберите сессию" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5019,6 +7917,12 @@ "Select all that apply" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выберите все подходящие" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5030,6 +7934,12 @@ "Selected" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбрано" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5041,6 +7951,12 @@ "Selected machine is offline" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбранная машина офлайн" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5052,6 +7968,12 @@ "Selected machine is offline. Choose an online machine." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбранная машина офлайн. Выберите машину онлайн." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5063,6 +7985,12 @@ "Send" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5074,6 +8002,12 @@ "Send & steer into current turn" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправить и вклиниться в текущий ход" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5085,6 +8019,12 @@ "Send — long-press to steer" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправить — долгое нажатие, чтобы направить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5096,6 +8036,12 @@ "Session Settings" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Настройки сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5107,6 +8053,12 @@ "Session Type" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Тип сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5118,6 +8070,12 @@ "Session files" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файлы сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5129,6 +8087,12 @@ "Session is controlled from the terminal — config changes will be rejected." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессией управляют из терминала — изменения конфигурации будут отклонены." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5140,6 +8104,12 @@ "Session is inactive and could not be resumed" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессия неактивна, и её не удалось возобновить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5151,6 +8121,12 @@ "Session is offline — changes apply after it resumes or may be rejected." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессия офлайн — изменения применятся после возобновления или могут быть отклонены." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5162,6 +8138,12 @@ "Session not found on any paired hub." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессия не найдена ни на одном сопряжённом хабе." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5173,6 +8155,12 @@ "Session settings" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Настройки сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5184,6 +8172,12 @@ "Session type" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Тип сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5195,6 +8189,12 @@ "Sessions" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5206,6 +8206,12 @@ "Sessions with usage: %lld" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессий с использованием: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5217,6 +8223,12 @@ "Settings" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Настройки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5228,6 +8240,12 @@ "Setup guide" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Руководство по настройке" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5239,6 +8257,12 @@ "Share file" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Поделиться файлом" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5250,6 +8274,12 @@ "Shared memory" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Общая память" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5261,6 +8291,12 @@ "Show Hidden" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показывать скрытые" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5272,6 +8308,12 @@ "Show all %lld lines" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать все строки: %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5283,6 +8325,12 @@ "Show hidden files" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показывать скрытые файлы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5294,6 +8342,12 @@ "Show image" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать изображение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5305,6 +8359,12 @@ "Show video" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать видео" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5316,6 +8376,12 @@ "Showing %lld of %lld parts" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показано %lld из %lld частей" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5327,6 +8393,12 @@ "Showing the last available group. Live group updates are unavailable." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показана последняя доступная группа. Живые обновления группы недоступны." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5338,6 +8410,12 @@ "Showing the last available record. Live updates are unavailable for this tool." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показана последняя доступная запись. Живые обновления для этого инструмента недоступны." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5349,6 +8427,12 @@ "Shutdown Response" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ответ на завершение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5360,6 +8444,12 @@ "Shutdown: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Завершение: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5371,6 +8461,12 @@ "Sign Out" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выйти" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5382,6 +8478,12 @@ "Sign Out…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выйти…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5393,6 +8495,12 @@ "Sign out of %@?" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выйти из %@?" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5404,6 +8512,12 @@ "Signed out of %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вы вышли из %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5415,6 +8529,12 @@ "Simple" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Обычная" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5426,6 +8546,12 @@ "Source" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Исходник" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5437,6 +8563,12 @@ "Spawn agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запустить агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5448,6 +8580,12 @@ "Staged" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В индексе" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5459,6 +8597,12 @@ "Staged (%lld)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В индексе (%lld)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5470,6 +8614,12 @@ "Standard" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Стандартный" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5481,6 +8631,12 @@ "Start an agent with the hapi CLI and it will appear here." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запустите агента через CLI hapi, и он появится здесь." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5492,6 +8648,12 @@ "Status: %@ · protocol v%lld" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Статус: %@ · протокол v%lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5503,6 +8665,12 @@ "Steer" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Направить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5514,6 +8682,12 @@ "Stop dictation" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Остановить диктовку" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5525,6 +8699,12 @@ "Stop the current turn" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Остановить текущий ход" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5536,6 +8716,12 @@ "Storage" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хранилище" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5547,6 +8733,12 @@ "Subdirectories" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Подкаталоги" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5558,6 +8750,12 @@ "Submit" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5569,6 +8767,12 @@ "Submit answer" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправить ответ" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5580,6 +8784,12 @@ "Submitting answer…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправка ответа…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5591,6 +8801,12 @@ "Submitting approval…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отправка одобрения…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5602,6 +8818,12 @@ "Take draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Взять черновик" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5613,6 +8835,12 @@ "Team: %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Команда: %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5624,6 +8852,12 @@ "Terminal" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Терминал" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5635,6 +8869,12 @@ "That code is not a HAPI pairing QR — scan one printed by the hub." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот код не является QR-кодом сопряжения HAPI — отсканируйте напечатанный хабом." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5646,6 +8886,12 @@ "That file is over the %lld MB limit" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот файл превышает лимит %lld МБ" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5657,6 +8903,12 @@ "That file is over the hub's per-file size limit" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот файл превышает лимит размера файла на хабе" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5668,6 +8920,12 @@ "That file type isn't allowed for scratchlist attachments" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот тип файла не разрешён для вложений в заметки" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5679,6 +8937,12 @@ "The app checks the hub is reachable, then exchanges the token for a session." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Приложение проверяет доступность хаба, затем обменивает токен на сессию." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5690,6 +8954,12 @@ "The attachments exceed the scratchlist limits — remove a file or choose a smaller one" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вложения превышают лимиты заметок — удалите файл или выберите меньший" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5701,6 +8971,12 @@ "The hub answered unexpectedly (HTTP %lld). Try again in a moment." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб ответил неожиданно (HTTP %lld). Попробуйте снова через мгновение." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5712,6 +8988,12 @@ "The hub rejected the stored credentials — the access token was probably rotated. Pair again to reconnect." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб отклонил сохранённые учётные данные — вероятно, токен доступа был обновлён. Сопрягите заново, чтобы переподключиться." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5723,6 +9005,12 @@ "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" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб отклонил этот токен доступа — возможно, он был обновлён. Получите свежий код сопряжения с хаба и попробуйте снова." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5734,6 +9022,12 @@ "The hub speaks protocol v%lld, this app supports v%lld. Update the older side, then try again." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб использует протокол v%lld, а это приложение поддерживает v%lld. Обновите более старую сторону и попробуйте снова." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5745,6 +9039,12 @@ "The selected Agent is not available on this machine." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбранный агент недоступен на этой машине." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5756,6 +9056,12 @@ "The session is no longer active." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сессия больше не активна." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5767,6 +9073,12 @@ "Theme" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Тема" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5778,6 +9090,12 @@ "Thinking" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Думает" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5789,6 +9107,12 @@ "This agent manages its own permissions. YOLO mode is not available." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот агент сам управляет разрешениями. Режим YOLO недоступен." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5800,6 +9124,12 @@ "This dashboard is only available to the hub owner (default namespace)." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Эта панель доступна только владельцу хаба (пространство имён по умолчанию)." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5811,6 +9141,12 @@ "This device cannot scan QR codes (for example the Simulator). Go back and use manual entry instead." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Это устройство не может сканировать QR-коды (например, симулятор). Вернитесь и введите данные вручную." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5822,6 +9158,12 @@ "This file is empty" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот файл пуст" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5833,6 +9175,12 @@ "This hub will be added to your paired hubs and become active." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот хаб будет добавлен к сопряжённым и станет активным." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5844,6 +9192,12 @@ "This note's attachment budget is used up" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Бюджет вложений этой заметки исчерпан" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5855,6 +9209,12 @@ "This pairing link is invalid or incomplete. Copy the full link from your hub." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Эта ссылка для сопряжения недействительна или неполна. Скопируйте полную ссылку с хаба." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5866,6 +9226,12 @@ "This question could not be displayed. Open details to inspect the request." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось показать этот вопрос. Откройте детали, чтобы изучить запрос." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5877,6 +9243,12 @@ "To composer" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "В поле ввода" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5888,6 +9260,12 @@ "Todo list" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Список задач" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5899,6 +9277,12 @@ "Token rejected" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Токен отклонён" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5910,6 +9294,12 @@ "Token usage across agents and models" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использование токенов по агентам и моделям" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5921,6 +9311,12 @@ "Tool %lld of %lld" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Инструмент %lld из %lld" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5932,6 +9328,12 @@ "Tool details" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Детали инструмента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5943,6 +9345,12 @@ "Total" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Итого" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5954,6 +9362,12 @@ "Total tokens" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Всего токенов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5965,6 +9379,12 @@ "Transcription failed" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка транскрипции" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5976,6 +9396,12 @@ "Try Again" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Повторить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5987,6 +9413,12 @@ "Type an answer first" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сначала введите ответ" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -5998,6 +9430,12 @@ "Type to search files in the session directory" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Начните вводить текст для поиска файлов в каталоге сессии" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6009,6 +9447,12 @@ "Type your answer…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Введите ответ…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6020,6 +9464,12 @@ "Uncached" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Без кеша" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6031,6 +9481,12 @@ "Unknown machine" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Неизвестная машина" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6042,6 +9498,12 @@ "Unpin" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Открепить" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6053,6 +9515,12 @@ "Unread" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Непрочитано" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6064,6 +9532,12 @@ "Unstaged" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вне индекса" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6075,6 +9549,12 @@ "Unstaged (%lld)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вне индекса (%lld)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6086,6 +9566,12 @@ "Up" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вверх" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6097,6 +9583,12 @@ "Upgrade and restart this machine's HAPI runner before creating sessions." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Обновите и перезапустите раннер HAPI этой машины перед созданием сессий." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6108,6 +9600,12 @@ "Upload failed — check the hub connection" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка загрузки — проверьте подключение к хабу" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6119,6 +9617,12 @@ "Uploading…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Загрузка…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6130,6 +9634,12 @@ "Usage" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использование" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6141,6 +9651,12 @@ "Use selected directory as-is" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использовать выбранный каталог как есть" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6152,6 +9668,12 @@ "Uses dangerous agent flags when spawning." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использует опасные флаги агента при запуске." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6163,6 +9685,12 @@ "Uses dangerous agent flags when spawning. Applies native %@ mode." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использует опасные флаги агента при запуске. Применяет нативный режим %@." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6174,6 +9702,12 @@ "Version mismatch" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Несовпадение версий" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6185,6 +9719,12 @@ "View agent process" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6196,6 +9736,12 @@ "View all" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать все" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6207,6 +9753,12 @@ "View current file" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать текущий файл" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6218,6 +9770,12 @@ "View full input" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать полный ввод" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6229,6 +9787,12 @@ "View full message" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать сообщение целиком" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6240,6 +9804,12 @@ "View full questions and answers" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать все вопросы и ответы" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6251,6 +9821,12 @@ "View image" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать изображение" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6262,6 +9838,36 @@ "View process · %lld steps" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс · %lld шаг" + } + }, + "few" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс · %lld шага" + } + }, + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс · %lld шагов" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать процесс · %lld шага" + } + } + } + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6273,6 +9879,12 @@ "View the full draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать черновик целиком" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6284,6 +9896,12 @@ "View tool details" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать детали инструмента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6295,6 +9913,12 @@ "View tool group" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Показать группу инструментов" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6306,6 +9930,12 @@ "Wait for agent" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ждать агента" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6317,6 +9947,12 @@ "Wait for result" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ждать результат" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6328,6 +9964,12 @@ "Waiting for output…" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ожидание вывода…" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6339,6 +9981,12 @@ "Web fetch" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Веб-запрос" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6350,6 +9998,12 @@ "Web search" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Веб-поиск" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6361,6 +10015,12 @@ "Workspace Roots" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Корни рабочего пространства" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6372,6 +10032,12 @@ "Workspace file" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Файл рабочего пространства" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6383,6 +10049,12 @@ "Worktree" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Worktree" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6394,6 +10066,12 @@ "Worktree sessions require an existing repository directory." : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Для сессий worktree нужен существующий каталог репозитория." + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6405,6 +10083,12 @@ "Write draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Написать черновик" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6416,6 +10100,12 @@ "Write file" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Запись файла" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6427,6 +10117,12 @@ "Write-ahead log" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Журнал упреждающей записи" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6438,6 +10134,12 @@ "You already have a draft" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "У вас уже есть черновик" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6449,6 +10151,12 @@ "Your answer" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ваш ответ" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6460,6 +10168,12 @@ "Your input changed — review it and try again" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ваш ввод изменился — проверьте его и попробуйте снова" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6471,6 +10185,12 @@ "error" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "ошибка" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6482,6 +10202,12 @@ "feature-x (optional)" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "feature-x (необязательно)" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6493,6 +10219,12 @@ "now" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "сейчас" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6504,6 +10236,12 @@ "pending" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "ожидает" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6515,6 +10253,12 @@ "— Canceled" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "— Отменено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6526,6 +10270,12 @@ "● Recording… %@" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "● Запись… %@" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6537,6 +10287,12 @@ "✓ Approved" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "✓ Одобрено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", @@ -6548,6 +10304,12 @@ "✕ Denied" : { "extractionState" : "manual", "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "✕ Отклонено" + } + }, "zh-Hans" : { "stringUnit" : { "state" : "translated", diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Settings/SettingsPrefs.swift b/ios/Packages/HapiKit/Sources/HapiClient/Settings/SettingsPrefs.swift index 932d8487..b6608f03 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Settings/SettingsPrefs.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Settings/SettingsPrefs.swift @@ -47,6 +47,7 @@ public enum AppLanguage: String, CaseIterable, Sendable { case system = "system" case english = "en" case simplifiedChinese = "zh-Hans" + case russian = "ru" /// Unknown/corrupt/absent stored values degrade to ``system``. public init(storageKey: String?) { @@ -63,6 +64,7 @@ public enum AppLanguage: String, CaseIterable, Sendable { case .system: return "Follow system" case .english: return "English" case .simplifiedChinese: return "简体中文" + case .russian: return "Русский" } } } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/ThemePrefsTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/ThemePrefsTests.swift index e849e6d8..00d76471 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/ThemePrefsTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/ThemePrefsTests.swift @@ -47,6 +47,7 @@ struct ThemePrefsTests { #expect(AppLanguage.system.storageKey == "system") #expect(AppLanguage.english.storageKey == "en") #expect(AppLanguage.simplifiedChinese.storageKey == "zh-Hans") + #expect(AppLanguage.russian.storageKey == "ru") } // MARK: - Resolution @@ -76,6 +77,9 @@ struct ThemePrefsTests { LanguagePrefs(defaults: defaults).setLanguage(.english) #expect(LanguagePrefs(defaults: defaults).language == .english) + + LanguagePrefs(defaults: defaults).setLanguage(.russian) + #expect(LanguagePrefs(defaults: defaults).language == .russian) } @Test func corruptStoredLanguageDegradesToFollowSystem() throws { @@ -89,6 +93,7 @@ struct ThemePrefsTests { @Test func languageNamesAreShownInTheirOwnLanguage() { #expect(AppLanguage.english.displayName == "English") #expect(AppLanguage.simplifiedChinese.displayName == "简体中文") + #expect(AppLanguage.russian.displayName == "Русский") // The follow-system row's label is localized at the app layer; the // package carries the English source string. #expect(AppLanguage.system.displayName == "Follow system") From 0ef5f976c0a183e4b0f463aae334cc4cd08c6cb0 Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Mon, 5 Oct 2026 18:13:14 +0900 Subject: [PATCH 23/34] fix(web): render Codex goal responses as cards (#1954) --- .../messages/SystemMessage.test.tsx | 76 ++++++++++ .../AssistantChat/messages/SystemMessage.tsx | 31 +++- web/src/components/ToolCard/ToolCard.tsx | 2 +- web/src/components/ToolCard/goalTools.test.ts | 107 ++++++++++++++ web/src/components/ToolCard/goalTools.ts | 110 ++++++++++++++ web/src/components/ToolCard/knownTools.tsx | 18 ++- .../ToolCard/views/GoalView.test.tsx | 137 ++++++++++++++++++ .../components/ToolCard/views/GoalView.tsx | 106 ++++++++++++++ web/src/components/ToolCard/views/_all.tsx | 7 +- .../components/ToolCard/views/_results.tsx | 9 ++ web/src/lib/locales/en.ts | 14 ++ web/src/lib/locales/zh-CN.ts | 14 ++ 12 files changed, 623 insertions(+), 8 deletions(-) create mode 100644 web/src/components/AssistantChat/messages/SystemMessage.test.tsx create mode 100644 web/src/components/ToolCard/goalTools.test.ts create mode 100644 web/src/components/ToolCard/goalTools.ts create mode 100644 web/src/components/ToolCard/views/GoalView.test.tsx create mode 100644 web/src/components/ToolCard/views/GoalView.tsx diff --git a/web/src/components/AssistantChat/messages/SystemMessage.test.tsx b/web/src/components/AssistantChat/messages/SystemMessage.test.tsx new file mode 100644 index 00000000..80652b47 --- /dev/null +++ b/web/src/components/AssistantChat/messages/SystemMessage.test.tsx @@ -0,0 +1,76 @@ +import type { HTMLAttributes } from 'react' +import { fireEvent, render, screen } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { I18nProvider } from '@/lib/i18n-context' +import { HappySystemMessage } from './SystemMessage' + +const { message } = vi.hoisted(() => ({ + message: { + role: 'system', id: 'status-example', + content: [] as { type: string; text: string }[], + metadata: { custom: {} as Record } + } +})) +vi.mock('@assistant-ui/react', () => ({ + useAuiState: (selector: (state: { message: typeof message }) => unknown) => selector({ message }), + MessagePrimitive: { Root: (props: HTMLAttributes) =>
} +})) +vi.mock('./MessageTimestamp', () => ({ MessageTimestamp: () => 12:00 })) + +const goal = { + threadId: 'thread-example-1', objective: 'Compare the options and validate the chosen approach.', + status: 'active', tokenBudget: null, tokensUsed: 0, timeUsedSeconds: 0, + createdAt: 1704067200, updatedAt: 1704067200 +} +function show(text: string, eventType = 'message', kind = 'event') { + message.content = [{ type: 'text', text }] + message.metadata.custom = { kind, event: { type: eventType, message: text } } + return render() +} + +beforeEach(() => { message.role = 'system' }) + +describe('slash-command goal status messages', () => { + it('renders the actual event/message response as a goal snapshot card', () => { + const raw = JSON.stringify({ goal }) + const { container } = show(raw) + expect(screen.getByText('Goal')).toBeInTheDocument() + expect(screen.getByText(goal.objective)).toBeInTheDocument() + expect(screen.getByText('Active')).toBeInTheDocument() + expect(screen.getByText('0 tokens')).toBeInTheDocument() + expect(screen.getByText('No limit')).toBeInTheDocument() + expect(screen.getByText('0.0s')).toBeInTheDocument() + expect(container.querySelector('[data-goal-status="active"]')).not.toBeNull() + const details = screen.getByText('Raw JSON').closest('details')! + expect(details.open).toBe(false) + fireEvent.click(screen.getByText('Raw JSON')) + expect(details.open).toBe(true) + expect(details.textContent).toContain('thread-example-1') + expect(details.textContent).toContain(raw) + }) + + it('shows an explicitly empty goal', () => { + show('{"goal":null}') + expect(screen.getByText('No goal set')).toBeInTheDocument() + }) + + it.each(['Goal cleared', '{broken', '{"objective":"ordinary data"}', JSON.stringify({ goal, error: 'denied' })]) + ('preserves ordinary and malformed status text', (text) => { + const { container } = show(text) + expect(screen.getByText(text)).toBeInTheDocument() + expect(container.querySelector('[data-goal-status]')).toBeNull() + }) + + it.each([['error', 'event'], ['message', 'other']])('only formats confirmed message events', (eventType, kind) => { + const raw = JSON.stringify({ goal }) + const { container } = show(raw, eventType, kind) + expect(screen.getByText(raw)).toBeInTheDocument() + expect(container.querySelector('[data-goal-status]')).toBeNull() + }) + + it('does not format ordinary assistant content', () => { + message.role = 'assistant' + const { container } = show(JSON.stringify({ goal })) + expect(container).toBeEmptyDOMElement() + }) +}) diff --git a/web/src/components/AssistantChat/messages/SystemMessage.tsx b/web/src/components/AssistantChat/messages/SystemMessage.tsx index 5bc0dd3c..ff4321c0 100644 --- a/web/src/components/AssistantChat/messages/SystemMessage.tsx +++ b/web/src/components/AssistantChat/messages/SystemMessage.tsx @@ -5,6 +5,10 @@ import type { HappyChatMessageMetadata } from '@/lib/assistant-runtime' import { getConversationMessageAnchorId } from '@/chat/outline' import { MessageTimestamp } from '@/components/AssistantChat/messages/MessageTimestamp' import { MarkdownRenderer } from '@/components/MarkdownRenderer' +import { CodeBlock } from '@/components/CodeBlock' +import { parseGoalStatusMessage } from '@/components/ToolCard/goalTools' +import { GoalSummary } from '@/components/ToolCard/views/GoalView' +import { useTranslation } from '@/lib/use-translation' function formatTokenDelta(event: AgentEvent | undefined): string | null { if (!event || event.type !== 'compact-summary') return null @@ -16,17 +20,17 @@ function formatTokenDelta(event: AgentEvent | undefined): string | null { } export function HappySystemMessage() { + const { t } = useTranslation() const role = useAuiState((s) => s.message.role) const messageId = useAuiState((s) => s.message.id) const text = useAuiState((s) => { if (s.message.role !== 'system') return '' return s.message.content[0]?.type === 'text' ? s.message.content[0].text : '' }) - const icon = useAuiState((s) => { + const event = useAuiState((s) => { if (s.message.role !== 'system') return null const custom = s.message.metadata.custom as Partial | undefined - const event = custom?.kind === 'event' ? custom.event : undefined - return event ? getEventPresentation(event).icon : null + return custom?.kind === 'event' ? custom.event : undefined }) const compactSummary = useAuiState((s) => { if (s.message.role !== 'system') return undefined @@ -36,6 +40,27 @@ export function HappySystemMessage() { if (role !== 'system') return null + const icon = event ? getEventPresentation(event).icon : null + const goalMessage = event?.type === 'message' && typeof event.message === 'string' ? event.message : null + const goal = goalMessage !== null ? parseGoalStatusMessage(goalMessage) : null + if (goal && goalMessage !== null) { + return ( + +
+
+ {t('session.status.goal')} + +
+ +
+ {t('tool.goal.raw')} + +
+
+
+ ) + } + // Pi compaction summaries are real content, not status: render them as an // independent block (header with token delta + the summary markdown) // instead of the tiny centered status line used for other events. diff --git a/web/src/components/ToolCard/ToolCard.tsx b/web/src/components/ToolCard/ToolCard.tsx index d2c398d0..c4c00987 100644 --- a/web/src/components/ToolCard/ToolCard.tsx +++ b/web/src/components/ToolCard/ToolCard.tsx @@ -436,7 +436,7 @@ function ToolCardInner(props: ToolCardProps) { const isCodexAgentCard = toolName === 'CodexAgent' const useCompactTerminalCard = shouldUseCompactTerminalToolCard(toolName, props.terminalToolDisplayMode) const showInline = shouldShowInlineToolCardBody(toolName, presentation.minimal, props.terminalToolDisplayMode) - const CompactToolView = showInline ? getToolViewComponent(toolName) : null + const CompactToolView = showInline ? getToolViewComponent(toolName, props.block.tool) : null const compactViewOwnsInteractions = toolName === 'CodexDiff' const ResultToolView = getToolResultViewComponent(toolName) const permission = props.block.tool.permission diff --git a/web/src/components/ToolCard/goalTools.test.ts b/web/src/components/ToolCard/goalTools.test.ts new file mode 100644 index 00000000..56f35b7c --- /dev/null +++ b/web/src/components/ToolCard/goalTools.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from 'vitest' +import { isGoalToolName, parseGoalToolResult } from './goalTools' + +const goal = { + threadId: 'thread-1', + objective: 'Compare the options and validate the chosen approach.', + status: 'active', + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: 1704067200, + updatedAt: 1704067200 +} + +describe('goal tool results', () => { + it.each([ + { goal }, + JSON.stringify({ goal }), + { output: JSON.stringify({ goal }) }, + { result: { content: [{ type: 'text', text: JSON.stringify({ goal }) }] } }, + [{ type: 'text', text: JSON.stringify({ goal }) }], + goal + ])('reads the goal snapshot from supported envelopes', (result) => { + expect(parseGoalToolResult(result)).toEqual({ kind: 'goal', goal }) + }) + + it('keeps an explicit empty goal distinct from missing results', () => { + expect(parseGoalToolResult({ goal: null })).toEqual({ kind: 'empty' }) + expect(parseGoalToolResult(undefined)).toBeNull() + expect(parseGoalToolResult(null)).toBeNull() + }) + + it.each([ + '{broken', + 'Output:\n' + JSON.stringify({ goal }), + { data: { goal } }, + { goal: { status: 'active' } }, + { goal: { objective: ' ', status: 'active' } }, + { isError: true, content: [{ type: 'text', text: JSON.stringify({ goal }) }] }, + { error: 'denied', goal }, + { result: { result: { result: { result: { result: { goal } } } } } } + ])('leaves malformed, error and unrelated results to the generic renderer', (result) => { + expect(parseGoalToolResult(result)).toBeNull() + }) + + it('normalizes named snake_case fields and preserves zero and null', () => { + expect(parseGoalToolResult({ goal: { + objective: goal.objective, status: 'futureState', thread_id: 'thread-2', + token_budget: null, tokens_used: 0, time_used_seconds: 0, + created_at: 1704067200 + } })).toEqual({ kind: 'goal', goal: { + objective: goal.objective, status: 'futureState', threadId: 'thread-2', + tokenBudget: null, tokensUsed: 0, timeUsedSeconds: 0, createdAt: 1704067200 + } }) + }) + + it('does not invent missing counters or display invalid numeric fields', () => { + expect(parseGoalToolResult({ goal: { + objective: 'ship', status: 'active', tokensUsed: -1, + tokenBudget: Infinity, timeUsedSeconds: NaN, updatedAt: -2 + } })).toEqual({ kind: 'goal', goal: { objective: 'ship', status: 'active' } }) + expect(parseGoalToolResult({ goal: { objective: 'ship', status: 'active' } })) + .toEqual({ kind: 'goal', goal: { objective: 'ship', status: 'active' } }) + }) + + it('does not substitute snake_case values for explicit camelCase null', () => { + expect(parseGoalToolResult({ goal: { ...goal, token_budget: 100 } })) + .toEqual({ kind: 'goal', goal }) + }) + + it('stops at the nesting limit and handles circular objects', () => { + const cycle: { result?: unknown } = {} + cycle.result = cycle + expect(parseGoalToolResult(cycle)).toBeNull() + }) +}) + +describe('goal tool names', () => { + it.each(['create_goal', 'get_goal', 'update_goal', 'functions.create_goal', 'functions.get_goal', 'functions.update_goal']) + ('recognizes %s', (name) => expect(isGoalToolName(name)).toBe(true)) + + it.each(['mcp__other__create_goal', 'other.create_goal', 'recreate_goal', 'functions.functions.create_goal', 'Create_Goal', 'create_goal_extra']) + ('does not claim unrelated tool %s', (name) => expect(isGoalToolName(name)).toBe(false)) +}) + + +describe('goal status messages', () => { + it('recognizes the complete slash-command response', async () => { + const { parseGoalStatusMessage } = await import('./goalTools') + expect(parseGoalStatusMessage(JSON.stringify({ goal }))).toEqual({ kind: 'goal', goal }) + expect(parseGoalStatusMessage('{"goal":null}')).toEqual({ kind: 'empty' }) + }) + + it.each([ + JSON.stringify(goal), + JSON.stringify({ goal, error: 'denied' }), + JSON.stringify({ result: { goal } }), + JSON.stringify({ goal, unrelated: true }), + JSON.stringify({ goal: { objective: 'incomplete' } }), + '```json\n' + JSON.stringify({ goal }) + '\n```', + 'Goal result: ' + JSON.stringify({ goal }), + '{broken' + ])('leaves unrelated and malformed status messages unchanged', async (message) => { + const { parseGoalStatusMessage } = await import('./goalTools') + expect(parseGoalStatusMessage(message)).toBeNull() + }) +}) diff --git a/web/src/components/ToolCard/goalTools.ts b/web/src/components/ToolCard/goalTools.ts new file mode 100644 index 00000000..b3937364 --- /dev/null +++ b/web/src/components/ToolCard/goalTools.ts @@ -0,0 +1,110 @@ +import { isObject } from '@hapi/protocol' +import type { ChatToolCall } from '@/chat/types' + +const GOAL_TOOL_NAMES = ['create_goal', 'get_goal', 'update_goal'] as const +export type GoalToolName = typeof GOAL_TOOL_NAMES[number] + +export function getGoalToolName(name: string): GoalToolName | null { + const candidate = name.startsWith('functions.') ? name.slice('functions.'.length) : name + return (GOAL_TOOL_NAMES as readonly string[]).includes(candidate) ? candidate as GoalToolName : null +} + +export function isGoalToolName(name: string): boolean { + return getGoalToolName(name) !== null +} + +export type GoalSnapshot = { + objective: string + status: string + threadId?: string + tokenBudget?: number | null + tokensUsed?: number + timeUsedSeconds?: number + createdAt?: number + updatedAt?: number +} + +export type GoalResult = { kind: 'goal'; goal: GoalSnapshot } | { kind: 'empty' } + +function readField(record: Record, camel: string, snake: string): unknown { + return Object.prototype.hasOwnProperty.call(record, camel) ? record[camel] : record[snake] +} + +function parseSnapshot(value: unknown): GoalSnapshot | null { + if (!isObject(value) || typeof value.objective !== 'string' || !value.objective.trim() + || typeof value.status !== 'string' || !value.status.trim()) return null + + const goal: GoalSnapshot = { objective: value.objective, status: value.status } + const threadId = readField(value, 'threadId', 'thread_id') + if (typeof threadId === 'string' && threadId.trim()) goal.threadId = threadId + + const fields = [ + ['tokenBudget', 'token_budget'], ['tokensUsed', 'tokens_used'], + ['timeUsedSeconds', 'time_used_seconds'], ['createdAt', 'created_at'], ['updatedAt', 'updated_at'] + ] as const + for (const [camel, snake] of fields) { + const number = readField(value, camel, snake) + if (camel === 'tokenBudget' && number === null) goal.tokenBudget = null + else if (typeof number === 'number' && Number.isFinite(number) && number >= 0) goal[camel] = number + } + return goal +} + +/** Only unwrap documented result/text containers; arbitrary objects are not searched. */ +export function parseGoalToolResult(result: unknown, depth = 0): GoalResult | null { + if (depth > 4) return null + if (typeof result === 'string') { + const text = result.trim() + if (!text.startsWith('{') && !text.startsWith('[')) return null + try { + return parseGoalToolResult(JSON.parse(text) as unknown, depth) + } catch { + return null + } + } + if (Array.isArray(result)) { + if (result.length === 0 || !result.every((block) => isObject(block) + && block.type === 'text' && typeof block.text === 'string')) return null + return parseGoalToolResult(result.map((block) => block.text).join('\n'), depth + 1) + } + if (!isObject(result) || result.isError === true || result.is_error === true + || (result.error !== undefined && result.error !== null)) return null + + if (Object.prototype.hasOwnProperty.call(result, 'goal')) { + if (result.goal === null) return { kind: 'empty' } + const goal = parseSnapshot(result.goal) + return goal ? { kind: 'goal', goal } : null + } + const goal = parseSnapshot(result) + if (goal) return { kind: 'goal', goal } + for (const key of ['result', 'output', 'content', 'text']) { + if (Object.prototype.hasOwnProperty.call(result, key)) { + return parseGoalToolResult(result[key], depth + 1) + } + } + return null +} + +/** The shared Codex /goal command emits a standalone {goal} status message. */ +export function parseGoalStatusMessage(message: string): GoalResult | null { + try { + const value: unknown = JSON.parse(message) + if (!isObject(value) || Object.keys(value).length !== 1 + || !Object.prototype.hasOwnProperty.call(value, 'goal')) return null + return parseGoalToolResult(value) + } catch { + return null + } +} + +export function getPendingGoalRequest(input: unknown): { kind: 'objective' | 'status'; text: string } | null { + if (!isObject(input)) return null + if (typeof input.objective === 'string' && input.objective.trim()) return { kind: 'objective', text: input.objective } + return typeof input.status === 'string' && input.status.trim() ? { kind: 'status', text: input.status } : null +} + +export function canShowGoalPreview(tool: Pick): boolean { + if (tool.state === 'error') return false + if (tool.state === 'completed') return parseGoalToolResult(tool.result) !== null + return getPendingGoalRequest(tool.input) !== null +} diff --git a/web/src/components/ToolCard/knownTools.tsx b/web/src/components/ToolCard/knownTools.tsx index a1cde754..6139d756 100644 --- a/web/src/components/ToolCard/knownTools.tsx +++ b/web/src/components/ToolCard/knownTools.tsx @@ -6,6 +6,7 @@ import type { ChecklistItem } from '@/components/ToolCard/checklist' import { extractTodoChecklist, extractUpdatePlanChecklist } from '@/components/ToolCard/checklist' import { basename, resolveDisplayPath } from '@/utils/path' import { getInputStringAny, truncate } from '@/lib/toolInputUtils' +import { getGoalToolName } from '@/components/ToolCard/goalTools' import { getCodexAgentActivity, getCodexAgentPrompt, @@ -125,6 +126,18 @@ export const knownTools: Record string | null minimal?: boolean | ((opts: ToolOpts) => boolean) }> = { + create_goal: { + icon: () => , + title: () => 'Create goal' + }, + get_goal: { + icon: () => , + title: () => 'Get goal' + }, + update_goal: { + icon: () => , + title: () => 'Update goal' + }, // agy transitional "Inside the task-NNN log…" narration → compact chip. // description carries the short "task-NNN log" label from normalizeAgent. AgyTaskLog: { @@ -664,12 +677,13 @@ export function getToolPresentation( } } - const known = knownTools[opts.toolName] + const goalName = getGoalToolName(opts.toolName) + const known = knownTools[goalName ?? opts.toolName] if (known) { const minimal = typeof known.minimal === 'function' ? known.minimal(opts) : (known.minimal ?? false) return { icon: known.icon(opts), - title: known.title(opts), + title: goalName && t ? t(`tool.goal.${goalName}`) : known.title(opts), subtitle: known.subtitle ? known.subtitle(opts) : null, minimal } diff --git a/web/src/components/ToolCard/views/GoalView.test.tsx b/web/src/components/ToolCard/views/GoalView.test.tsx new file mode 100644 index 00000000..179d8af8 --- /dev/null +++ b/web/src/components/ToolCard/views/GoalView.test.tsx @@ -0,0 +1,137 @@ +import { fireEvent, render, screen, within } from '@testing-library/react' +import { beforeEach, describe, expect, it } from 'vitest' +import type { ApiClient } from '@/api/client' +import type { ToolCallBlock } from '@/chat/types' +import { ToolCard } from '@/components/ToolCard/ToolCard' +import { getToolResultViewComponent } from '@/components/ToolCard/views/_results' +import { I18nProvider } from '@/lib/i18n-context' + +const goal = { + objective: 'Compare the options and validate the chosen approach.', status: 'active', threadId: 'thread-1', + tokensUsed: 0, tokenBudget: null, timeUsedSeconds: 0, + createdAt: 1704067200, updatedAt: 1704067200 +} + +function goalBlock(result: unknown, state: ToolCallBlock['tool']['state'] = 'completed', name = 'create_goal', input: unknown = { objective: 'requested objective', status: 'complete' }): ToolCallBlock { + return { + kind: 'tool-call', id: 'goal-1', localId: null, createdAt: 1000, children: [], + tool: { + id: 'goal-1', name, state, input, + result, description: null, createdAt: 1000, startedAt: 1000, completedAt: 1500, + execStartedAt: null, execCompletedAt: null + } + } +} + +function renderGoal(result: unknown, state: ToolCallBlock['tool']['state'] = 'completed', name = 'create_goal', input?: unknown) { + return render( {}} block={goalBlock(result, state, name, input)} + />) +} + +describe('goal cards in ToolCard', () => { + beforeEach(() => localStorage.setItem('hapi-lang', 'en')) + + it.each(['create_goal', 'get_goal', 'update_goal', 'functions.create_goal', 'functions.get_goal', 'functions.update_goal'])('shows the snapshot once for %s', (name) => { + renderGoal(JSON.stringify({ goal }), 'completed', name) + expect(screen.getAllByText(goal.objective)).toHaveLength(1) + expect(screen.getByText('Active')).toBeInTheDocument() + expect(screen.getByText('0 tokens')).toBeInTheDocument() + expect(screen.getByText('No limit')).toBeInTheDocument() + expect(screen.getByText('0.0s')).toBeInTheDocument() + expect(screen.queryByText('requested objective')).not.toBeInTheDocument() + expect(screen.queryByRole('progressbar')).not.toBeInTheDocument() + expect(screen.queryByText('thread-1')).not.toBeInTheDocument() + }) + + it('shows token budget consumption without hiding over-budget usage', () => { + renderGoal({ goal: { ...goal, tokensUsed: 150, tokenBudget: 100 } }) + expect(screen.getByText('150 / 100 tokens')).toBeInTheDocument() + expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '100') + expect(screen.getByRole('progressbar')).toHaveAccessibleName('Token budget used') + }) + + it('shows no goal distinctly', () => { + renderGoal({ goal: null }) + expect(screen.getByText('No goal set')).toBeInTheDocument() + expect(screen.queryByText('Active')).not.toBeInTheDocument() + }) + + it('does not infer successful goal state while pending', () => { + renderGoal(undefined, 'pending') + expect(screen.getByText('requested objective')).toBeInTheDocument() + expect(screen.queryByText('Complete')).not.toBeInTheDocument() + }) + + it.each([ + ['en', 'Requested status', 'Complete'], + ['zh-CN', '请求的状态', '已完成'] + ])('labels status-only pending requests in %s without a successful state badge', (locale, label, status) => { + localStorage.setItem('hapi-lang', locale) + const { container } = renderGoal(undefined, 'pending', 'update_goal', { status: 'complete' }) + expect(screen.getByText(label)).toBeInTheDocument() + expect(screen.getByText(status)).toBeInTheDocument() + expect(screen.queryByText('complete')).not.toBeInTheDocument() + expect(container.querySelector('[data-goal-status]')).toBeNull() + }) + + it('keeps unknown requested statuses readable', () => { + renderGoal(undefined, 'pending', 'update_goal', { status: 'futureState' }) + expect(screen.getByText('Requested status')).toBeInTheDocument() + expect(screen.getByText('futureState')).toBeInTheDocument() + }) + + it.each([ + ['en', 0, '0.0s'], ['zh-CN', 0, '0.0s'], + ['en', 0.5, '0.5s'], ['zh-CN', 0.5, '0.5s'], + ['en', 76, '1m 16s'], ['zh-CN', 76, '1m 16s'] + ])('uses the common duration format for %s at %s seconds', (locale, seconds, duration) => { + localStorage.setItem('hapi-lang', locale) + const { container } = renderGoal({ goal: { ...goal, timeUsedSeconds: seconds } }) + expect(within(container.querySelector('[data-goal-status]') as HTMLElement).getByText(duration)).toBeInTheDocument() + }) + + it.each(['error', 'completed'] as const)('preserves the generic fallback for %s errors', (state) => { + renderGoal('Permission denied', state) + expect(screen.getByText('Permission denied')).toBeInTheDocument() + expect(screen.queryByText('Active')).not.toBeInTheDocument() + }) + + it('does not render a successful-looking goal payload when the tool failed', () => { + renderGoal({ goal }, 'error') + expect(screen.queryByText('Active')).not.toBeInTheDocument() + expect(screen.getByText('Result')).toBeInTheDocument() + }) + + it('keeps unknown status readable and omits absent metrics', () => { + renderGoal({ goal: { objective: goal.objective, status: 'futureState' } }) + expect(screen.getByText('futureState')).toBeInTheDocument() + expect(screen.queryByText('0 tokens')).not.toBeInTheDocument() + expect(screen.queryByText('0.0s')).not.toBeInTheDocument() + }) + + it('shows metadata and collapsed original JSON only in the detail dialog', () => { + renderGoal({ goal }) + fireEvent.click(screen.getByRole('button', { expanded: false })) + const dialog = screen.getByRole('dialog') + expect(within(dialog).getByText('thread-1')).toBeInTheDocument() + const raw = within(dialog).getByText('Raw JSON').closest('details')! + expect(raw.open).toBe(false) + fireEvent.click(within(dialog).getByText('Raw JSON')) + expect(within(dialog).getByText('Raw JSON').closest('details')).toBe(raw) + }) + + it('keeps metadata and raw output when used by a trace result without a surface', () => { + const ResultView = getToolResultViewComponent('get_goal') + render() + expect(screen.getByText('thread-1')).toBeInTheDocument() + expect(screen.getByText('Raw JSON').closest('details')?.open).toBe(false) + }) + + it('hides times that overflow millisecond conversion', () => { + const { container } = renderGoal({ goal: { ...goal, timeUsedSeconds: Number.MAX_VALUE } }) + expect(container.textContent).not.toMatch(/Infinity|NaN/) + expect(screen.getByText(goal.objective)).toBeInTheDocument() + }) +}) diff --git a/web/src/components/ToolCard/views/GoalView.tsx b/web/src/components/ToolCard/views/GoalView.tsx new file mode 100644 index 00000000..24efcbb4 --- /dev/null +++ b/web/src/components/ToolCard/views/GoalView.tsx @@ -0,0 +1,106 @@ +import { safeStringify } from '@hapi/protocol' +import { CodeBlock } from '@/components/CodeBlock' +import { formatDuration } from '@/chat/presentation' +import { useTranslation } from '@/lib/use-translation' +import { getPendingGoalRequest, parseGoalToolResult, type GoalResult } from '../goalTools' +import type { ToolViewProps } from './_all' + +const STATUS_TONES: Record = { + active: 'bg-blue-500/10 text-blue-700 dark:text-blue-300', + paused: 'bg-amber-500/10 text-amber-700 dark:text-amber-300', + budgetLimited: 'bg-amber-500/10 text-amber-700 dark:text-amber-300', + usageLimited: 'bg-amber-500/10 text-amber-700 dark:text-amber-300', + blocked: 'bg-red-500/10 text-red-700 dark:text-red-300', + complete: 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-300' +} + +function formatGoalDate(seconds: number | undefined, locale: string): string | null { + if (!seconds || seconds <= 0) return null + const date = new Date(seconds * 1000) + return Number.isFinite(date.getTime()) ? date.toLocaleString(locale) : null +} + +export function GoalSummary({ result, surface }: { result: GoalResult; surface?: 'inline' | 'dialog' }) { + const { t, locale } = useTranslation() + if (result.kind === 'empty') { + return
{t('tool.goal.empty')}
+ } + const { goal } = result + const number = (value: number) => value.toLocaleString(locale) + const used = goal.tokensUsed + const budget = goal.tokenBudget + const durationMs = goal.timeUsedSeconds !== undefined ? goal.timeUsedSeconds * 1000 : null + const duration = durationMs !== null && Number.isFinite(durationMs) + ? formatDuration(durationMs) + : null + const percentage = used !== undefined && typeof budget === 'number' && budget > 0 + ? Math.min(100, used / budget * 100) : null + const tone = Object.prototype.hasOwnProperty.call(STATUS_TONES, goal.status) ? STATUS_TONES[goal.status] : null + const metadata = [ + [t('tool.goal.thread'), goal.threadId], + [t('tool.goal.created'), formatGoalDate(goal.createdAt, locale)], + [t('tool.goal.updated'), formatGoalDate(goal.updatedAt, locale)] + ] + + return ( +
+
+ + {tone ? t(`session.status.goal.${goal.status}`) : goal.status} + +
{goal.objective}
+
+
+ {used !== undefined ? ( + {t('tool.goal.tokens', { value: typeof budget === 'number' ? `${number(used)} / ${number(budget)}` : number(used) })} + ) : typeof budget === 'number' ? ( + {t('tool.goal.budget', { value: number(budget) })} + ) : null} + {budget === null ? {t('tool.goal.unlimited')} : null} + {duration ? {duration} : null} +
+ {percentage !== null ? ( +
+
+
+ ) : null} + {surface === 'dialog' && metadata.some(([, value]) => value) ? ( +
+ {metadata.filter(([, value]) => value).map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+ ) : null} +
+ ) +} + +export function GoalView({ block, surface }: ToolViewProps) { + const { t } = useTranslation() + const result = block.tool.state === 'completed' ? parseGoalToolResult(block.tool.result) : null + if (!result) { + const request = getPendingGoalRequest(block.tool.input) + const isStatus = request?.kind === 'status' + const text = isStatus && Object.prototype.hasOwnProperty.call(STATUS_TONES, request.text) + ? t(`session.status.goal.${request.text}`) : request?.text + return
+ {t(isStatus ? 'tool.goal.requestedStatus' : 'tool.goal.requested')} + {text} +
+ } + return ( +
+ + {surface === 'dialog' ? ( +
+ {t('tool.goal.raw')} + +
+ ) : null} +
+ ) +} diff --git a/web/src/components/ToolCard/views/_all.tsx b/web/src/components/ToolCard/views/_all.tsx index 72076192..282fb7a2 100644 --- a/web/src/components/ToolCard/views/_all.tsx +++ b/web/src/components/ToolCard/views/_all.tsx @@ -1,5 +1,5 @@ import type { ComponentType } from 'react' -import type { ToolCallBlock } from '@/chat/types' +import type { ChatToolCall, ToolCallBlock } from '@/chat/types' import type { SessionMetadataSummary } from '@/types/api' import { CodexDiffCompactView, CodexDiffFullView } from '@/components/ToolCard/views/CodexDiffView' import { CodexPatchView } from '@/components/ToolCard/views/CodexPatchView' @@ -12,6 +12,8 @@ import { MultiEditFullView, MultiEditView } from '@/components/ToolCard/views/Mu import { TodoWriteView } from '@/components/ToolCard/views/TodoWriteView' import { UpdatePlanView } from '@/components/ToolCard/views/UpdatePlanView' import { WriteView } from '@/components/ToolCard/views/WriteView' +import { GoalView } from '@/components/ToolCard/views/GoalView' +import { canShowGoalPreview, isGoalToolName } from '@/components/ToolCard/goalTools' import { getInputStringAny } from '@/lib/toolInputUtils' import { getCodexAgentFieldRows, @@ -126,7 +128,8 @@ export const toolFullViewRegistry: Record = { request_user_input: RequestUserInputView } -export function getToolViewComponent(toolName: string): ToolViewComponent | null { +export function getToolViewComponent(toolName: string, tool?: Pick): ToolViewComponent | null { + if (isGoalToolName(toolName)) return tool && canShowGoalPreview(tool) ? GoalView : null return toolViewRegistry[toolName] ?? null } diff --git a/web/src/components/ToolCard/views/_results.tsx b/web/src/components/ToolCard/views/_results.tsx index c14fde7f..6ab793df 100644 --- a/web/src/components/ToolCard/views/_results.tsx +++ b/web/src/components/ToolCard/views/_results.tsx @@ -6,6 +6,8 @@ import { MarkdownRenderer } from '@/components/MarkdownRenderer' import { ChecklistList, extractTodoChecklist } from '@/components/ToolCard/checklist' import { basename, resolveDisplayPath } from '@/utils/path' import { getInputStringAny } from '@/lib/toolInputUtils' +import { isGoalToolName, parseGoalToolResult } from '@/components/ToolCard/goalTools' +import { GoalView } from '@/components/ToolCard/views/GoalView' import { getCodexAgentActivity, getCodexAgentTargets, @@ -1070,7 +1072,14 @@ export const toolResultViewRegistry: Record = { exit_plan_mode: MarkdownResultView } +const GoalResultView: ToolViewComponent = (props) => { + return props.block.tool.state === 'completed' && parseGoalToolResult(props.block.tool.result) + ? + : +} + export function getToolResultViewComponent(toolName: string): ToolViewComponent { + if (isGoalToolName(toolName)) return GoalResultView if (toolName.startsWith('mcp__')) { return GenericResultView } diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index cfdc81fb..73441644 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -1183,6 +1183,20 @@ export default { 'session.action.syncCodexDisabledActive': 'Stop or archive the running session before syncing Codex history.', 'codexSync.manual.success.noNewMessages': 'No new Codex messages.', 'session.status.title': 'Session status', + 'tool.goal.create_goal': 'Create goal', + 'tool.goal.get_goal': 'Get goal', + 'tool.goal.update_goal': 'Update goal', + 'tool.goal.empty': 'No goal set', + 'tool.goal.tokens': '{value} tokens', + 'tool.goal.budget': 'Budget: {value} tokens', + 'tool.goal.unlimited': 'No limit', + 'tool.goal.budgetUsed': 'Token budget used', + 'tool.goal.thread': 'Thread', + 'tool.goal.created': 'Created', + 'tool.goal.updated': 'Updated', + 'tool.goal.raw': 'Raw JSON', + 'tool.goal.requested': 'Requested goal', + 'tool.goal.requestedStatus': 'Requested status', 'session.status.goal': 'Goal', 'session.status.tasks': 'Tasks', 'session.status.subagents': 'Subagents', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 2c3bf400..73b2f730 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -1181,6 +1181,20 @@ export default { 'session.action.syncCodexDisabledActive': '当前会话正在运行,停止或归档后才能同步 Codex 历史。', 'codexSync.manual.success.noNewMessages': '没有新的 Codex 消息。', 'session.status.title': '会话状态', + 'tool.goal.create_goal': '创建目标', + 'tool.goal.get_goal': '查看目标', + 'tool.goal.update_goal': '更新目标', + 'tool.goal.empty': '未设置目标', + 'tool.goal.tokens': '{value} token', + 'tool.goal.budget': '预算:{value} token', + 'tool.goal.unlimited': '无限制', + 'tool.goal.budgetUsed': 'Token 预算用量', + 'tool.goal.thread': '会话', + 'tool.goal.created': '创建时间', + 'tool.goal.updated': '更新时间', + 'tool.goal.raw': '原始 JSON', + 'tool.goal.requested': '请求的目标', + 'tool.goal.requestedStatus': '请求的状态', 'session.status.goal': '目标', 'session.status.tasks': '任务', 'session.status.subagents': '子代理', From efc9004fda5c8fd30f876efdebd8f47aaa1b64ff Mon Sep 17 00:00:00 2001 From: Matvey Rudoy <75200069+mrudybtw@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:13:53 +0300 Subject: [PATCH 24/34] feat(web): add Russian locale and detect initial language (#1958) * feat(web): add Russian locale - Add web/src/lib/locales/ru.ts - Register 'ru' in the locale registry, i18n context, language switcher and settings - Format outline timestamps with the day.month convention for 'ru' * feat(web): detect initial locale from Telegram and browser The Telegram Mini App runs in its own web view, so a language chosen in the browser does not carry over and the app always opened in English. Pick the first session locale from an explicit stored choice, then the Telegram user's language_code, then navigator.language, then English. * feat(web): translate the newly localized strings Russian values for the keys added by the hardcoded-string fix (see the separate web i18n PR). Keeping them on this branch so the locale PR is complete when both land. * feat(web): add Russian for the newly localized strings * fix(web): recheck the Telegram language after a slow SDK load * fix(web): keep a manual language choice over late Telegram detection --------- Co-authored-by: mrudy --- web/src/chat/presentation.ts | 7 +- web/src/components/LanguageSwitcher.tsx | 1 + web/src/components/settings/SettingsNav.tsx | 2 +- web/src/hooks/useTelegram.ts | 1 + web/src/lib/i18n-context.test.ts | 140 ++ web/src/lib/i18n-context.tsx | 109 +- web/src/lib/locales/index.ts | 1 + web/src/lib/locales/ru.ts | 1284 +++++++++++++++++++ web/src/routes/settings/general.tsx | 1 + 9 files changed, 1537 insertions(+), 9 deletions(-) create mode 100644 web/src/lib/i18n-context.test.ts create mode 100644 web/src/lib/locales/ru.ts diff --git a/web/src/chat/presentation.ts b/web/src/chat/presentation.ts index 5877bbcf..09b4bf07 100644 --- a/web/src/chat/presentation.ts +++ b/web/src/chat/presentation.ts @@ -45,7 +45,7 @@ export function formatMessageTimestamp(date: Date, now: Date = new Date()): stri export function formatOutlineTimestamp( date: Date, - locale: 'en' | 'zh-CN', + locale: 'en' | 'zh-CN' | 'ru', now: Date = new Date() ): string { const sameDay = date.getFullYear() === now.getFullYear() @@ -67,6 +67,11 @@ export function formatOutlineTimestamp( return `${dateLabel} ${time}` } + if (locale === 'ru') { + const dateLabel = sameYear ? `${day}.${month}` : `${day}.${month}.${year}` + return `${dateLabel} ${time}` + } + const dateLabel = sameYear ? `${month}/${day}` : `${year}/${month}/${day}` return `${dateLabel} ${time}` } diff --git a/web/src/components/LanguageSwitcher.tsx b/web/src/components/LanguageSwitcher.tsx index 45fbbf8e..fa8243c4 100644 --- a/web/src/components/LanguageSwitcher.tsx +++ b/web/src/components/LanguageSwitcher.tsx @@ -4,6 +4,7 @@ import { useTranslation, type Locale } from '@/lib/use-translation' const locales: { value: Locale; label: string }[] = [ { value: 'en', label: 'English' }, { value: 'zh-CN', label: '简体中文' }, + { value: 'ru', label: 'Русский' }, ] function LanguageIcon() { diff --git a/web/src/components/settings/SettingsNav.tsx b/web/src/components/settings/SettingsNav.tsx index 5e4fbea5..d8038d2b 100644 --- a/web/src/components/settings/SettingsNav.tsx +++ b/web/src/components/settings/SettingsNav.tsx @@ -30,7 +30,7 @@ export function SettingsNav(props: { activeId?: string; mobile?: boolean }) { const { composerEnterBehavior } = useComposerEnterBehavior() const summaries: Record = { - general: locale === 'zh-CN' ? '简体中文' : 'English', + general: locale === 'zh-CN' ? '简体中文' : locale === 'ru' ? 'Русский' : 'English', display: `${t(`settings.display.appearance.${appearance}`)} · ${Math.round(fontScale * 100)}%`, chat: t(`settings.chat.enterBehavior.${composerEnterBehavior}`), voice: t('settings.hub.voice.summary'), diff --git a/web/src/hooks/useTelegram.ts b/web/src/hooks/useTelegram.ts index 4d52d088..60c3967e 100644 --- a/web/src/hooks/useTelegram.ts +++ b/web/src/hooks/useTelegram.ts @@ -40,6 +40,7 @@ export type TelegramWebAppUser = { username?: string first_name: string last_name?: string + language_code?: string } export type TelegramWebAppInitDataUnsafe = { diff --git a/web/src/lib/i18n-context.test.ts b/web/src/lib/i18n-context.test.ts new file mode 100644 index 00000000..753b5d2a --- /dev/null +++ b/web/src/lib/i18n-context.test.ts @@ -0,0 +1,140 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + applyLateTelegramLocale, + detectInitialLocale, + normalizeLocaleTag, + resolveLateTelegramLocale +} from './i18n-context' + +function setTelegramLanguage(code: string | undefined) { + if (code === undefined) { + delete (window as unknown as { Telegram?: unknown }).Telegram + return + } + ;(window as unknown as { Telegram?: unknown }).Telegram = { + WebApp: { initDataUnsafe: { user: { language_code: code } } } + } +} + +beforeEach(() => { + localStorage.clear() + setTelegramLanguage(undefined) +}) + +afterEach(() => { + localStorage.clear() + setTelegramLanguage(undefined) + vi.restoreAllMocks() +}) + +describe('normalizeLocaleTag', () => { + it('maps Russian tags', () => { + expect(normalizeLocaleTag('ru')).toBe('ru') + expect(normalizeLocaleTag('ru-RU')).toBe('ru') + expect(normalizeLocaleTag('RU')).toBe('ru') + expect(normalizeLocaleTag('ru_RU')).toBe('ru') + }) + + it('maps Chinese tags to the simplified locale we ship', () => { + expect(normalizeLocaleTag('zh')).toBe('zh-CN') + expect(normalizeLocaleTag('zh-Hans')).toBe('zh-CN') + expect(normalizeLocaleTag('zh-CN')).toBe('zh-CN') + expect(normalizeLocaleTag('zh_CN')).toBe('zh-CN') + }) + + it('maps English tags', () => { + expect(normalizeLocaleTag('en')).toBe('en') + expect(normalizeLocaleTag('en-US')).toBe('en') + }) + + it('rejects unsupported or empty tags', () => { + expect(normalizeLocaleTag('de')).toBeNull() + expect(normalizeLocaleTag('')).toBeNull() + expect(normalizeLocaleTag(null)).toBeNull() + expect(normalizeLocaleTag(undefined)).toBeNull() + }) +}) + +describe('detectInitialLocale', () => { + it('prefers an explicit stored choice over Telegram', () => { + localStorage.setItem('hapi-lang', 'en') + setTelegramLanguage('ru') + + expect(detectInitialLocale()).toBe('en') + }) + + it('uses the Telegram Mini App language when nothing is stored', () => { + setTelegramLanguage('ru') + + expect(detectInitialLocale()).toBe('ru') + }) + + it('normalizes the Telegram language tag', () => { + setTelegramLanguage('zh-hans') + + expect(detectInitialLocale()).toBe('zh-CN') + }) + + it('falls back to the browser language', () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('ru-RU') + + expect(detectInitialLocale()).toBe('ru') + }) + + it('falls back to English for unsupported languages', () => { + setTelegramLanguage('de') + vi.spyOn(navigator, 'language', 'get').mockReturnValue('de-DE') + + expect(detectInitialLocale()).toBe('en') + }) +}) + +describe('resolveLateTelegramLocale', () => { + it('picks up the language when the SDK appears after the timeout', async () => { + vi.useFakeTimers() + setTelegramLanguage(undefined) + + const pending = resolveLateTelegramLocale(500, 5) + await vi.advanceTimersByTimeAsync(1500) + setTelegramLanguage('ru') + await vi.advanceTimersByTimeAsync(500) + + await expect(pending).resolves.toBe('ru') + vi.useRealTimers() + }) + + it('resolves null when the SDK never loads', async () => { + vi.useFakeTimers() + setTelegramLanguage(undefined) + + const pending = resolveLateTelegramLocale(500, 2) + await vi.advanceTimersByTimeAsync(1500) + + await expect(pending).resolves.toBeNull() + vi.useRealTimers() + }) +}) + +describe('applyLateTelegramLocale', () => { + it('applies the detected locale when nothing is stored', () => { + const apply = vi.fn() + + expect(applyLateTelegramLocale('ru', apply)).toBe(true) + expect(apply).toHaveBeenCalledWith('ru') + }) + + it('does not override a manual choice made while the SDK loaded', () => { + localStorage.setItem('hapi-lang', 'en') + const apply = vi.fn() + + expect(applyLateTelegramLocale('ru', apply)).toBe(false) + expect(apply).not.toHaveBeenCalled() + }) + + it('ignores a null detection', () => { + const apply = vi.fn() + + expect(applyLateTelegramLocale(null, apply)).toBe(false) + expect(apply).not.toHaveBeenCalled() + }) +}) diff --git a/web/src/lib/i18n-context.tsx b/web/src/lib/i18n-context.tsx index 99979c56..1f80c7c7 100644 --- a/web/src/lib/i18n-context.tsx +++ b/web/src/lib/i18n-context.tsx @@ -1,7 +1,8 @@ import { createContext, useEffect, useState, useCallback, type ReactNode } from 'react' -import { en, zhCN } from './locales' +import { getTelegramWebApp, isTelegramEnvironment } from '@/hooks/useTelegram' +import { en, zhCN, ru } from './locales' -export type Locale = 'en' | 'zh-CN' +export type Locale = 'en' | 'zh-CN' | 'ru' export type Translations = Record @@ -13,7 +14,54 @@ export type I18nContextValue = { export const I18nContext = createContext(null) -const locales: Record = { en, 'zh-CN': zhCN } +const locales: Record = { en, 'zh-CN': zhCN, ru } + +/** + * Map a BCP-47-ish language tag (`ru`, `ru-RU`, `zh-Hans`, `en-US`) onto a + * supported locale. Returns null for anything we do not ship. + */ +export function normalizeLocaleTag(tag: string | null | undefined): Locale | null { + if (!tag) return null + const lower = tag.trim().toLowerCase().replace(/_/g, '-') + if (!lower) return null + if (lower === 'ru' || lower.startsWith('ru-')) return 'ru' + if (lower === 'zh' || lower.startsWith('zh-')) return 'zh-CN' + if (lower === 'en' || lower.startsWith('en-')) return 'en' + return null +} + +function readStoredLocale(): Locale | null { + try { + return normalizeLocaleTag(localStorage.getItem('hapi-lang')) + } catch { + return null + } +} + +/** + * Pick the locale for a fresh session: an explicit user choice wins, then the + * Telegram Mini App user's language, then the browser language, then English. + * Telegram runs the app in its own web view, so `localStorage` from a normal + * browser visit is not available and the language must be detected here. + */ +export function detectInitialLocale(): Locale { + const stored = readStoredLocale() + if (stored) return stored + + if (typeof window !== 'undefined') { + const telegramLocale = normalizeLocaleTag( + getTelegramWebApp()?.initDataUnsafe?.user?.language_code + ) + if (telegramLocale) return telegramLocale + } + + if (typeof navigator !== 'undefined') { + const browserLocale = normalizeLocaleTag(navigator.language) + if (browserLocale) return browserLocale + } + + return 'en' +} function interpolate(str: string, params?: Record): string { if (!params) return str @@ -23,11 +71,40 @@ function interpolate(str: string, params?: Record): str }) } +/** + * Telegram loads its SDK asynchronously and `loadTelegramSdk` gives up after a + * timeout, so the user's `language_code` can appear after the first render. + * Poll briefly for the WebApp and resolve the language once it shows up. + */ +export async function resolveLateTelegramLocale( + intervalMs = 500, + maxAttempts = 20 +): Promise { + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + const telegramLocale = normalizeLocaleTag( + getTelegramWebApp()?.initDataUnsafe?.user?.language_code + ) + if (telegramLocale) return telegramLocale + await new Promise((resolve) => setTimeout(resolve, intervalMs)) + } + return null +} + +/** + * Apply a late-detected Telegram locale unless the user has stored an explicit + * choice in the meantime. Returns true when the locale was applied. + */ +export function applyLateTelegramLocale( + detected: Locale | null, + apply: (locale: Locale) => void +): boolean { + if (!detected || readStoredLocale()) return false + apply(detected) + return true +} + export function I18nProvider({ children }: { children: ReactNode }) { - const [locale, setLocaleState] = useState(() => { - const saved = localStorage.getItem('hapi-lang') - return (saved === 'en' || saved === 'zh-CN') ? saved : 'en' - }) + const [locale, setLocaleState] = useState(() => detectInitialLocale()) const setLocale = useCallback((newLocale: Locale) => { setLocaleState(newLocale) @@ -46,6 +123,24 @@ export function I18nProvider({ children }: { children: ReactNode }) { document.documentElement.lang = locale }, [locale]) + // The Telegram SDK can finish loading after `detectInitialLocale` ran, so + // pick up the Telegram language then — unless the user chose one explicitly. + useEffect(() => { + if (typeof window === 'undefined') return + if (readStoredLocale()) return + if (!isTelegramEnvironment()) return + if (normalizeLocaleTag(getTelegramWebApp()?.initDataUnsafe?.user?.language_code)) return + + let cancelled = false + void resolveLateTelegramLocale().then((detected) => { + if (cancelled) return + applyLateTelegramLocale(detected, setLocaleState) + }) + return () => { + cancelled = true + } + }, []) + return ( {children} diff --git a/web/src/lib/locales/index.ts b/web/src/lib/locales/index.ts index e4668824..6e339e93 100644 --- a/web/src/lib/locales/index.ts +++ b/web/src/lib/locales/index.ts @@ -1,2 +1,3 @@ export { default as en } from './en' export { default as zhCN } from './zh-CN' +export { default as ru } from './ru' diff --git a/web/src/lib/locales/ru.ts b/web/src/lib/locales/ru.ts new file mode 100644 index 00000000..c3d03910 --- /dev/null +++ b/web/src/lib/locales/ru.ts @@ -0,0 +1,1284 @@ +export default { + // Состояния загрузки + 'loading': 'Загрузка…', + 'authorizing': 'Авторизация…', + 'loading.session': 'Загрузка сессии…', + 'loading.git': 'Загрузка статуса Git…', + 'loading.file': 'Загрузка файла…', + 'loading.files': 'Загрузка файлов…', + 'loading.messages': 'Загрузка сообщений…', + 'loading.machines': 'Загрузка машин…', + 'message.copy': 'Копировать', + 'message.copied': 'Скопировано', + 'message.info': 'Сведения о сообщении', + 'message.fork': 'Форк', + 'message.rewind': 'Откат', + 'message.fork.confirmTitle': 'Форк диалога', + 'message.fork.confirmDescription': 'Создать новую сессию с этого места?\nТекущая сессия не будет изменена.', + 'message.fork.confirming': 'Создание форка…', + 'message.rewind.confirmTitle': 'Откат диалога', + 'message.rewind.confirmDescription': 'Откатить эту сессию к этому месту?\nИстория диалога после этого момента будет удалена безвозвратно. Файлы изменены не будут.', + 'message.rewind.confirming': 'Откат…', + 'message.rewind.fallbackTitle': 'Откат недоступен', + 'message.rewind.fallbackDescription': 'HAPI не изменил эту сессию, поскольку её нативная граница Codex неоднозначна.\nСоздать новую сессию до этого места? Текущая сессия не будет изменена.', + 'message.rewind.fallbackFork': 'Форк здесь', + 'message.rewind.fallbackForking': 'Создание форка…', + 'message.shareTurn': 'Поделиться ходом как изображением', + 'shareTurn.title': 'Поделиться ходом как изображением', + 'shareTurn.badge': 'Общий ход', + 'shareTurn.generated': 'Создано в HAPI', + 'shareTurn.cancel': 'Отмена', + 'shareTurn.copy': 'Копировать', + 'shareTurn.copying': 'Копирование…', + 'shareTurn.copied': 'Скопировано', + 'shareTurn.share': 'Поделиться', + 'shareTurn.sharing': 'Отправка…', + 'shareTurn.download': 'Скачать', + 'shareTurn.saving': 'Сохранение…', + + // Вход / Аутентификация + 'login.title': 'HAPI', + 'login.subtitle': 'Vibe Coding — в любое время, в любом месте', + 'login.bind.title': 'Привязать Telegram', + 'login.submit': 'Войти', + 'login.bind.submit': 'Привязать', + 'login.submitting': 'Вход…', + 'login.bind.submitting': 'Привязка…', + 'login.placeholder': 'Токен доступа', + 'login.error.enterToken': 'Введите токен доступа', + 'login.error.bindingUnavailable': 'Привязка недоступна.', + 'login.error.loginUnavailable': 'Вход недоступен.', + 'login.error.bindFailed': 'Не удалось привязать', + 'login.error.authFailed': 'Ошибка аутентификации', + 'login.help': 'Нужна помощь?', + 'login.server.default': '(По умолчанию)', + 'login.server.custom': '(Свой)', + 'login.server.title': 'URL хаба', + 'login.server.description': 'Задайте origin хаба HAPI для API и живых обновлений.', + 'login.server.current': 'Текущий:', + 'login.server.origin': 'Origin хаба', + 'login.server.placeholder': 'https://hapi.example.com', + 'login.server.hint': 'Только http(s). Путь игнорируется.', + 'login.server.required': 'Требуется URL хаба. Укажите его перед входом.', + 'login.server.useSameOrigin': 'Использовать тот же origin', + 'login.server.save': 'Сохранить хаб', + 'login.footer': 'Создано с', + 'login.footer.for': 'для Vibe Coding', + 'login.footer.copyright': '©', + + // Страница сессий + 'sessions.new': 'Новая сессия', + 'sessions.empty.title': 'Сессий пока нет', + 'sessions.empty.hint': 'Запустите сессию в любой папке рабочего пространства или сначала просмотрите дерево.', + 'sessions.empty.startSession': 'Запустить сессию', + 'sessions.empty.browse': 'Просмотр рабочего пространства', + 'sessions.search.placeholder': 'Поиск по названию/пути/агенту/машине/ID…', + 'sessions.search.open': 'Поиск сессий (название, путь, агент, имя машины, ID и другое)', + 'sessions.search.clear': 'Очистить поиск', + 'sessions.search.noResults': 'Нет сессий, соответствующих фильтрам.', + 'sessions.unreadFilter.toggle': 'Только непрочитанные', + 'sessions.markAllRead.button': 'Отметить все как прочитанные ({count})', + 'sessions.markAllRead.title': 'Отметить все как прочитанные?', + 'sessions.markAllRead.description': 'Будут отмечены как прочитанные {count} непрочитанных сессий на этом устройстве.', + 'sessions.markAllRead.confirm': 'Подтвердить', + 'sessions.markAllRead.confirming': 'Отмечаем как прочитанные…', + 'sessions.timeFilter.label': 'Фильтр сессий по последней активности', + 'sessions.timeFilter.pickStart': 'Выбрать дату начала', + 'sessions.timeFilter.pickEnd': 'Выбрать дату окончания', + 'sessions.timeFilter.clear': 'Очистить', + 'sessions.timeFilter.close': 'Закрыть выбор даты', + 'sessions.timeFilter.previousMonth': 'Предыдущий месяц', + 'sessions.timeFilter.nextMonth': 'Следующий месяц', + 'sessions.timeFilter.dayWithActivity': '{date}, есть активность сессии', + 'sessions.group.expand': 'Развернуть {n}', + 'sessions.group.collapse': 'Свернуть {n}', + 'sessions.runningSection': 'В работе', + 'sessions.activeSection': 'Активные сессии', + 'sessions.group.new': 'Новая сессия в этой папке', + 'sessions.machineFilter.label': 'Фильтр сессий по машине', + 'sessions.machineFilter.all': 'Все', + 'codexSync.tooltip': 'Импортировать сессии из Codex в Hapi', + 'codexSync.newSessionAction': 'Импорт истории Codex', + 'codexSync.confirm.title': 'Импорт сессий Codex', + 'codexSync.confirm.description': 'Выберите сессии Codex для импорта в Hapi', + 'piImport.inline.title': 'Импорт истории Pi', + 'piImport.inline.description': 'Необязательно: выберите существующую локальную сессию Pi для импорта и продолжения.', + 'piImport.inline.clear': 'Очистить', + 'piImport.inline.choose': 'Выбрать историю', + 'piImport.dialog.title': 'Импорт сессий Pi', + 'piImport.dialog.description': 'Выберите локальные истории Pi. Один выбор продолжается сразу; несколько выборов импортируются в фоне.', + 'piImport.dialog.concurrentWarning': 'Несколько процессов могут открыть одну и ту же сессию Pi, но избегайте записи из устаревших копий. Перед продолжением в HAPI перезагрузите или закройте любой другой процесс Pi, чтобы избежать непреднамеренного ответвления.', + 'piImport.loading': 'Сканирование сессий Pi…', + 'piImport.empty': 'Не найдено сессий Pi для импорта.', + 'piImport.selectedCount': 'Выбрано: {n}', + 'piImport.clearAll': 'Очистить все', + 'piImport.selectAll': 'Выбрать все', + 'piImport.allDirectories': 'Все каталоги', + 'piImport.search': 'Поиск по названию, запросу, пути, модели или ID', + 'piImport.imported': 'Импортировано', + 'piImport.needsAttention': 'Требует внимания', + 'piImport.messages': 'сообщений', + 'piImport.importing': 'Импорт…', + 'piImport.confirm': 'Импортировать', + 'piImport.success.title': 'Сессии Pi импортированы', + 'piImport.success.body': 'Импортировано сессий Pi: {n}.', + 'piImport.failed.title': 'Не удалось импортировать Pi', + 'piImport.failed.body': 'Не удалось импортировать историю Pi.', + 'piImport.failed.partial': 'Не удалось импортировать сессий: {failed}. Причина: {reason}', + 'piImport.error.diverged': 'Локальная ветка Pi изменилась после предыдущего импорта. Проверьте сессию перед продолжением.', + 'piImport.error.active': 'Остановите активную сессию Hapi Pi перед импортом более новой нативной истории.', + 'piImport.manual.success.title': 'Синхронизация истории Pi завершена', + 'piImport.manual.success.body': 'Синхронизировано новых элементов истории Pi: {n}.', + 'piImport.manual.success.noNewMessages': 'История Pi уже актуальна.', + 'piImport.manual.failed.title': 'Не удалось синхронизировать историю Pi', + // Комментарий: ниже — тексты для списка с множественным выбором в диалоге импорта, состояния загрузки и подсказки кнопки перезапуска клиента Codex в правом верхнем углу. + 'codexSync.confirm.selectAll': 'Выбрать все', + 'codexSync.confirm.clearAll': 'Очистить все', + 'codexSync.confirm.selectedCount': 'Выбрано сессий: {n}', + 'codexSync.confirm.empty': 'Локальные сессии Codex не найдены', + 'codexSync.confirm.current': 'Связано', + 'codexSync.confirm.cwd': 'Рабочий каталог', + 'codexSync.confirm.cwdFilter': 'Рабочий каталог', + 'codexSync.confirm.cwdFilterAll': 'Все рабочие каталоги', + 'codexSync.confirm.emptyForWorkdir': 'Нет сессий Codex в этом рабочем каталоге', + 'codexSync.confirm.confirm': 'Импортировать', + 'codexSync.confirm.confirming': 'Импорт…', + 'codexSync.confirm.loading': 'Загрузка локальных сессий Codex…', + 'codexSync.success.title': 'Импорт завершён', + 'codexSync.success.body': 'Импортировано сессий Codex в Hapi: {n}.', + 'codexSync.manual.success.title': 'Синхронизация Codex завершена', + 'codexSync.manual.success.body': 'Синхронизировано сессий Codex: {n}.', + 'codexSync.manual.failed.title': 'Не удалось синхронизировать сессию Codex', + 'codexSync.error.timeout': 'Время операции истекло', + 'codexSync.error.active': 'Эта сессия ещё активна. Дождитесь её завершения и повторите.', + 'codexSync.failed.title': 'Не удалось импортировать сессии Codex', + 'codexSync.failed.body': 'Не удалось импортировать сессии Codex.', + 'codexSync.failed.bodyWithReason': 'Импорт не удался: {reason}', + 'codexSync.restart.tooltip': 'Перезапустить клиент Codex', + 'codexSync.restart.title': 'Перезапустить клиент Codex', + 'codexSync.restart.description': 'Перезапустить клиент Codex сейчас, чтобы обновить сессии?', + 'codexSync.restart.confirm': 'Перезапустить', + 'codexSync.restart.confirming': 'Перезапуск…', + 'codexSync.restart.failed.title': 'Не удалось перезапустить клиент Codex', + 'codexSync.restart.failed.notFound': 'Не удалось перезапустить клиент Codex: не установлен или не найден', + 'codexSync.restart.failed.body': 'Не удалось выполнить скрипт перезапуска.', + 'codexSync.restart.started.title': 'Перезапуск запущен', + 'codexSync.restart.started.body': 'Клиент Codex перезапускается для обновления сессий.', + 'codexSync.duplicates.confirm.title': 'Обнаружены дубликаты сессий', + 'codexSync.duplicates.confirm.description': 'Обнаружены дубликаты сессий. Объединить их?', + 'codexSync.duplicates.confirm.confirm': 'Объединить', + 'codexSync.duplicates.confirm.confirming': 'Объединение…', + 'codexSync.duplicates.detect.failed.title': 'Не удалось обнаружить дубликаты сессий', + 'codexSync.duplicates.detect.failed.body': 'Не удалось обнаружить дубликаты сессий.', + 'codexSync.duplicates.merge.success.title': 'Дубликаты сессий объединены', + 'codexSync.duplicates.merge.success.body': 'Объединены дубликаты выбранных сессий Codex.', + 'codexSync.duplicates.merge.failed.title': 'Не удалось объединить дубликаты сессий', + 'codexSync.duplicates.merge.failed.body': 'Не удалось объединить дубликаты сессий.', + + // Список сессий + 'session.item.path': 'путь', + 'session.item.agent': 'агент', + 'session.item.model': 'модель', + 'session.item.machine': 'машина', + 'session.modelChange.pending': 'Изменение…', + 'session.modelChange.cursorAutoRestart': 'Авто (для переключения обратно нужен перезапуск)', + 'session.modelChange.pendingTooltip': 'Модель изменится, когда текущая задача завершится.', + 'session.item.worktree': 'рабочее дерево', + 'session.item.pending': 'ожидание', + 'session.item.thinking': 'размышление', + 'session.item.running': 'Выполняется', + 'session.item.active': 'Активна', + 'session.item.idle': 'Простаивает (только keepalive)', + 'session.item.permission': 'Требуется разрешение', + 'session.item.needsInput': 'Нужен ввод', + 'session.item.background': 'Выполняются фоновые задачи', + 'session.item.newActivity': 'Новая активность', + 'session.item.scheduledMessage': 'Ожидает отложенное сообщение', + 'session.item.scheduledMessages': 'Ожидает отложенных сообщений: {count}', + 'session.tooltip.permission.body': 'Одобрить:', + 'session.tooltip.input.body': 'Ответить:', + 'session.tooltip.background.count.one': 'Выполняется 1 задача', + 'session.tooltip.background.count.other': 'Выполняется задач: {count}', + 'session.tooltip.scheduled.body': 'Сработает по наступлении срока.', + 'session.tooltip.scheduled.fires': 'Сработает {when}', + 'session.tooltip.scheduled.next': 'Следующее {when} · ещё +{more}', + 'session.tooltip.moreCount': 'ещё +{count}', + 'session.time.justNow': 'только что', + 'session.time.minutesAgo': '{n} мин назад', + 'session.time.hoursAgo': '{n} ч назад', + 'session.time.daysAgo': '{n} дн назад', + 'session.time.inLessThanMinute': 'через <1 мин', + 'session.time.inMinutes': 'через {n} мин', + 'session.time.inHours': 'через {n} ч', + 'session.time.inDays': 'через {n} дн', + 'session.time.soon': 'скоро', + 'session.time.importedFromCodex.justNow': 'только что импортировано из Codex', + 'session.time.importedFromCodex.minutesAgo': 'импортировано из Codex {n} мин назад', + 'session.time.importedFromCodex.hoursAgo': 'импортировано из Codex {n} ч назад', + 'session.time.importedFromCodex.daysAgo': 'импортировано из Codex {n} дн назад', + 'session.cursorMigration.banner.title': 'Обновление сессии Cursor', + 'session.cursorMigration.banner.body': 'Переключение этого устаревшего чата на более безопасный протокол ACP. Для сессий с длинной историей это занимает 15–20 секунд; ваш диалог возобновится автоматически, а любой черновой текст сохранится.', + 'session.cursorMigration.bannerAmbiguous.title': 'Обновление сессии Cursor требует проверки вручную', + 'session.cursorMigration.bannerAmbiguous.body': 'Этот чат существует на диске в нескольких папках рабочего пространства, либо размер на диске не совпадает с синхронизированной историей, поэтому HAPI отказался переносить его автоматически. Проверьте логи хаба на предмет списка кандидатов (поиск по «[migrator] ambiguous legacy store» или «[migrator] size sanity check refused»), удалите устаревшие папки в ~/.cursor/chats/ и откройте сессию заново.', + + // Неактивная сессия + 'session.inactive.autoResume': 'Эта сессия неактивна. Отправьте сообщение, чтобы возобновить.', + 'session.inactive.cannotResume': 'Эта сессия неактивна и не может быть возобновлена.', + + // Шапка сессии + 'session.title': 'Файлы', + 'session.view.returnToChat': 'Вернуться к диалогу', + 'session.more': 'Дополнительные действия', + 'session.outline.open': 'План диалога', + 'session.outline.close': 'Закрыть план', + 'session.outline.title': 'План', + 'session.outline.loadOlder': 'Загрузить более ранние', + 'session.outline.empty': 'В загруженных сообщениях нет элементов плана', + 'session.outline.searchPlaceholder': 'Поиск по плану', + 'session.outline.searchLabel': 'Поиск элементов плана', + 'session.outline.searchResults': '{matched} из {total} элементов', + 'session.outline.noSearchResults': 'Нет подходящих элементов плана', + + // Действия с сессией + 'session.action.rename': 'Переименовать', + 'session.action.pinProject': 'Закрепить в проекте', + 'session.action.unpinProject': 'Открепить от проекта', + 'session.action.pinGlobal': 'Закрепить глобально', + 'session.action.unpinGlobal': 'Открепить глобально', + 'session.action.pinFailed': 'Не удалось изменить закрепление', + 'sessions.pinnedSection': 'Закреплённые сессии', + 'session.action.export': 'Экспортировать диалог', + 'session.action.markUnread': 'Отметить как непрочитанную', + 'session.action.syncCodex': 'Синхронизировать Codex', + 'session.action.syncPi': 'Синхронизировать историю Pi', + 'session.action.archive': 'Архивировать', + 'session.action.reopen': 'Открыть заново', + 'session.action.reopenCursorChecking': 'Проверка доступности данных чата Cursor на записанной машине.', + 'session.action.reopenCursorMissing': 'Данные чата Cursor больше недоступны на записанной машине.', + 'session.action.reopenCursorCheckFailed': 'Не удалось проверить данные чата Cursor на записанной машине.', + 'session.action.reopenCursorUnverified': 'Не удалось проверить данные чата Cursor (раннер может быть устаревшим). Повторное открытие всё ещё доступно — обновите CLI на той машине, если оно не сработает.', + 'runner.skew.updateRequired': 'ТРЕБУЕТСЯ ОБНОВЛЕНИЕ', + 'runner.skew.banner.title': 'Раннер устарел на {host}', + 'runner.skew.banner.body': 'Этому хабу нужна более новая версия HAPI CLI на {host} (сейчас {version}). Обновите CLI на той машине, затем перезапустите раннер (`systemctl --user restart hapi-runner` или `hapi runner start`). Этот баннер будет отображаться, пока раннер не сообщит о наличии требуемых возможностей.', + 'runner.skew.banner.bodyUnknownVersion': 'Этому хабу нужна более новая версия HAPI CLI на {host}. Обновите CLI на той машине, затем перезапустите раннер (`systemctl --user restart hapi-runner` или `hapi runner start`). Этот баннер будет отображаться, пока раннер не сообщит о наличии требуемых возможностей.', + 'runner.skew.banner.summaryTitle': 'Устаревших раннеров: {count}', + 'runner.skew.banner.summaryBody': 'Обновите HAPI CLI на каждом хосте ниже, затем перезапустите соответствующий раннер. Сверните или отложите этот баннер, чтобы добраться до сессий под ним.', + 'runner.skew.banner.minimized': 'Устаревших раннеров: {count} ({hosts}) — нажмите, чтобы развернуть', + 'runner.skew.banner.minimize': 'Свернуть', + 'runner.skew.banner.dismissTemp': 'Отложить на 1 ч', + 'runner.skew.banner.restart': 'Перезапустить раннер', + 'runner.skew.banner.restartUnavailable': 'Сначала обновите CLI', + 'runner.skew.banner.restartNeedsNewerBinary': 'Перезапуск поможет только после установки более новой версии HAPI CLI на этом хосте. Он не скачивает пакеты.', + 'runner.skew.banner.restartNeedsSupervisor': 'Перезапуск работает только когда раннер под наблюдением (HAPI_RUNNER_SUPERVISED=1 / systemd). Остановка без наблюдателя оставит хост офлайн.', + 'runner.skew.banner.restarting': 'Перезапуск…', + 'runner.skew.banner.binaryUpdatedHint': '(на диске уже более новая версия CLI — раннер скоро перезапустится сам)', + 'runner.skew.banner.upgradeCliFirst': '(на диске ещё нет более новой версии CLI — установите/обновите на этом хосте)', + 'runner.skew.banner.handoffHint': 'После обновления CLI на хосте этот раннер обычно перезапускается сам (передача версии). Перезапуск здесь только останавливает раннер под наблюдением, чтобы systemd/pm2 перезапустил его — никогда не используйте на раннере отдельного ноутбука.', + 'runner.skew.restartFailed': 'Не удалось перезапустить раннер', + 'session.action.delete': 'Удалить', + 'session.action.copy': 'Копировать', + 'session.action.copyReference': 'Копировать ссылку', + + // Диалоги + 'dialog.uri.title': 'Открыть эту ссылку?', + 'dialog.uri.description': 'Эта ссылка использует пользовательскую схему URI. Убедитесь, что доверяете этой ссылке, прежде чем открывать её.', + 'dialog.uri.open': 'Открыть', + 'dialog.uri.alwaysAllow': 'Всегда разрешать {scheme}:', + 'dialog.rename.title': 'Переименовать сессию', + 'dialog.rename.placeholder': 'Название сессии', + 'dialog.rename.save': 'Сохранить', + 'dialog.rename.saving': 'Сохранение…', + 'dialog.rename.error': 'Не удалось переименовать. Попробуйте ещё раз.', + 'dialog.rename.generate': 'Сгенерировать', + 'dialog.rename.generating': 'Генерация…', + 'dialog.rename.generateError': 'Не удалось сгенерировать название. Попробуйте ещё раз.', + 'dialog.archive.title': 'Архивировать сессию', + 'dialog.archive.description': 'Вы уверены, что хотите архивировать «{name}»? Активная сессия будет отключена.', + 'dialog.archive.confirm': 'Архивировать', + 'dialog.archive.confirming': 'Архивирование…', + 'dialog.reopen.errorTitle': 'Не удалось открыть сессию заново', + 'dialog.reopen.dismiss': 'Закрыть', + 'dialog.delete.title': 'Удалить сессию', + 'dialog.delete.description': 'Вы уверены, что хотите удалить «{name}»? Это действие необратимо.', + 'dialog.delete.scratchlist.one': 'Также будет удалена 1 запись блокнота.', + 'dialog.delete.scratchlist.other': 'Также будут удалены записи блокнота: {n}.', + 'dialog.delete.confirm': 'Удалить', + 'dialog.delete.confirming': 'Удаление…', + 'dialog.error.default': 'Операция не удалась. Попробуйте ещё раз.', + + // Экспорт сессии + 'session.export.title': 'Экспорт диалога', + 'session.export.description': 'Выберите формат, затем скачайте весь видимый диалог и записи блокнота.', + 'session.export.format.json': 'JSON', + 'session.export.format.json.description': 'Полные данные без потерь: метаданные сессии, сообщения и записи блокнота (только метаданные вложений).', + 'session.export.format.markdown': 'Markdown', + 'session.export.format.markdown.description': 'Читаемое представление, сгенерированное из тех же данных экспорта.', + 'session.export.download': 'Скачать', + 'session.export.downloadAnyway': 'Скачать в любом случае', + 'session.export.downloading': 'Экспорт…', + 'session.export.warning.title': 'Большой экспорт', + 'session.export.warning.description': 'Этот экспорт содержит {count} сообщений и оценивается в {size}. Это превышает рекомендуемый порог в {limit} сообщений.', + 'session.export.error.noApi': 'Нет соединения с сервером', + 'session.export.error.tooLarge': 'Этот экспорт слишком велик для безопасной подготовки ({count} сообщений, {size}; максимум {maxSize}).', + 'session.export.error.default': 'Не удалось экспортировать диалог', + 'session.export.toast.success.title': 'Диалог экспортирован', + 'session.export.toast.success.body': 'Скачан {filename}', + 'session.export.toast.error.title': 'Экспорт не удался', + + // Диаграммы Mermaid + 'mermaid.openFullscreen': 'Открыть диаграмму на весь экран', + 'mermaid.viewerTitle': 'Диаграмма', + 'mermaid.loading': 'Загрузка диаграммы…', + 'mermaid.renderError': 'Не удалось отобразить диаграмму.', + + // Общие кнопки + 'button.cancel': 'Отмена', + 'button.save': 'Сохранить', + 'button.confirm': 'Подтвердить', + 'button.close': 'Закрыть', + 'button.dismiss': 'Закрыть', + 'button.copy': 'Копировать', + 'button.paste': 'Вставить', + + // Форма новой сессии + 'newSession.title': 'Создать сессию', + 'newSession.machine': 'Машина', + 'newSession.directory': 'Каталог', + 'newSession.placeholder': '/путь/к/проекту', + 'newSession.browse': 'Обзор', + 'newSession.recent': 'Недавние пути', + 'newSession.type': 'Тип сессии', + 'newSession.type.simple': 'Обычная', + 'newSession.type.simple.desc': 'Использовать выбранный каталог как есть', + 'newSession.type.worktree': 'Рабочее дерево', + 'newSession.type.worktree.desc': 'Создать новое рабочее дерево рядом с репозиторием (Cursor использует нативные ~/.cursor/worktrees)', + 'newSession.type.worktree.placeholder': 'feature-x (по умолчанию 1228-xxxx)', + 'newSession.agent': 'Агент', + 'newSession.agentAvailabilityLoading': 'Проверка установленных агентов…', + 'newSession.agentAvailabilityFailed': 'Не удалось проверить установленные агенты.', + 'newSession.runnerUpgradeRequired': 'Перед созданием сессий обновите и перезапустите раннер HAPI на этой машине.', + 'newSession.noAvailableAgents': 'На этой машине не установлены поддерживаемые агенты.', + 'newSession.agentUnavailable': 'Выбранный агент больше недоступен на этой машине. Обновите список и выберите другого агента.', + 'newSession.directoryOutsideWorkspaceRoots': 'Каталог должен находиться внутри одного из корней рабочего пространства этой машины.', + 'newSession.model': 'Модель', + 'newSession.effort': 'Усилия', + 'newSession.model.optional': 'необязательно', + 'newSession.model.default': 'По умолчанию', + 'newSession.model.loadFailed': 'Не удалось загрузить модели', + 'newSession.model.selectVariant': 'Выбрать вариант', + 'newSession.model.cursorUnavailable': 'Моделей Cursor пока нет. Запустите сессию Cursor один раз или используйте Auto.', + 'newSession.agyModel.fetchingModels': 'Получение доступных моделей…', + 'newSession.agyModel.authRequired': 'Требуется аутентификация', + 'newSession.agyModel.authHint': 'Выполните `agy` в терминале, чтобы войти через Google.', + 'newSession.agyModel.retry': 'Повторить', + 'newSession.agyModel.notListed': 'больше не в списке', + 'newSession.agyModel.noModels': 'Нет доступных моделей Antigravity', + 'newSession.opencodeModel.loading': 'Поиск моделей OpenCode…', + 'newSession.opencodeModel.loadFailed': 'Не удалось загрузить модели OpenCode', + 'newSession.opencodeModel.retry': 'Повторить', + 'newSession.opencodeModel.empty': 'Для этого каталога не найдено моделей OpenCode', + 'newSession.opencodeModel.default': 'По умолчанию', + 'newSession.permission.managedTitle': 'Управляется агентом', + 'newSession.permission.managedDesc': 'Этот агент управляет своими разрешениями самостоятельно. Режим YOLO недоступен.', + 'newSession.reasoningEffort': 'Уровень рассуждений', + 'newSession.collaborationMode': 'Режим совместной работы', + 'newSession.copilotAgentMode': 'Режим агента', + 'newSession.fastMode': 'Быстрый режим', + 'newSession.yolo': 'Режим YOLO', + 'newSession.yolo.title': 'Обойти подтверждения и песочницу', + 'newSession.yolo.desc': 'Использует опасные флаги агента при запуске.', + 'newSession.yolo.mapsTo': 'Применяет нативный режим {mode}.', + 'newSession.grokAutoUnavailable': 'недоступно', + 'newSession.grokAutoUnavailableDesc': 'Grok не включил автоматические разрешения для этой учётной записи или сборки CLI.', + 'newSession.create': 'Создать', + 'newSession.creating': 'Создание…', + 'button.retry': 'Повторить', + + 'session.directoryMissingSimple': 'Каталог не существует. При создании сессии он будет создан автоматически.', + 'session.directoryMissingSimpleConfirm': 'Каталог не существует. Нажмите ещё раз, чтобы создать его автоматически.', + 'session.directoryMissingWorktree': 'Сессии с рабочим деревом требуют существующего каталога репозитория.', + 'session.codexModelsLoadFailed': 'Не удалось загрузить модели Codex', + 'session.createAndCreateDirectory': 'Создать и создать каталог', + + // Машина + 'machine.unknown': 'Неизвестная платформа', + 'machine.os.windows': 'Windows', + 'machine.os.linux': 'Linux', + 'machine.os.macos': 'macOS', + 'machine.os.unknown': 'Неизвестная ОС', + 'machine.header.sessionCount': 'Сессий: {n}', + 'machine.health.tooltip.title': 'Ёмкость машины', + 'machine.health.status.healthy': 'В норме — есть место для новых агентов', + 'machine.health.status.elevated': 'Повышенная — новые агенты могут работать медленнее', + 'machine.health.status.high': 'Высокая нагрузка — лучше не запускать здесь новые', + 'machine.health.status.unknown': 'Метрики недоступны', + 'machine.health.metric.cpu': 'ЦП', + 'machine.health.metric.ram': 'ОЗУ', + 'machine.health.tooltip.load': 'Очередь выполнения (1 мин): {value}', + 'machine.health.tooltip.loadShort': 'Нагрузка (1м)', + 'machine.health.tooltip.uptimeShort': 'Аптайм', + 'machine.health.uptimeCompact': 'работает {value}', + 'machine.health.tooltip.hint': 'Обновляется примерно каждые 20 с раннером на этой машине', + 'machine.health.aria.cpu': 'ЦП {n} процентов', + 'machine.health.aria.ram': 'ОЗУ {n} процентов', + 'machine.health.aria.unknown': 'Состояние машины недоступно', + + // Чат + 'chat.placeholder': 'Введите сообщение…', + 'chat.send': 'Отправить', + 'chat.abort': 'Прервать', + 'chat.settings': 'Настройки', + 'chat.terminal': 'Терминал', + 'chat.switchRemote': 'Переключиться в удалённый режим', + 'chat.sendError.fallback': 'Не удалось отправить сообщение. Отредактируйте и попробуйте ещё раз.', + 'chat.sendError.sessionInactive': 'Эта сессия заархивирована. Откройте её заново, чтобы отправить сообщение.', + 'chat.sendError.sessionInactive.action': 'Открыть заново', + + // Обзор Codex + 'codexReview.title': 'Обзор Codex', + 'codexReview.findings': 'Находок: {count}', + 'codexReview.confidence': 'Уверенность {value}', + 'codexReview.location.missing': 'Нет местоположения', + + // Терминал + 'terminal.commandName': 'Команда', + 'terminal.commandMessage': 'Сообщение команды', + 'terminal.commandArgs': 'Аргументы команды', + 'terminal.stdout': 'Stdout', + 'terminal.stderr': 'Stderr', + 'terminal.unsupportedWindows': 'Удалённый терминал недоступен на этом хосте.', + 'terminal.retry': 'Повторить', + 'terminal.inputMode.label': 'Режим ввода терминала', + 'terminal.inputMode.command': 'Команда', + 'terminal.inputMode.direct': 'Прямой', + 'terminal.command.placeholder': 'Введите команду…', + 'terminal.command.inputLabel': 'Ввод команды', + 'terminal.command.run': 'Выполнить команду', + 'terminal.command.shortcuts': 'Основные команды', + 'terminal.direct.pages': 'Страницы прямых клавиш', + 'terminal.direct.page.control': 'Управление', + 'terminal.direct.page.navigation': 'Навигация', + 'terminal.direct.page.shell': 'Оболочка', + 'terminal.direct.page.symbols': 'Символы', + 'terminal.paste.fallbackTitle': 'Вставить ввод', + 'terminal.paste.fallbackDescription': 'Чтение из буфера обмена недоступно. Вставьте текст ниже.', + 'terminal.paste.placeholder': 'Вставьте ввод терминала сюда…', + + // Блок кода + 'code.copy': 'Копировать', + 'code.truncated': 'Предпросмотр обрезан — откройте детали для полного вывода', + 'code.wrap.enable': 'Включить перенос строк', + 'code.wrap.disable': 'Отключить перенос строк', + + // Просмотр изменений + 'diff.title': 'Изменения', + 'diff.view': 'Просмотр', + + // Страница файлов + 'files.page.title': 'Файлы', + 'files.page.refresh': 'Обновить', + 'files.page.refreshFilesystem': 'Обновить вид файловой системы', + 'files.page.searchPlaceholder': 'Поиск файлов', + 'files.projectRoot': 'корень проекта', + 'files.branch.detached': 'отделённый HEAD', + 'files.branch.summary': '{staged} индексировано, {unstaged} не индексировано', + 'files.tab.changes': 'Изменения', + 'files.tab.directories': 'Каталоги', + 'files.search.empty': 'Нет файлов, соответствующих поиску.', + 'files.search.error.failed': 'Не удалось выполнить поиск файлов.', + 'files.search.error.failedWithDetail': 'Не удалось выполнить поиск файлов: {error}', + 'files.changes.section.staged': 'Индексированные изменения ({n})', + 'files.changes.section.unstaged': 'Неиндексированные изменения ({n})', + 'files.changes.empty.unavailable': 'Статус Git недоступен. Используйте «Каталоги» для просмотра всех файлов или поиск.', + 'files.changes.empty.none': 'Изменений не обнаружено. Используйте «Каталоги» для просмотра всех файлов или поиск.', + 'files.changes.error.gitStatusUnavailable': 'Статус Git недоступен.', + 'files.changes.error.gitStatusUnavailableWithDetail': 'Статус Git недоступен: {error}', + 'files.changes.error.unstagedDiffUnavailableWithDetail': 'Неиндексированные изменения недоступны: {error}', + 'files.changes.error.stagedDiffUnavailableWithDetail': 'Индексированные изменения недоступны: {error}', + 'files.directories.empty': 'Пустой каталог.', + 'files.directories.error.listFailed': 'Не удалось получить список каталога.', + 'files.directories.error.listFailedWithDetail': 'Не удалось получить список каталога: {error}', + 'files.directories.download': 'Скачать файл', + 'files.directories.downloadNamed': 'Скачать {name}', + 'files.directories.download.error.title': 'Скачивание не удалось', + 'files.directories.download.error.default': 'Не удалось скачать файл.', + 'files.sort.title': 'Сортировка файлов', + 'files.sort.by': 'Сортировать по', + 'files.sort.name': 'Имя', + 'files.sort.modified': 'Время изменения', + 'files.sort.size': 'Размер файла', + 'files.sort.nameAsc': 'От А до Я', + 'files.sort.nameDesc': 'От Я до А', + 'files.sort.oldest': 'Сначала старые', + 'files.sort.newest': 'Сначала новые', + 'files.sort.smallest': 'Сначала маленькие', + 'files.sort.largest': 'Сначала большие', + + // Контекстное меню файла + 'file.menu.title': 'Действия с файлом', + 'file.menu.copyPath': 'Копировать путь', + 'file.menu.copyAbsolutePath': 'Копировать абсолютный путь', + 'file.menu.addToComposer': 'Добавить в редактор', + + // Страница файла + 'file.page.fallbackName': 'Файл', + 'file.page.unknownPath': 'Неизвестный путь', + 'file.page.copyPath': 'Копировать путь', + 'file.page.copyContent': 'Копировать содержимое файла', + 'file.page.download': 'Скачать файл', + 'file.page.tab.diff': 'Изменения', + 'file.page.tab.file': 'Файл', + 'file.page.tab.source': 'Исходник', + 'file.page.tab.preview': 'Предпросмотр', + 'file.page.missingPath': 'Путь к файлу не указан.', + 'file.page.binary': 'Похоже, это бинарный файл. Его нельзя отобразить.', + 'file.page.imagePreviewAlt': 'Предпросмотр изображения {name}', + 'file.page.empty': 'Файл пуст.', + 'file.page.noChanges': 'Нет изменений для отображения.', + 'file.error.readFailed': 'Не удалось прочитать файл.', + 'file.error.readFailedWithDetail': 'Не удалось прочитать файл: {error}', + 'file.error.diffUnavailable': 'Изменения недоступны.', + 'file.error.diffUnavailableWithDetail': 'Изменения недоступны: {error}', + + // Встроенные медиа + 'media.displayed.image': 'Показано изображение', + 'media.displayed.video': 'Показано видео', + 'media.displayed.audio': 'Показано аудио', + 'media.displayed.file': 'Показан файл', + 'media.displayed.header': '{label}: {fileName}', + 'media.displayed.unavailable': '{label} недоступно. {error}', + + // Карточка инструмента + 'tool.askQuestion': 'Другое', + 'tool.edit': 'Правка', + 'tool.multiedit': 'Мультиправка', + 'tool.write': 'Запись', + 'tool.todo': 'Задачи', + 'tool.confirm': 'Подтвердить', + 'tool.deny': 'Отклонить', + 'tool.abort': 'Прервать', + 'tool.allow': 'Разрешить', + 'tool.allowAll': 'Разрешить все правки', + 'tool.denyAll': 'Запретить все правки', + 'tool.approved': 'Одобрено', + 'tool.rejected': 'Отклонено', + 'tool.cancel': 'Отмена', + 'tool.exitPlan': 'Выйти из режима плана', + 'tool.plan.implement': 'Реализовать план', + 'tool.plan.continue': 'Продолжить планирование', + 'tool.patch': 'Патч', + 'tool.input': 'Ввод', + 'tool.label': 'Инструмент', + 'tool.more': '+ещё {count}', + 'tool.trace': 'Трассировка', + 'tool.trace.callsSuffix': 'вызовов', + 'tool.result': 'Результат', + 'tool.duration': 'Длительность', + 'tool.startedAt': 'Начато', + 'tool.completedAt': 'Завершено', + 'tool.semanticTitle.readFile': 'Чтение файла', + 'tool.semanticTitle.runShell': 'Выполнение команды', + 'tool.semanticTitle.search': 'Поиск', + 'tool.semanticTitle.openUrl': 'Открыть URL', + 'tool.semanticTitle.query': 'Запрос', + 'tool.questionsAnswers': 'Вопросы и ответы', + 'tool.submit': 'Отправить', + 'tool.submitting': 'Отправка…', + 'tool.prev': '← Назад', + 'tool.next': 'Далее →', + 'tool.yes': 'Да', + 'tool.yesForSession': 'Да для сессии', + 'tool.allowForSession': 'Разрешить для сессии', + 'tool.abortLabel': 'Прервать', + 'tool.other': 'Другое', + 'tool.otherDescription': 'Введите свой ответ', + 'tool.question': 'Вопрос', + 'tool.selectOption': 'Выберите хотя бы один вариант или введите ответ.', + 'tool.waitingForApproval': 'Ожидание одобрения…', + 'tool.resolved': 'Разрешено в Codex', + 'tool.canceled': 'Отменено', + 'tool.approvedForSession': 'Одобрено для сессии', + 'tool.aborted': 'Прервано', + 'tool.approvedAllowAllEdits': 'Одобрено: разрешить все правки', + 'tool.requestFailed': 'Запрос не удался', + 'tool.askUserQuestion.fallback': 'Данные AskUserQuestion не в ожидаемом формате. Введите ответ:', + 'tool.askUserQuestion.placeholder': 'Введите ответ…', + 'tool.askUserQuestion.otherPlaceholder': 'Или введите свой ответ…', + 'tool.requestUserInput.textPlaceholder': 'Введите ответ…', + 'tool.requestUserInput.noteLabel': 'Дополнительное примечание (необязательно)', + 'tool.requestUserInput.notePlaceholder': 'Добавить примечание…', + 'tool.requestUserInput.otherLabel': 'Ничего из вышеперечисленного', + 'tool.requestUserInput.otherDescription': 'При желании добавьте детали в примечаниях.', + 'tool.requestUserInput.popupBlocked': 'Не удалось открыть страницу входа. Разрешите всплывающие окна и попробуйте ещё раз.', + 'toolGroup.title': 'Активность инструментов', + 'toolGroup.friendly.inspectTarget': 'Проверить {target}', + 'toolGroup.friendly.searchTarget': 'Найти «{target}»', + 'toolGroup.friendly.runTarget': 'Выполнить {target}', + 'toolGroup.friendly.editTarget': 'Изменить {target}', + 'toolGroup.primary.fileTargets': '{target} +{n}', + 'toolGroup.primary.commandTargets': '{target} +{n}', + 'toolGroup.primary.searchTargets': '{target} +{n}', + 'toolGroup.primary.urlTargets': '{target} +{n}', + 'toolGroup.primary.otherTargets': '{target} +{n}', + 'toolGroup.summary.read': 'Чтение {n}', + 'toolGroup.summary.mutation': 'Правка {n}', + 'toolGroup.summary.command': 'Выполнение {n}', + 'toolGroup.summary.search': 'Поиск {n}', + 'toolGroup.summary.web': 'Веб {n}', + 'toolGroup.summary.other': 'Инструмент {n}', + 'toolGroup.friendly.inspectFiles': 'Проверить файлы проекта', + 'toolGroup.friendly.searchContent': 'Найти в содержимом проекта', + 'toolGroup.friendly.runCommands': 'Выполнить команды проекта', + 'toolGroup.friendly.editFiles': 'Изменить файлы проекта', + 'toolGroup.friendly.openWeb': 'Просмотреть веб-содержимое', + 'toolGroup.friendly.genericCommand': 'Выполнить команду', + 'toolGroup.friendly.genericTool': 'Использовать инструмент', + 'toolGroup.badge.running': '{n} выполняется', + 'toolGroup.badge.pending': '{n} в ожидании', + 'toolGroup.badge.error': '{n} ошибка', + 'toolGroup.badge.fileTargets': '{n} файлов', + 'toolGroup.toolCount': '{n} действий', + 'toolGroup.loadingOlderHistory': 'Загрузка более ранней активности инструментов…', + 'toolGroup.historyUnavailable': 'Более ранняя активность инструментов недоступна.', + 'toolGroup.rowStatus.running': 'Выполняется', + 'toolGroup.rowStatus.pending': 'Ожидание', + 'toolGroup.rowStatus.error': 'Ошибка', + 'toolGroup.codex.exploring': 'Изучение', + 'toolGroup.codex.explored': 'Изучено', + 'toolGroup.codex.read': 'Чтение', + 'toolGroup.codex.list': 'Список', + 'toolGroup.codex.search': 'Поиск', + 'toolGroup.codex.searchIn': '{query} в {path}', + + // Кнопки редактора + 'composer.settings': 'Настройки', + 'composer.terminal': 'Терминал', + 'composer.abort': 'Прервать', + 'composer.switchRemote': 'Переключиться в удалённый режим', + 'composer.attach': 'Прикрепить файл', + 'composer.expand': 'Развернуть редактор сообщений', + 'composer.collapse': 'Свернуть редактор сообщений', + 'composer.dropToAttach': 'Перетащите, чтобы прикрепить', + 'composer.send': 'Отправить', + 'composer.stop': 'Остановить', + 'composer.voice': 'Голосовой ассистент', + 'composer.dictate': 'Диктовка (Ctrl/Cmd+Shift+D)', + 'composer.scheduleSend': 'Отложенная отправка', + 'composer.scheduleRelativeTab': 'Относительно', + 'composer.scheduleSpecificTab': 'Точное время', + 'composer.scheduleSpecificHint': 'Максимум 7 дней. Требуется работающий хаб; CLI наверстает отправку при следующем подключении после этого времени.', + 'composer.scheduleErrorPast': 'Время отправки должно быть в будущем.', + 'composer.scheduleErrorTooFar': 'Максимальное время отправки — 7 дней.', + 'queuedMessages.scheduledFor': 'Запланировано на {time}', + 'queuedMessages.editAlreadyInvoked': 'Сообщение уже отправлено — его нельзя отредактировать', + 'queuedMessages.editBusyNotRestored': 'Доставка всё ещё не завершена — черновик не восстановлен (может ещё быть в пути)', + 'queuedMessages.editCurrentDraftKept': 'Отложенное сообщение отменено — текущий черновик и расписание сохранены.', + 'queuedMessages.steer': 'Доставить в текущий ход сейчас', + 'queuedMessages.steerFailed': 'Не удалось направить — сообщение остаётся в очереди', + 'queuedMessages.steerOutcomeUnknown': 'Исход доставки неизвестен — повторите или явно отмените', + 'queuedMessages.retryOutcome': 'Повторить неопределённую доставку', + 'queuedMessages.retryFailed': 'Повтор не удался', + 'queuedMessages.retryMissing': 'Сообщение больше недоступно', + 'queuedMessages.retryUnavailable': 'Агент всё ещё обрабатывает эту доставку', + 'queuedMessages.steeredBadge': '↳ Направлено', + 'queuedMessages.steeredBadgeTitle': 'Направлено в активный ход', + + // Блокнот (рабочее пространство сессии) + 'scratchlist.title': 'Блокнот', + 'scratchlist.heldLabel': 'отложено — не отправлено', + 'scratchlist.empty': 'пусто', + 'scratchlist.count.one': '1 элемент', + 'scratchlist.count.other': 'Элементов: {n}', + 'scratchlist.attachmentOnly': '(вложение)', + 'scratchlist.emptyHint': 'Откладывайте сюда заметки, черновики и идеи. Ничего не отправляется, пока вы не продвинете запись.', + 'scratchlist.drawerHint': 'Печатайте ниже — кнопка «Отправить» добавляет следующее сообщение в блокнот, а не в чат. Нажмите иконку заметки ещё раз, чтобы выйти.', + 'scratchlist.toggleAriaLabel': 'Панель блокнота', + 'scratchlist.toggleTooltip': 'Блокнот — откладывать заметки и черновики (Ctrl/Cmd+Shift+S)', + 'scratchlist.sendToScratchlist': 'Отправить в блокнот', + 'scratchlist.fueTitle': 'Новое: блокнот', + 'scratchlist.fueBody': 'Откладывайте сюда заметки и черновики без отправки. Пока вы копите записи, кнопка «Отправить» светится янтарным; нажмите иконку (или Ctrl/Cmd+Shift+S) ещё раз, чтобы выйти.', + 'richComposer.fueTitle': 'Новое: @упоминание другой сессии', + 'richComposer.fueBody': 'Введите @, чтобы упомянуть другую сессию. Она станет чипом (наведите для деталей в стиле боковой панели). При отправке сообщение включает полный ID этой сессии, чтобы агент мог вызвать inspect_peer или ping_peer.', + 'scratchlist.addPlaceholder': 'Заметка, черновик или идея — Enter для добавления', + 'scratchlist.addAriaLabel': 'Добавить запись в блокнот', + 'scratchlist.add': 'Добавить', + 'scratchlist.atCap': 'Блокнот достиг лимита в {n} записей. Удалите старую запись, чтобы добавить новую.', + 'scratchlist.confirmDelete': 'Удалить эту запись блокнота? Это действие необратимо.', + 'scratchlist.listAriaLabel': 'Записи блокнота', + 'scratchlist.action.moveUp': 'Переместить запись вверх', + 'scratchlist.action.moveDown': 'Переместить запись вниз', + 'scratchlist.action.promoteToComposer': 'Скопировать в редактор', + 'scratchlist.action.promoteToQueue': 'Отправить в очередь', + 'scratchlist.action.copy': 'Скопировать текст в буфер обмена (не изображения)', + 'scratchlist.action.copied': 'Скопировано!', + 'scratchlist.action.delete': 'Удалить запись', + 'scratchlist.entry.lastSaved': 'Сохранено {time}', + 'scratchlist.entry.lastSavedAriaLabel': 'Запись сохранена {time}', + 'scratchlist.migrationBanner.title': 'Блокнот теперь синхронизируется между устройствами', + 'scratchlist.migrationBanner.body': 'Ваши существующие заметки скопированы в хаб — ничего не потеряно. Теперь изменения в этой сессии будут появляться на каждом используемом вами устройстве.', + 'scratchlist.migrationBanner.dismiss': 'Понятно', + 'fue.newFeatureDot': 'Доступна новая функция', + 'fue.gotIt': 'Понятно', + 'fue.closeAriaLabel': 'Закрыть пояснение', + 'composer.codexSlashUnsupported.title': 'Команда Codex недоступна', + 'composer.codexSlashUnsupported.body': 'Удалённый режим HAPI пока не выполняет встроенные слэш-команды Codex, такие как {command}. Используйте обычный язык или выполните её в локальном TUI Codex.', + + // Голосовой ассистент + 'voice.connecting': 'Подключение...', + 'voice.active': 'Активен', + 'voice.muted': 'Выключен звук', + 'voice.error': 'Ошибка', + 'voice.mute': 'Выключить звук', + 'voice.unmute': 'Включить звук', + 'voice.end': 'Завершить', + 'voice.error.micPermission': 'Доступ к микрофону запрещён', + 'voice.error.network': 'Ошибка сети', + 'voice.error.notInitialized': 'Голосовая сессия не инициализирована', + 'voice.error.startFailed': 'Не удалось запустить голосовую сессию', + 'voice.error.notAllowed': 'Голос недоступен', + 'voice.error.connection': 'Ошибка подключения', + 'voice.dismiss': 'Закрыть', + + // Баннеры + 'offline.title': 'Офлайн', + 'offline.message': 'Вы сейчас офлайн. Некоторые функции могут быть ограничены.', + 'syncing.title': 'Синхронизация…', + 'syncing.message': 'Ваши данные синхронизируются.', + 'reconnecting.message': 'Переподключение...', + 'reconnecting.reason.error': 'ошибка потока', + 'reconnecting.reason.closed': 'поток закрыт', + 'reconnecting.reason.heartbeatTimeout': 'таймаут heartbeat', + 'reconnecting.reason.visibilityRecovery': 'возобновление после фона', + 'reconnecting.reason.connectTimeout': 'таймаут подключения', + 'reconnecting.reason.transportError': 'ошибка потока', + 'pwa.update.title': 'Доступна новая версия', + 'pwa.update.body': 'Перезагрузите, чтобы получить последнюю версию HAPI', + 'pwa.update.reload': 'Перезагрузить', + 'pwa.update.whyToggle': 'Почему нельзя закрыть?', + 'pwa.update.whyBody': 'HAPI не будет перезагружать вкладку автоматически, пока у вас может работать агент, ожидаться разрешение или отправляться сообщение. Запуск старой веб-сборки с текущим сервером может вызвать ошибки синхронизации и неудачные действия. Этот баннер остаётся видимым до перезагрузки, чтобы вы случайно не застряли на устаревшей версии — но вы сами решаете, когда нажать «Перезагрузить», закончив текущие дела.', + + // Отправка заблокирована + 'send.blocked.title': 'Не удаётся отправить сообщение', + 'send.blocked.noConnection': 'Нет соединения с сервером', + 'resume.failed.title': 'Не удалось возобновить', + 'toast.ready.title': 'Готово к вводу', + 'toast.ready.body': '{agent} ожидает в {session}', + 'toast.permission.title': 'Запрос разрешения', + 'toast.input.title': '{agent} нужен ваш ввод', + 'toast.task.completed': 'Задача завершена', + 'toast.task.failed': 'Задача не удалась', + + // Предложение установки + 'install.title': 'Установить HAPI', + 'install.description': 'Добавьте HAPI на главный экран для быстрого доступа.', + 'install.button': 'Установить', + + // Переключатель языка + 'language.title': 'Язык', + 'language.english': 'English', + 'language.chinese': '简体中文', + + // Страница настроек + 'common.back': 'Назад', + 'settings.title': 'Настройки', + 'settings.hub.description': 'Выберите категорию, чтобы настроить HAPI под свой рабочий процесс.', + 'settings.hub.voice.summary': 'Голос, язык и поведение', + 'settings.general.title': 'Общие', + 'settings.storage.title': 'Хранилище', + 'settings.storage.summary': 'Использование базы данных хаба', + 'settings.storage.description': 'Текущий размер базы данных SQLite хаба на диске.', + 'settings.storage.loading': 'Загрузка использования хранилища…', + 'settings.storage.error': 'Не удалось загрузить использование хранилища', + 'settings.storage.total': 'Всего', + 'settings.storage.database': 'База данных', + 'settings.storage.wal': 'Журнал предзаписи', + 'settings.storage.shm': 'Разделяемая память', + 'settings.storage.path': 'Путь', + 'settings.storage.refresh': 'Обновить', + 'settings.storage.refreshing': 'Обновление…', + 'settings.storage.chartTitle': 'Относительная доля', + 'settings.storage.chartEmpty': 'Пока нет данных о размере на диске.', + 'settings.usage.title': 'Расход токенов', + 'settings.usage.summary': 'Панель расхода только по токенам', + 'settings.usage.description': 'Токены, обработанные при управлении агентами через HAPI. Ранее импортированные расшифровки не учитываются; стоимость не входит.', + 'settings.usage.range.label': 'Период', + 'settings.usage.range.7d': '7 дней', + 'settings.usage.range.30d': '30 дней', + 'settings.usage.range.all': 'Всё время', + 'settings.usage.loading': 'Загрузка расхода токенов…', + 'settings.usage.error': 'Не удалось загрузить расход токенов', + 'settings.usage.empty': 'За этот период расход токенов не зафиксирован.', + 'settings.usage.total': 'Обработано токенов (с учётом кэша)', + 'settings.usage.uncached': 'Токены без кэша', + 'settings.usage.input': 'Входные токены (включая кэш)', + 'settings.usage.output': 'Выходные токены', + 'settings.usage.cacheRead': 'Чтение кэша (включено во входные)', + 'settings.usage.cacheCreation': 'Создание кэша (включено)', + 'settings.usage.cacheHitRate': 'Доля попаданий в кэш', + 'settings.usage.requests': 'Запросы', + 'settings.usage.daily.title': 'Динамика по дням', + 'settings.usage.agent.title': 'По агентам', + 'settings.usage.model.title': 'По моделям', + 'settings.usage.bucketDetails': '{requests} запросов · {input} вход · {output} выход', + 'settings.usage.sessions': 'Сессий с расходом: {count}', + 'settings.general.description': 'Язык, сопряжение с приложением-компаньоном и общие предпочтения приложения.', + 'settings.general.sessionSummary.title': 'Сводки статуса сессий', + 'settings.general.sessionSummary.description': 'Выберите, будут ли поддерживаемые агенты формировать сводки статуса и отображаться ли они в чате.', + 'settings.general.sessionSummaryContract': 'Формировать сводки статуса', + 'settings.general.sessionSummaryContract.desc': 'По умолчанию выключено. При включении поддерживаемых агентов просят добавлять после каждого хода завершающую строку AGENT_NOTIFY_SUMMARY для уведомлений и записей о фоновой работе. Применяется к новым/возобновлённым сессиям. (Поддерживаются: Claude, Codex, OpenCode, удалённый Grok; пока не поддерживаются: локальный Grok, Cursor)', + 'settings.general.sessionSummaryInChat': 'Показывать сводки статуса в чате', + 'settings.general.sessionSummaryInChat.desc': 'Влияет только на отображение в чате и скопированном содержимом; не влияет на формирование сводок, уведомления или записи о фоновой работе. При включении показывается строка статуса, при выключении она скрыта. Сохранённые сообщения не изменяются.', + 'settings.language.title': 'Язык', + 'settings.language.label': 'Язык', + 'settings.display.title': 'Отображение', + 'settings.display.description': 'Внешний вид, типографика и настройки списка сессий.', + 'settings.display.typography': 'Типографика', + 'settings.display.sessions': 'Список сессий', + 'settings.display.appearance': 'Оформление', + 'settings.display.appearanceMode': 'Режим оформления', + 'settings.display.appearance.system': 'Как в системе', + 'settings.display.appearance.dark': 'Тёмная', + 'settings.display.appearance.oled': 'OLED-чёрный', + 'settings.display.appearance.light': 'Светлая', + 'settings.display.colorTheme': 'Цветовая тема', + 'settings.display.colorTheme.default': 'По умолчанию', + 'settings.display.colorTheme.notion': 'Notion', + 'settings.display.colorTheme.one': 'One', + 'settings.display.colorTheme.proof': 'Proof', + 'settings.display.colorTheme.raycast': 'Raycast', + 'settings.display.colorTheme.rosePine': 'Rose Pine', + 'settings.display.colorTheme.solarized': 'Solarized', + 'settings.display.colorTheme.vercel': 'Vercel', + 'settings.display.colorTheme.vsCodePlus': 'VS Code Plus', + 'settings.display.colorTheme.xcode': 'Xcode', + 'settings.display.colorTheme.linear': 'Linear', + 'settings.display.colorTheme.lobster': 'Lobster', + 'settings.display.colorTheme.material': 'Material', + 'settings.display.colorTheme.matrix': 'Matrix', + 'settings.display.colorTheme.monokai': 'Monokai', + 'settings.display.colorTheme.nightOwl': 'Night Owl', + 'settings.display.colorTheme.nord': 'Nord', + 'settings.display.themeColors.title': 'Свои цвета', + 'settings.display.themeColors.description': 'Применяется к текущему оформлению. Переключите оформление, чтобы настроить каждое отдельно.', + 'settings.display.themeColors.reset': 'Сбросить', + 'settings.display.themeColors.resetAll': 'Сбросить все', + 'settings.display.themeColors.expand': 'Настроить', + 'settings.display.themeColors.key.background': 'Фон', + 'settings.display.themeColors.key.surface': 'Карточки и поверхности', + 'settings.display.themeColors.key.text': 'Текст', + 'settings.display.themeColors.key.hint': 'Приглушённый текст', + 'settings.display.themeColors.key.accent': 'Акцент и ссылки', + 'settings.display.themeColors.key.border': 'Границы', + 'settings.display.themeColors.key.userBubble': 'Пузырь вашего сообщения', + 'settings.display.fontSize': 'Размер шрифта', + 'settings.display.terminalFontSize': 'Размер шрифта терминала', + 'settings.display.sessionPreviewLimit': 'Сессий до сворачивания', + 'settings.display.sessionPreviewLimit.decrease': 'Показывать меньше сессий до сворачивания', + 'settings.display.sessionPreviewLimit.increase': 'Показывать больше сессий до сворачивания', + 'settings.display.activeSessionsOnly': 'Только активные сессии', + 'settings.display.activeSessionsOnly.desc': 'Скрыть неактивные сессии в боковой панели. Открытая сессия остаётся видимой.', + 'settings.display.pinInProgressSessions': 'Закреплять сессии в работе', + 'settings.display.pinInProgressSessions.desc': 'Перемещать незакреплённые подключённые сессии в разделы над папками проекта: сначала выполняющиеся и ожидающие, затем спокойные активные сессии (выполнение завершено, подключение есть). Глобальные закрепления остаются выше них. Выключено — всё остаётся в группах по каталогам.', + 'settings.display.appBadge': 'Значок непрочитанного на панели задач', + 'settings.display.appBadge.desc': 'Показывать число сессий с новой активностью в установленной PWA Edge или Chrome. Внешний вид определяет браузер хоста; в обычной вкладке браузера это не действует.', + 'settings.display.sessionListStatus': 'Подсказки статуса в списке сессий', + 'settings.display.sessionListStatus.standard': 'Базовые', + 'settings.display.sessionListStatus.detailed': 'Расширенные', + 'settings.display.sessionListStatus.detailedDescription': 'Выберите, какие подсказки статуса показывать в списке сессий. Базовые показывают состояние выполнения; расширенные также показывают подсказки о разрешениях, вводе, фоновых задачах, новой активности и отложенных сообщениях (иконка часов).', + 'settings.display.sessionHeader': 'Шапка сессии', + 'settings.display.sessionHeader.description': 'Выберите, какие детали показывать под названием сессии. На мобильных показывается агент плюс самая приоритетная доступная деталь.', + 'settings.display.sessionHeader.showLabels': 'Показывать подписи полей', + 'settings.display.sessionHeader.agent': 'Агент', + 'settings.display.sessionHeader.model': 'Модель', + 'settings.display.sessionHeader.reasoning': 'Уровень рассуждений', + 'settings.display.sessionHeader.fastMode': 'Быстрый режим', + 'settings.display.sessionHeader.machine': 'Машина', + 'settings.display.sessionHeader.lastActive': 'Время активности', + 'settings.display.sessionHeader.createdAt': 'Время создания', + 'settings.display.sessionHeader.updatedAt': 'Время обновления', + 'settings.display.sessionHeader.worktree': 'Ветка рабочего дерева', + 'settings.display.links': 'Ссылки', + 'settings.display.openExternalLinksInNewTab': 'Открывать внешние ссылки в новой вкладке', + 'settings.display.openExternalLinksInNewTab.desc': 'Выключено (по умолчанию) сохраняет текущее поведение. Включено — открывает внешние ссылки в отдельной вкладке браузера.', + 'session.header.createdAt': 'Создана', + 'session.header.updatedAt': 'Обновлена', + 'settings.chat.title': 'Чат', + 'settings.chat.description': 'Ввод сообщений, карточки инструментов и цвета диалога.', + 'settings.chat.input': 'Ввод', + 'settings.chat.tools': 'Карточки инструментов', + 'settings.chat.colors': 'Цвета диалога', + 'settings.chat.enterBehavior': 'Клавиша Enter', + 'settings.chat.enterBehavior.send': 'Отправить сообщение', + 'settings.chat.enterBehavior.newline': 'Вставить перенос строки', + 'settings.chat.terminalToolDisplay': 'Карточки инструментов терминала', + 'settings.chat.terminalToolDisplay.compact': 'Компактные (только команда)', + 'settings.chat.terminalToolDisplay.detailed': 'Подробные (показывать предпросмотр вывода)', + 'settings.chat.codexExplorationCollapsed': 'Сворачивать изученные группы инструментов по умолчанию', + 'settings.chat.codexExplorationCollapsed.desc': 'Держать активность чтения и поиска Codex свёрнутой, пока вы её не откроете.', + 'settings.chat.reasoningCollapsed': 'Сворачивать рассуждения по умолчанию', + 'settings.chat.reasoningCollapsed.desc': 'Держать сообщения с рассуждениями ИИ свёрнутыми, в том числе во время потокового вывода.', + 'settings.chat.groupedToolBackground': 'Фон сгруппированного использования инструментов', + 'settings.chat.userMessageBackground': 'Фон сообщения пользователя', + 'settings.chat.surfaceColor.default': 'Цвет по умолчанию', + 'settings.chat.surfaceColor.softBlue': 'Мягкий синий', + 'settings.chat.surfaceColor.softGreen': 'Мягкий зелёный', + 'settings.chat.surfaceColor.softYellow': 'Мягкий жёлтый', + 'settings.chat.surfaceColor.custom': 'Свой цвет', + 'settings.chat.composerToolbar.title': 'Настройка панели инструментов редактора', + 'settings.chat.composerToolbar.description': 'Выберите, как расположить действия панели под полем ввода сообщения.', + 'settings.chat.composerToolbar.layout': 'Выравнивание', + 'settings.chat.composerToolbar.order': 'Порядок инструментов', + 'settings.chat.composerToolbar.hidden': 'Скрытые инструменты', + 'settings.chat.composerToolbar.emptyHidden': 'Перетащите сюда инструменты, чтобы скрыть их', + 'settings.chat.composerToolbar.hide': 'Скрыть', + 'settings.chat.composerToolbar.show': 'Показать', + 'settings.chat.composerToolbar.layout.left': 'Слева', + 'settings.chat.composerToolbar.layout.center': 'По центру', + 'settings.chat.composerToolbar.layout.right': 'Справа', + 'settings.chat.composerToolbar.layout.split': 'Раздельно', + 'settings.chat.composerToolbar.dragHint': 'Перетаскивайте действия, чтобы изменить порядок. В раздельной раскладке перетаскивайте между двумя группами.', + 'settings.chat.composerToolbar.previewHint': 'Перетаскивайте реальные иконки панели ниже, чтобы изменить порядок, или перемещайте их в «Скрытые инструменты». Изменения применяются сразу; наведите на иконку, чтобы увидеть её действие.', + 'settings.chat.composerToolbar.reset': 'Сбросить', + 'settings.chat.composerToolbar.leftGroup': 'Левая группа', + 'settings.chat.composerToolbar.rightGroup': 'Правая группа', + 'settings.chat.composerToolbar.emptyGroup': 'Перетащите действия сюда', + 'settings.chat.composerToolbar.moveLeft': 'Переместить в левую группу', + 'settings.chat.composerToolbar.moveRight': 'Переместить в правую группу', + 'settings.chat.composerToolbar.moveEarlier': 'Переместить раньше', + 'settings.chat.composerToolbar.moveLater': 'Переместить позже', + 'settings.chat.composerToolbar.item.attachment': 'Добавить вложение', + 'settings.chat.composerToolbar.item.settings': 'Настройки сессии', + 'settings.chat.composerToolbar.item.expand': 'Развернуть редактор сообщений', + 'settings.chat.composerToolbar.item.model': 'Модель', + 'settings.chat.composerToolbar.item.effort': 'Усилия', + 'settings.chat.composerToolbar.item.terminal': 'Терминал', + 'settings.chat.composerToolbar.item.abort': 'Прервать', + 'settings.chat.composerToolbar.item.switch': 'Переключиться на удалённый', + 'settings.chat.composerToolbar.item.voiceMic': 'Микрофон голоса', + 'settings.chat.composerToolbar.item.scratchlist': 'Блокнот', + 'settings.chat.composerToolbar.item.schedule': 'Отложенная отправка', + 'settings.voice.title': 'Голос', + 'settings.voice.description': 'Выберите диктовку или полный голосовой ассистент.', + 'settings.voice.inputMode.title': 'Режим голоса', + 'settings.voice.inputMode.hint': 'Диктовка только вставляет текст в редактор; она никогда не отправляет автоматически.', + 'settings.voice.inputMode.assistant': 'Голосовой ассистент', + 'settings.voice.inputMode.assistant.hint': 'Двусторонний голосовой разговор', + 'settings.voice.inputMode.dictation': 'Диктовка', + 'settings.voice.inputMode.dictation.hint': 'Только ввод речи в текст', + 'settings.voice.transcriptionProvider': 'Провайдер транскрипции', + 'settings.voice.noTranscriptionProvider': 'На хабе пока нет провайдера транскрипции — добавьте OpenAI, ElevenLabs или Groq ниже (или используйте встроенный в браузер, если доступен).', + 'settings.voice.noVoiceBackend': 'На хабе не настроен бэкенд голосового ассистента — добавьте его ниже.', + 'settings.voice.credentials.hint': 'Выберите OpenAI, ElevenLabs или Groq. Ключи хранятся на хабе; браузер никогда не хранит долгоживущие секреты провайдера.', + 'settings.voice.credentials.assistantHint': 'Добавьте ключ ElevenLabs, Gemini Live или Qwen Realtime. Ключи хранятся на хабе.', + 'settings.voice.credentials.provider': 'Провайдер', + 'settings.voice.credentials.openaiCompatible': 'OpenAI-совместимый / локальный', + 'settings.voice.credentials.geminiLive': 'Gemini Live', + 'settings.voice.credentials.qwenRealtime': 'Qwen Realtime', + 'settings.voice.credentials.apiKey': 'API-ключ', + 'settings.voice.credentials.apiKeyPlaceholder': 'Вставьте API-ключ', + 'settings.voice.credentials.apiKeyReplace': 'Вставьте новый ключ для замены', + 'settings.voice.credentials.baseUrl': 'Базовый URL', + 'settings.voice.credentials.model': 'Модель', + 'settings.voice.credentials.save': 'Сохранить на хабе', + 'settings.voice.credentials.clear': 'Очистить', + 'settings.voice.credentials.saved': 'Сохранено. Список провайдеров обновлён.', + 'settings.voice.credentials.cleared': 'Удалено из настроек хаба.', + 'settings.voice.credentials.saveFailed': 'Не удалось сохранить учётные данные.', + 'settings.voice.credentials.configuredAs': 'Настроено через {source}: {hint}', + 'settings.voice.credentials.source.env': 'окружение', + 'settings.voice.credentials.source.settings': 'Настройки', + 'settings.voice.credentials.envLocked': 'Этот ключ задан окружением хаба и не может быть изменён здесь.', + 'settings.voice.credentials.manage': 'Добавить или управлять провайдерами', + 'settings.voice.credentials.manageHint': 'Добавьте OpenAI, ElevenLabs или Groq, чтобы включить диктовку на хабе.', + 'settings.voice.credentials.manageAssistantHint': 'Вставьте API-ключ, чтобы включить ElevenLabs, Gemini Live или Qwen Realtime на хабе.', + 'settings.voice.transcriptionMode': 'Режим транскрипции', + 'settings.voice.transcriptionMode.standard': 'Стандартный', + 'settings.voice.transcriptionMode.standard.hint': 'Записать, затем транскрибировать (по умолчанию)', + 'settings.voice.transcriptionMode.realtime': 'Реального времени', + 'settings.voice.transcriptionMode.realtime.hint': 'Показывать живой текст во время речи; вставить итог после остановки', + 'settings.voice.voices.description': 'Выберите голос, используемый выбранным бэкендом.', + 'settings.voice.sounds.title': 'Как это звучит', + 'settings.voice.responds.title': 'Как отвечает', + 'settings.voice.connection.title': 'Подключение и провайдер', + 'settings.voice.behaves.title': 'Как себя ведёт', + 'settings.voice.persona.title': 'Персона и инструкции', + 'settings.voice.advanced.section.title': 'Дополнительно', + 'settings.voice.responseLength.label': 'Длина ответа', + 'settings.voice.responseLength.brief': 'Краткий', + 'settings.voice.responseLength.balanced': 'Сбалансированный', + 'settings.voice.responseLength.detailed': 'Подробный', + 'settings.voice.responseLength.brief.hint': 'Отвечать в 1–2 предложениях.', + 'settings.voice.responseLength.balanced.hint': 'По умолчанию — ассистент сам определяет длину по контексту.', + 'settings.voice.responseLength.detailed.hint': 'Давать развёрнутые ответы, когда полезна глубина.', + 'settings.voice.opening.label': 'Начало', + 'settings.voice.opening.greet': 'Поздороваться', + 'settings.voice.opening.brief': 'Ввести в курс', + 'settings.voice.opening.greet.hint': 'Ассистент здоровается и ждёт, пока вы заговорите.', + 'settings.voice.opening.brief.hint': 'Ассистент кратко описывает активность агента при подключении.', + 'settings.voice.group.label': 'Настройки голоса', + 'settings.voice.group.hint': 'Настройки применяются к выбранному голосовому провайдеру или провайдеру транскрипции.', + 'settings.voice.backend': 'Бэкенд голоса', + 'settings.voice.language': 'Язык голоса', + 'settings.voice.autoDetect': 'Автоопределение', + 'settings.voice.voice': 'Голос', + 'settings.voice.voiceDefault': 'По умолчанию', + 'settings.voice.advanced.title': 'Расширенные настройки голоса', + 'settings.voice.advanced.hint': 'Идентичность, характер, фикстуры, ползунки. Значения по умолчанию подходят — открывайте только если хотите перенастроить.', + 'settings.voice.advanced.customizedBadge': 'изменено', + 'settings.voice.fixtures.title': 'Правила платформы (только чтение)', + 'settings.voice.fixtures.hint': 'Поставляются с приложением: инструменты, маршрутизация, правила TTS. Обновляются при обновлении HAPI — здесь не редактируются.', + 'settings.voice.identity.title': 'Идентичность и бренд', + 'settings.voice.identity.hint': 'Кто такой голосовой ассистент. HAPI — это приложение; здесь можно переименовать или ребрендировать персону (например, «надзиратель»). Ограничения провайдера всегда применяются отдельно.', + 'settings.voice.identity.reset': 'Сбросить идентичность', + 'settings.voice.identity.default': 'Встроенная идентичность по умолчанию', + 'settings.voice.identity.customized': 'Своя идентичность', + 'settings.voice.character.promptTitle': 'Характер и стиль речи', + 'settings.voice.character.promptHint': 'Тон и стиль. Текст предустановленной подачи объединяется сюда, когда характер пуст. Компонуется с правилами платформы во время выполнения на всех голосовых бэкендах.', + 'settings.voice.character.reset': 'Сбросить характер', + 'settings.voice.character.appendPreset': 'Добавить предустановленный текст подачи', + 'settings.voice.layers.resetAll': 'Сбросить идентичность и характер', + 'settings.voice.layers.composedNote': 'Промпт во время выполнения = правила платформы + ваша идентичность + характер (все бэкенды).', + 'settings.voice.wireBudget.elevenlabs': 'ElevenLabs отправляет собранные инструкции при подключении; история сессии инициализируется, затем передаётся потоком.', + 'settings.voice.wireBudget.gemini': 'Gemini Live использует те же собранные инструкции через прокси хаба.', + 'settings.voice.wireBudget.qwen': 'Qwen Realtime использует те же собранные инструкции в session.update.', + 'settings.voice.wireBudget.storage': 'Лимит локального хранилища (символов):', + 'settings.voice.wireBudget.elevenlabsLimits': 'Ограничения канала: ~{msg} Б на сообщение WebRTC; бюджет собранного промпта ~{prompt} Б.', + 'settings.voice.wireBudget.promptTruncated': 'Ваш собранный промпт был сокращён, чтобы уложиться в лимит канала ElevenLabs. Сократите идентичность/характер, иначе мы ещё обрежем его при подключении.', + 'settings.voice.wireBudget.composedSize': 'Размер последнего собранного промпта', + 'settings.voice.contextNotice': 'Последняя голосовая сессия', + 'settings.voice.character.title': 'Предустановка стиля речи', + 'settings.voice.character.presetSlidersHint': 'Предустановки настраивают ползунки TTS ElevenLabs и необязательную формулировку подачи (слой характера).', + 'settings.voice.character.preset.label': 'Предустановка', + 'settings.voice.character.preset.balanced': 'Сбалансированная', + 'settings.voice.character.preset.balancedHint': 'Тёплая и сосредоточенная — подходит для повседневных задач.', + 'settings.voice.character.preset.warm': 'Тёплая и выразительная', + 'settings.voice.character.preset.warmHint': 'Более живая подача; аудио-теги ElevenLabs, когда доступны.', + 'settings.voice.character.preset.calm': 'Спокойная', + 'settings.voice.character.preset.calmHint': 'Медленный, размеренный тон для долгих или поздних сессий.', + 'settings.voice.character.preset.direct': 'Прямая', + 'settings.voice.character.preset.directHint': 'Кратко и эффективно — минимум лишнего.', + 'settings.voice.character.preset.custom': 'Своя', + 'settings.voice.character.preset.customHint': 'Вы управляете ползунками и системным промптом выше.', + 'settings.voice.tuning.title': 'Акустическая настройка', + 'settings.voice.tuning.elevenlabs': 'ElevenLabs', + 'settings.voice.tuning.gemini': 'Gemini Live', + 'settings.voice.tuning.stability': 'Стабильность', + 'settings.voice.tuning.stabilityHint': 'Ниже = динамичнее; выше = ровнее.', + 'settings.voice.tuning.expressiveness': 'Выразительность', + 'settings.voice.tuning.expressivenessHint': 'Преувеличение стиля (стиль ElevenLabs).', + 'settings.voice.tuning.speakingRate': 'Скорость речи', + 'settings.voice.tuning.speakingRateHint': '0,7–1,2× (API ElevenLabs).', + 'settings.voice.tuning.similarity': 'Усиление схожести', + 'settings.voice.tuning.similarityHint': 'Более точное совпадение с обученным голосом.', + 'settings.voice.tuning.speakerBoost': 'Усиление голоса', + 'settings.voice.tuning.affectiveDialog': 'Аффективный диалог', + 'settings.voice.tuning.affectiveDialogHint': 'Подстраивать подачу под ваш тон (Gemini v1alpha).', + 'settings.voice.tuning.qwenHint': 'У Qwen здесь нет ползунков TTS — отредактируйте голосовой системный промпт выше; эмоции подстраиваются под вашу речь.', + 'settings.voice.tuning.selectBackend': 'Ползунки для каждого бэкенда появляются при выборе голосового бэкенда.', + 'settings.voice.preview.elevenlabsOnly': 'Предпросмотр голоса доступен только для ElevenLabs', + 'settings.voice.preview.unavailable': 'Предпросмотр недоступен без API-ключа ElevenLabs', + 'settings.voice.preview.play': 'Прослушать голос', + 'settings.voice.preview.stop': 'Остановить предпросмотр', + 'settings.voice.staticCatalogHint': 'Откройте список, чтобы увидеть заметки о характере голоса. Аудиопредпросмотр — только ElevenLabs.', + 'settings.voice.session.label': 'Поведение сессии', + 'settings.voice.proactive': 'Начинать голосовую сессию со сводкой', + 'settings.voice.proactive.description': 'При включении голосовая сессия начинается с озвученной сводки текущей активности агента. При выключении ассистент здоровается и ждёт, пока вы заговорите.', + 'settings.companion.title': 'Компаньон', + 'settings.companion.noToken': 'Для сопряжения нужен исходный токен доступа (CLI_API_TOKEN). Похоже, вы вошли через Telegram или другим способом, который не сохранил его — вставьте токен вручную в приложении-компаньоне.', + 'settings.companion.description': 'Отсканируйте из приложения-компаньона HAPI на Android (телефон или Wear OS), чтобы привязать его к этому хабу. Код сопряжения — это ваш токен доступа; относитесь к нему как к паролю.', + 'settings.companion.showQr': 'Показать QR сопряжения', + 'settings.companion.qrAriaLabel': 'QR-код сопряжения компаньона', + 'settings.companion.copyLink': 'Копировать ссылку', + 'settings.companion.copied': 'Скопировано!', + 'settings.companion.hide': 'Скрыть', + 'settings.machines.title': 'Машины', + 'settings.machines.description': 'Дайте своим машинам собственные имена. Отображаются только машины, которые сейчас онлайн.', + 'settings.machines.section': 'Ваши машины', + 'settings.machines.rename': 'Переименовать {name}', + 'settings.machines.namePlaceholder': 'Использовать имя хоста', + 'settings.machines.empty': 'Нет машин онлайн.', + 'settings.machines.error': 'Не удалось переименовать эту машину.', + 'settings.hub.machines.summary': 'Собственные имена для ваших машин', + 'settings.about.title': 'О приложении', + 'settings.about.description': 'Ссылки и информация о версии HAPI.', + 'settings.about.website': 'Сайт', + 'settings.about.appVersion': 'Версия приложения', + 'settings.about.protocolVersion': 'Версия протокола', + + // Обзор / Рабочее пространство + 'browse.title': 'Обзор', + 'browse.goUp': 'Наверх', + 'browse.empty': 'Подкаталоги не найдены', + 'browse.refresh': 'Обновить', + 'browse.showHidden': 'Показать скрытые', + 'browse.startSession': 'Запустить сессию', + 'browse.nav': 'Обзор', + 'browse.noRootTitle': 'Обзор рабочего пространства выключен', + 'browse.noRootHint': 'Обзор включается по желанию. Перезапустите раннер с одним или несколькими корнями рабочего пространства, чтобы включить навигацию по дереву файлов и ограниченный запуск сессий.', + 'browse.noRootFooter': 'Вы по-прежнему можете создавать сессии на странице «Новая сессия».', + 'browse.noMachinesConnected': 'CLI не подключён. Выполните `hapi runner start --workspace-root /путь/а --workspace-root /путь/б` на машине, чтобы начать.', + + // Разное + 'misc.noMachines': 'Нет доступных машин', + 'misc.machine': 'Машина', + 'misc.collaborationMode': 'Режим совместной работы', + 'misc.copilotAgentMode': 'Режим агента', + 'misc.permissionMode': 'Режим разрешений', + 'misc.model': 'Модель', + 'misc.reasoningEffort': 'Уровень рассуждений', + 'misc.effort': 'Усилия', + 'misc.fastMode': 'Быстрый режим', + 'misc.fastModeStandard': 'Стандартный', + 'misc.fastModeFast': 'Быстрый', + 'misc.variant': 'Вариант', + 'misc.changeModel': 'Сменить модель…', + 'misc.backToModelList': '← Модели', + 'misc.loading': 'Загрузка…', + 'misc.newMessage': 'Новых сообщений: {n}', + 'misc.scrollToBottom': 'Прокрутить вниз', + 'misc.loadingMessages': 'Загрузка сообщений…', + 'misc.pullToLoadOlder': 'Тяните, чтобы загрузить более ранние сообщения', + 'misc.releaseToLoadOlder': 'Отпустите, чтобы загрузить более ранние сообщения', + 'misc.typeMessage': "Введите 'continue', чтобы продолжить...", + 'misc.typeAMessage': 'Введите сообщение...', + 'misc.typeAMessageWithMentions': 'Введите, что должен сделать агент, или @упомяните другую сессию для контекста или передачи', + 'misc.offline': 'офлайн', + 'misc.permissionRequired': 'требуется разрешение', + 'misc.online': 'онлайн', + 'misc.contextDetails': 'Сведения о контексте', + 'misc.contextCache': 'Кэш: {value}', + 'misc.contextUsed': 'Использовано: {value} ({percent}%)', + 'misc.contextUsedTokens': 'Использовано: {value}', + 'misc.contextRemaining': 'Осталось: {value} ({percent}%)', + + // Выбор цели Web Share + 'share.title': 'Поделиться в HAPI', + 'share.subtitle': 'Выберите сессию, к которой это прикрепить.', + 'share.recentSessions': 'Недавние активные сессии', + 'share.newSession': 'Новая сессия', + 'share.discard': 'Отменить', + 'share.loading': 'Загрузка общего содержимого…', + 'share.notFound.title': 'Общее содержимое не найдено', + 'share.notFound.body': 'Эта ссылка истекла или была открыта напрямую без передачи.', + 'share.error.ingest': 'Не удалось прочитать общее содержимое. Попробуйте ещё раз из исходного приложения.', + 'share.error.noId': 'Не передан идентификатор. Откройте эту страницу из системного меню «Поделиться».', + 'share.backToSessions': 'Назад к сессиям', + 'share.preview.text': 'Общий текст', + 'share.preview.empty': '(пустой общий элемент)', + 'share.preview.files': '{n} файлов', + 'share.noActiveSessions': 'Нет активных сессий. Выберите «Новая сессия» ниже.', + 'sessions.refresh.pull': 'Потяните для обновления', + 'sessions.refresh.release': 'Отпустите для обновления', + 'sessions.refresh.refreshing': 'Обновление…', + 'sessions.refresh.failed.title': 'Не удалось обновить', + 'codexSync.newSessionInline.title': 'Импорт истории Codex', + 'codexSync.newSessionInline.description': 'Необязательно: выберите одну локальную сессию Codex, затем выберите модель/настройки и нажмите «Создать» для импорта.', + 'codexSync.newSessionInline.clear': 'Очистить выбранную историю', + 'codexSync.newSessionInline.choose': 'Выбрать историю', + 'codexSync.confirm.search': 'Поиск', + 'codexSync.confirm.searchPlaceholder': 'Поиск по названию, сообщению, каталогу, ID сессии', + 'codexSync.confirm.useSelected': 'Использовать выбранное', + 'codexSync.confirm.imported': 'Импортировано', + 'codexSync.confirm.original': 'Исходная', + 'codexSync.confirm.fork': 'Форк', + 'codexSync.confirm.archiveAction': 'Архивировать в Codex', + 'session.action.syncCodexDisabledActive': 'Остановите или заархивируйте выполняющуюся сессию перед синхронизацией истории Codex.', + 'codexSync.manual.success.noNewMessages': 'Нет новых сообщений Codex.', + 'session.status.title': 'Статус сессии', + 'session.status.goal': 'Цель', + 'session.status.tasks': 'Задачи', + 'session.status.subagents': 'Подагенты', + 'session.status.terminals': 'Фоновые терминалы', + 'session.status.terminalsUnavailable': 'Выполняется: {count} · точная команда недоступна', + 'session.status.terminalsPossible': 'Возможные команды', + 'session.status.goal.active': 'Активна', + 'session.status.goal.paused': 'Приостановлена', + 'session.status.goal.budgetLimited': 'Ограничена', + 'session.status.goal.usageLimited': 'Ограничена по расходу', + 'session.status.goal.blocked': 'Заблокирована', + 'session.status.goal.complete': 'Завершена', + 'session.status.subagent.running': 'Выполняется', + 'session.status.subagent.waiting': 'Ожидание', + 'session.status.subagent.error': 'Ошибка', + 'share.searchResults': 'Подходящие сессии', + 'share.noSearchResults': 'Нет сессий, соответствующих поиску.', + 'share.searchForMore': 'Ещё {n} активных сессий — воспользуйтесь поиском, чтобы найти их.', + 'session.summary.label': 'Сводка сессии', + 'session.summary.ariaLabel': 'Сводка статуса сессии', + 'session.summary.status.done': 'Готово', + 'session.summary.status.blocked': 'Заблокирована', + 'session.summary.status.needsReview': 'Требует проверки', + 'session.summary.status.needsDecision': 'Требует решения', + 'session.summary.status.failed': 'Не удалась', + 'session.summary.status.stalled': 'Застопорилась', + + // Install prompt (iOS add-to-home-screen guide) + 'install.close': 'Закрыть', + 'install.ios.step1.before': 'Нажмите', + 'install.ios.step1.after': '«Поделиться» на панели', + 'install.ios.step2.before': 'Прокрутите вниз и нажмите', + 'install.ios.step2.after': 'На экран «Домой»', + 'install.ios.step3.before': 'Нажмите', + 'install.ios.step3.emphasis': 'Добавить', + 'install.ios.step3.after': 'в правом верхнем углу', + + // Queued messages bar + 'queuedMessages.title': 'Сообщения в очереди', + 'queuedMessages.status': 'В очереди', + 'queuedMessages.editLabel': 'Изменить сообщение в очереди', + 'queuedMessages.cancelLabel': 'Отменить сообщение в очереди', + 'queuedMessages.pendingInvocation.one': '{n} сообщение в очереди ожидает вызова', + 'queuedMessages.pendingInvocation.other': '{n} сообщений в очереди ожидают вызова', + + // Image viewer / zoomable lightbox + 'image.clickToZoom': 'Нажмите, чтобы увеличить', + 'image.previous': 'Предыдущее изображение', + 'image.next': 'Следующее изображение', + 'image.zoomIn': 'Увеличить', + 'image.zoomOut': 'Уменьшить', + 'image.resetZoom': 'Сбросить масштаб', + 'image.fitToScreen': 'По размеру экрана', + + // Chat chrome and status + 'chat.contextCompacted': 'Контекст сжат', + 'chat.reasoning': 'Рассуждения', + 'chat.queuedStatus': 'В очереди', + 'chat.sendingStatus': 'Отправка', + 'chat.terminalOutput': 'Вывод терминала', + 'chat.removeAttachment': 'Убрать вложение', + 'chat.uploadFailed': 'Ошибка загрузки', + + // Tool cards + 'tool.output': 'Вывод', + 'tool.prompt': 'Промпт', + 'tool.draft': 'Черновик', + 'tool.rawJson': 'Исходный JSON', + 'tool.fileContent': 'Содержимое файла', + + // Team panel + 'team.members': 'Участники', + 'team.tasks': 'Задачи', + 'team.recentMessages': 'Недавние сообщения', + + // Terminal / app shell + 'terminal.inactiveSession': 'Сессия неактивна. Терминал недоступен.', + 'app.sessionUnavailable': 'Сессия недоступна', + + // Tool result states + 'tool.state.waitingForPermission': 'Ожидание разрешения…', + 'tool.state.running': 'Выполняется…', + 'tool.state.noOutput': '(нет вывода)', + 'tool.result.done': 'Готово', + 'tool.result.agentLaunched': 'Агент запущен', + 'tool.result.timedOut': 'Тайм-аут', + 'tool.result.noStatus': 'Нет статуса', + 'tool.result.skillLoaded': 'Навык загружен', + 'tool.result.skillLoadedNamed': 'Навык «{name}» загружен', + 'tool.result.fieldName': 'Имя', + 'tool.result.fieldTask': 'Задача', + 'tool.result.fieldId': 'ID', + 'tool.result.agentCount': 'Агентов: {count}', + + // Session shell + 'session.notFound.returning': 'Сессия не найдена. Возвращаемся к списку…', +} as const diff --git a/web/src/routes/settings/general.tsx b/web/src/routes/settings/general.tsx index 17f6cbe2..da7c5f6a 100644 --- a/web/src/routes/settings/general.tsx +++ b/web/src/routes/settings/general.tsx @@ -8,6 +8,7 @@ import { queryKeys } from '@/lib/query-keys' const locales: ReadonlyArray<{ value: Locale; label: string }> = [ { value: 'en', label: 'English' }, { value: 'zh-CN', label: '简体中文' }, + { value: 'ru', label: 'Русский' }, ] function getNamespace(token: string | null): string | null { From 99cd3d4172fb49f893b62dff39239fa85c5f6275 Mon Sep 17 00:00:00 2001 From: Matvey Rudoy <75200069+mrudybtw@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:14:11 +0300 Subject: [PATCH 25/34] feat(android): add Russian locale (#1963) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(android): add Russian locale Translate all 518 app strings into values-ru/strings.xml, register ru in locales_config.xml, and add AppLanguage.RUSSIAN to the in-app language picker. * fix(android): use count-agnostic Russian forms for dynamic counts The *_many strings used a genitive-plural noun after the number, which is wrong for 2-4 (e.g. "2 инструментов"). The house style avoids , so phrase these labels with the noun first ("Инструменты: %1") instead: tool groups, review findings, queued/new messages, agent steps, questions, lines, chars, edits, usage requests, scratchlist count and attachment cap. * fix(android): make the process-steps label count-safe * fix(android): use a count-safe token label in the usage tooltip --------- Co-authored-by: mrudy --- .../feature/settings/LanguagePrefs.kt | 10 +- .../feature/settings/SettingsScreen.kt | 1 + .../app/src/main/res/values-ru/strings.xml | 573 ++++++++++++++++++ .../app/src/main/res/xml/locales_config.xml | 1 + 4 files changed, 581 insertions(+), 4 deletions(-) create mode 100644 android/app/src/main/res/values-ru/strings.xml diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/settings/LanguagePrefs.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/LanguagePrefs.kt index 6a41f757..98aed0f5 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/settings/LanguagePrefs.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/LanguagePrefs.kt @@ -12,9 +12,10 @@ import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map /** - * App language choice. [ENGLISH]/[SIMPLIFIED_CHINESE] mirror the web's - * `Locale` (`'en' | 'zh-Hans'`); [SYSTEM] is the Android-only default — - * follow the device language (empty per-app locale list). + * App language choice. [ENGLISH]/[SIMPLIFIED_CHINESE]/[RUSSIAN] mirror the + * web's `Locale` (`'en' | 'zh-Hans'` plus the fork's `'ru'`); [SYSTEM] is the + * Android-only default — follow the device language (empty per-app locale + * list). * * B-M5a wires the selection through `AppCompatDelegate.setApplicationLocales` * ([localeTags] is the BCP-47 tag list to apply); the Settings screen applies @@ -24,7 +25,8 @@ import kotlinx.coroutines.flow.map enum class AppLanguage(val storageKey: String, val localeTags: String) { SYSTEM("system", ""), ENGLISH("en", "en"), - SIMPLIFIED_CHINESE("zh-Hans", "zh-Hans"); + SIMPLIFIED_CHINESE("zh-Hans", "zh-Hans"), + RUSSIAN("ru", "ru"); companion object { fun fromStorageKey(raw: String?): AppLanguage = diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/SettingsScreen.kt index 9da3db64..7a4e7a4d 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/settings/SettingsScreen.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/SettingsScreen.kt @@ -377,4 +377,5 @@ private fun languageLabel(language: AppLanguage): String = when (language) { AppLanguage.SYSTEM -> stringResource(R.string.settings_language_system) AppLanguage.ENGLISH -> "English" AppLanguage.SIMPLIFIED_CHINESE -> "简体中文" + AppLanguage.RUSSIAN -> "Русский" } diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml new file mode 100644 index 00000000..c21500a9 --- /dev/null +++ b/android/app/src/main/res/values-ru/strings.xml @@ -0,0 +1,573 @@ + + + HAPI + + + Копировать + Скопировано + текст + Двоичный файл не показан + Показать ещё строк: %1$d + Свернуть + + + Сопряжение с хабом + HAPI размещается самостоятельно: ваши агенты кодинга работают на ваших машинах за хабом HAPI, которым управляете вы. Сопрягите это приложение с хабом, чтобы наблюдать за ними и управлять ими с телефона. + Отсканируйте QR-код «Companion app», который хаб печатает при запуске (с --relay), либо введите URL хаба и токен доступа вручную. + Сканировать QR-код + Ввести вручную + Закрыть + Закрыть + Проверка хаба… + Сопрячь с этим хабом? + Этот хаб уже сопряжён с этим устройством. + Сопрячь сейчас + Использовать существующее сопряжение + Пересопрячь с новым кодом + Отмена + Эта ссылка для сопряжения недействительна, неполна или не использует HTTPS. + Назад + + + Ручное сопряжение + Оба значения можно найти в терминале хаба при запуске или в веб-приложении в разделе Настройки → Сопряжение с приложением. + URL хаба + https://hub.example.com + Токен доступа + Вставьте токен доступа + Сопрячь + + + Сканировать QR для сопряжения + Наведите камеру на QR-код сопряжения + Этот QR-код не является действительным HTTPS-кодом сопряжения HAPI. Отсканируйте один из двух QR-кодов, которые печатает хаб (Companion app или Web app). + Сканировать снова + Для сканирования QR-кода нужен доступ к камере. Можно также сопрячь вручную. + Разрешить доступ к камере + + + Меню + Настройки + Хаб + Хабы и настройки + Переключить хаб + Сопрячь другой хаб… + Выйти + Удалить сопряжение с этим хабом? Сохранённые учётные данные будут удалены с устройства (сам хаб не затрагивается). + Отмена + + + Новая сессия + Назад + Новая сессия + Машина + Загрузка машин… + Нет машин онлайн + Последняя ошибка запуска раннера: %1$s + Каталог + /путь/к/проекту + Обзор каталогов + Выбрать каталог + Перейти в родительский каталог + Обновить + Показывать скрытые + Нет подкаталогов + Выбрать текущий каталог + Недавние пути + Тип сессии + Обычная + Использовать выбранный каталог как есть + Worktree + Создать новый git worktree рядом с репозиторием + Имя worktree + feature-x (необязательно) + Агент + Проверка установленных агентов… + Повторить + Модель + Усилие + Усилие рассуждений + Режим разрешений + Управляется агентом + Этот агент сам управляет разрешениями. Режим YOLO недоступен. + Режим YOLO + Обойти подтверждения и песочницу + Использует опасные флаги агента при запуске. + Применяет нативный режим %1$s. + Режим совместной работы + Режим агента + Быстрый режим + Стандартный + Быстрый + Загрузка… + Создать + Создание… + Создать и создать каталог + + + Настройки + Назад + Отмена + Повторить + Не удалось загрузить эту панель. + Эта панель доступна только владельцу хаба (пространство имён по умолчанию). + + Оформление + Тема + Как в системе + Светлая + Тёмная + Чёрная OLED + Цвета Material You + Брать цвета приложения из обоев. + Недоступно с чёрной OLED. + + Язык + Язык приложения + Как в системе + + Аналитика + Использование токенов по агентам и моделям + Размер базы данных хаба на диске + + О программе + Версия приложения + Версия протокола + Хаб + Проверка хаба… + Статус: %1$s · протокол v%2$d + Хаб недоступен — нажмите, чтобы повторить. + + + Использование + 7 дней + 30 дней + За всё время + Всего токенов + Без кеша + Вход + Выход + Чтение кеша + Создание кеша + Доля попаданий в кеш + Запросы + Токены по дням + Токены: %1$s · запросов: %2$d · вход %3$s / выход %4$s + 0 токенов + По агентам + По моделям + Запросы: %1$d · вход %2$s · выход %3$s + Сессий с использованием: %1$d + За этот период использование не зафиксировано. + + + Хранилище + Место на диске, занимаемое базой SQLite хаба (база, журнал упреждающей записи, общая память). + Файлы SQLite + Данные о хранилище не переданы. + База данных + Журнал упреждающей записи + Общая память + Итого + Путь + Обновить + Обновление… + + + Запросы разрешений + Агент ждёт, чтобы вы разрешили или отклонили вызов инструмента + Вопросы к вам + Агенту нужен ваш ответ на вопрос в сессии + Агент готов + Агент завершил работу и ждёт ввода + Уведомления о задачах + Задача выполнена или завершилась с ошибкой, а также другие обновления + Разрешить + Отклонить + Ответить + Закрыть + Сообщение + Разрешение… + Отклонение… + Отправка… + Разрешено + Отклонено + Ответ отправлен + Уже обработано + Сессия больше не активна — откройте приложение, чтобы возобновить её + Сессия не найдена ни на одном сопряжённом хабе + Не удалось связаться с хабом — откройте приложение, чтобы ответить + Ответ не отправлен — откройте приложение, чтобы повторить + + + Закреплённые + Сессии + Все + Неизвестная машина + Офлайн — показаны кешированные сессии + Загрузка сессий… + Хаб недоступен + Сессий пока нет + Получение списка сессий с хаба. + Потяните, чтобы повторить, когда вернётесь онлайн. + Запустите агента через CLI hapi, и он появится здесь. + нужен ввод + одобрить %1$s + ожидает + Открепить + Закрепить за проектом + Закрепить глобально + Переименовать + Открыть заново + Архивировать + Удалить + Не удалось закрепить + Не удалось архивировать + Не удалось переименовать + Не удалось удалить + Не удалось открыть заново + Не удалось загрузить машины + Сессия ещё активна — сначала архивируйте её + Не удалось открыть сессию заново + Переименовать сессию + Имя сессии + Удалить сессию? + «%1$s» и история её сообщений будут навсегда удалены с хаба. Активные сессии сначала нужно архивировать. + Отмена + сейчас + + + Назад + Файлы сессии + Заметки + Заметки (%1$d) + Настройки сессии + Действия с сессией + Заметки + Сессия неактивна — отправьте сообщение, чтобы возобновить, или + Повторить + Загрузка сообщений… + Загрузка старых сообщений… + Не удалось загрузить эту сессию + Проверьте подключение к хабу и попробуйте снова. + Сообщений пока нет + Сообщения появятся здесь по мере работы агента. + 1 новое сообщение ↓ + Новых сообщений: %1$d ↓ + + + На хабе не настроен провайдер транскрипции + Для диктовки нужен доступ к микрофону + Для фото нужен доступ к камере + %1$s превышает лимит загрузки 50 МБ + Не удалось прочитать %1$s + Черновик отложен в заметки + Заметки заполнены (200 записей) + Не удалось отложить черновик — проверьте подключение к хабу + Вложения ещё загружаются — подождите либо повторите или удалите неудачные + Сессия неактивна, и её не удалось возобновить + Не удалось прервать + Не удалось переименовать сессию + Не удалось удалить сессию + Не удалось отменить сообщение в очереди + Сообщение отменено — текущий черновик сохранён + Уже доставлено агенту + Не удалось направить сообщение + Запрос уже обработан + Запрос не выполнен + Не удалось загрузить модели + Не удалось обновить сессию + + + Сообщение агенту… + Загрузка… + Ошибка — нажмите, чтобы повторить + ● Запись… %1$s + Отмена + Отложить черновик в заметки + Добавить вложение + Начать диктовку + Остановить запись + Отправить + Остановить текущий ход + Отправить и вклиниться в текущий ход + 1 сообщение в очереди + Сообщений в очереди: %1$d + По расписанию · %1$s + Направить + Изменить + Прикрепить + Галерея + Камера + Файлы + + + Не удалось начать запись + Не удалось связаться с хабом + Ошибка записи звука + Звук не записан + Ошибка транскрипции + + + Сессия офлайн — изменения применятся после возобновления или могут быть отклонены. + Сессией управляют из терминала — изменения конфигурации будут отклонены. + Режим разрешений + Модель + Загрузка моделей… + Список моделей недоступен для этой сессии. + Усилие + + + Ожидает одобрения + ⏳ Ожидает одобрения + ✓ Одобрено + ✕ Отклонено + Решено в Codex + — Отменено + ожидает + ошибка + 1 шаг агента + Шаги агента: %1$d + 1 инструмент + Инструменты: %1$d + До + После + Правка %1$d/%2$d + (пусто) + Результат + Результат · ошибка + 💭 Рассуждения ▾ + 💭 Рассуждения ▸ + Не доставлено — нажмите, чтобы повторить + Не доставлено + Ревью кода + 1 замечание + Замечания: %1$d + + + Разрешить + Отклонить + Прервать + Разрешить для этой сессии + Разрешить все правки + Уже обработано в другом месте + Введите ответ… + Сначала введите ответ + Сначала ответьте на все вопросы + Сначала ответьте на все обязательные вопросы + Отправить + Другое… + %1$s (необязательно) + Добавить примечание… + Ничего из перечисленного + При желании добавьте подробности в примечании. + + + Открыть ссылку? + Открыть + Нет приложения, способного открыть эту ссылку + + + Терминал + Чтение файла + Чтение блокнота + Правка файла + Правка блокнота + Запись файла + Поиск файлов + Поиск по содержимому + Список файлов + Веб-запрос + Веб-поиск + Задача + Запуск агента + Агент: %1$s + Агент + Запустить агента + Возобновить агента + Ждать агента + Закрыть агента + Прервать агента + Широковещание + Завершение: %1$s + агент + Ответ на завершение + Сообщение: %1$s + Сообщение агенту + Список агентов + Команда: %1$s + Создать команду + Удалить команду + Список задач + План + Предложение плана + Реализовать план + Продолжить планирование + Навык + Навык: %1$s + Рассуждения + Запрос разрешения + Разрешение: %1$s + Применить изменения + Диф + Журнал %1$s + Просмотр журнала задачи + Фоновая задача + Ошибка + Запуск оболочки + Поиск + Открыть URL + Запрос + Вопрос + Вопросы: %1$d + %1$s (+ещё %2$d) + Строки: %1$d + Символы: %1$d + %1$s (правки: %2$d) + + + Назад + Файлы + Обновить + Изменения + Обзор + Поиск + Статус Git недоступен для этой сессии + Отсоединённый HEAD + %1$d в индексе · %2$d вне индекса + В рабочем дереве нет изменений + В индексе (%1$d) + Вне индекса (%1$d) + Корень проекта + Показывать скрытые файлы + Свернуть + Развернуть + Поиск файлов… + Начните вводить текст для поиска файлов в каталоге сессии + Файлы не найдены + Статус Git недоступен + Диф вне индекса недоступен: %1$s + Диф в индексе недоступен: %1$s + неизвестная ошибка + Не удалось получить список каталога + Не удалось выполнить поиск файлов + Не удалось загрузить диф + Не удалось прочитать файл + Скопировано + Копировать путь + Диф + Файл + Вне индекса + В индексе + Исходник + Предпросмотр + Строка %1$d + В этом файле нет изменений + Этот файл пуст + Двоичный файл — предпросмотр недоступен + Предпросмотр для этого формата изображения недоступен + + + Назад + Заметки + Нет заметок + 1 заметка + Заметки: %1$d + Новая заметка + Редактировать заметку + В поле ввода + Только вложение + Заметка, черновик, идея на потом… + Добавить фото + Удалить + Отмена + Сохранить + Повторить + Не удалось загрузить заметки + Проверьте подключение к хабу и попробуйте снова. + Заметок пока нет + Откладывайте черновики из поля ввода или нажмите +, чтобы записать заметку для этой сессии. + Заметки заполнены (200 записей) — сначала удалите одну + Заметки заполнены (200 записей) + У заметки должен быть текст или вложение — используйте «Удалить», чтобы убрать её + Не удалось сохранить заметку — проверьте подключение к хабу + Не удалось удалить заметку — проверьте подключение к хабу + Не удалось прикрепить файл — проверьте подключение к хабу + Не удалось убрать вложение — проверьте подключение к хабу + Этот файл превышает лимит размера файла на хабе + Ошибка загрузки — проверьте подключение к хабу + Не удалось прочитать выбранный файл + Изображение слишком большое даже после сжатия + Максимум вложений в заметке: %1$d + Этот тип файла не разрешён для вложений в заметки + Этот файл превышает лимит %1$d МБ + Бюджет вложений этой заметки исчерпан + + + Введите корректный HTTPS-URL хаба, например https://hub.example.com. + Введите токен доступа, который показывает ваш хаб. + Хаб отклонил этот токен доступа. Токены меняются при ротации CLI_API_TOKEN на хабе — возьмите свежий QR-код или токен и попробуйте снова. + Этот хаб больше не сопряжён. Сопрягите его заново ниже. + Не удалось связаться с %1$s. Проверьте адрес, сеть и то, что хаб запущен. + %1$s ответил, но это не похоже на хаб HAPI. Перепроверьте URL (это должен быть адрес самого хаба, а не веб-приложения). + Этот хаб использует протокол v%1$d, а приложение поддерживает v%2$d. Обновите приложение и попробуйте снова. + Этот хаб использует протокол v%1$d, а приложение поддерживает v%2$d. Обновите хаб и попробуйте снова. + Сопряжение не удалось (HTTP %1$d). Попробуйте снова через мгновение. + Сопряжение этого устройства отозвано — токен доступа хаба изменился. Сопрягите заново, чтобы продолжить. + Хаб продолжал отклонять сессию этого устройства. Сопрягите заново, чтобы продолжить. + Сохранённые учётные данные для этого хаба пропали. Сопрягите заново, чтобы продолжить. + + + Для сессий worktree нужен существующий каталог репозитория. + Каталог не существует. При создании сессии он будет создан автоматически. + Каталог не существует. Нажмите «Создать» ещё раз, чтобы создать его автоматически. + Не удалось создать сессию + Не удалось загрузить модели Codex + Не удалось загрузить модели: %1$s + Имя должно содержать хотя бы одну букву или цифру + Каталог должен находиться внутри одного из корней рабочего пространства этой машины. + Не удалось просмотреть каталоги + Не удалось проверить установленных агентов + Обновите и перезапустите раннер HAPI этой машины перед созданием сессий. + На этой машине не установлено ни одного поддерживаемого агента. + Выбранный агент недоступен на этой машине. + К последним ↓ + Не удалось загрузить историю. Нажмите, чтобы повторить. + Продолжить загрузку истории + Загрузить старые сообщения + Начало разговора + Копировать всё содержимое + Показано %1$d из %2$d частей + Загрузить больше + Вопросы и ответы + Ответы + Свой ответ + Примечание + Показать сообщение целиком + Сообщение целиком + Предыдущая часть + Следующая часть + Часть %1$d + Повторить экспорт + Экспортировать полный текст + Скопировано + Закрыть просмотр + Снимок только для чтения. Эта запись больше не в текущем окне сообщений. + Более ранние вызовы не загружены. Вернитесь к разговору, чтобы загрузить старую историю. + Детали инструмента + Это содержимое недоступно. Вернитесь к разговору, чтобы загрузить его снова. + Последний инструмент + Показать текущий файл + Показать полный ввод + Показать процесс · шагов: %1$d + Процесс агента + Показать изображение + Переподключение… Нажмите, чтобы повторить + Фильтры + Фильтры применены + Сбросить фильтр + Машина · %1$s + Фильтр: %1$s + Политика конфиденциальности + Нет приложения, способного открыть эту ссылку. + diff --git a/android/app/src/main/res/xml/locales_config.xml b/android/app/src/main/res/xml/locales_config.xml index 281d26a7..13466b1b 100644 --- a/android/app/src/main/res/xml/locales_config.xml +++ b/android/app/src/main/res/xml/locales_config.xml @@ -4,4 +4,5 @@ + From eca9e99331f90a4288ef56d51216a2c50a1824a3 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:15:15 +0100 Subject: [PATCH 26/34] feat(web): Enlarge button for dictation and text submission (#2006) (#2007) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(web): larger empty-composer voice/dictate hit target When the primary UnifiedButton is idle voice/dictate (empty draft), use h-12 w-12 so Quest and touch clients get a usable target. Compact h-8 w-8 remains for Send, stop, and disabled states. Closes #2006 Co-authored-by: Cursor * feat(web): full-height composer primary (voice ↔ send) Park UnifiedButton beside the composer card so it stretches the full input+toolbar height. Empty shows giant voice/dictate; draft swaps the same giant control to Send (icon only). Refs #2006 Co-authored-by: Cursor * test(web): fix fill-height primary goldens + UnifiedButton mocks (#2006) Fill-height tip regressed no-arg onSend assertions and empty-voice helper expect; HappyComposer omitPrimaryButton needs UnifiedButton in vi.mocks. Co-authored-by: Cursor * test(web): assert onSend('default') + fill-height helpers (#2006) Co-authored-by: Cursor * fix(web): flush fill-height composer primary to card edge (#2006) Co-authored-by: Cursor * fix(web): keep draft voice companion beside fill-height Send (#2006) Co-authored-by: Cursor * fix(web): keep draft voice companion beside fill-height Send (#2006) Revert accidental soup dump of expandEnter + fat ComposerButtons. Empty stays giant voice; draft shows companion waveform left of giant Send. Co-authored-by: Cursor * fix(web): draft voice as toolbar circle, not beside giant Send (#2006) Co-authored-by: Cursor * fix(web): hide draft voice when scratchlist owns Send (#2006) Codex P2: toolbar DictationButton and Ctrl/Cmd+Shift+D must not start voice while routesToScratchlist — same suppress as UnifiedButton. Co-authored-by: Cursor * fix(web): compact primary when composer is expanded (#2006) Fill-height Send/voice is for the collapsed Quest card. Expanded mode stays a compact control so we do not paint a full-shell action strip. Co-authored-by: Cursor * chore: re-trigger upstream pr-review after Sol distributor 503 Empty commit — test/integration already green on tip; pr-review failed twice with "No available channel for model gpt-6.1-sol". Co-authored-by: Cursor --------- Co-authored-by: Cursor --- .../AssistantChat/ComposerButtons.test.tsx | 157 ++++++++- .../AssistantChat/ComposerButtons.tsx | 180 ++++++++-- .../HappyComposer.expandSelection.test.tsx | 3 + .../HappyComposer.sendError.test.tsx | 7 +- .../AssistantChat/HappyComposer.tsx | 309 ++++++++++-------- web/src/lib/composerDictateShortcut.test.ts | 21 +- web/src/lib/composerDictateShortcut.ts | 14 +- 7 files changed, 510 insertions(+), 181 deletions(-) diff --git a/web/src/components/AssistantChat/ComposerButtons.test.tsx b/web/src/components/AssistantChat/ComposerButtons.test.tsx index 3b7df015..013196c9 100644 --- a/web/src/components/AssistantChat/ComposerButtons.test.tsx +++ b/web/src/components/AssistantChat/ComposerButtons.test.tsx @@ -12,7 +12,11 @@ import { ComposerExpandButton, DictationButton, getComposerToolbarJustifyContent, + isComposerPrimaryFillHeight, + isLargeEmptyVoicePrimary, + shouldShowDraftVoiceButton, UnifiedButton, + unifiedButtonSizeClass, } from './ComposerButtons' const adapter: ChatModelAdapter = { @@ -161,6 +165,104 @@ describe('UnifiedButton — default send intent', () => { }) }) +describe('UnifiedButton — fill-height primary (voice ↔ send)', () => { + afterEach(cleanup) + + it('fills height when empty with voice/dictate afforded', () => { + expect(isLargeEmptyVoicePrimary({ + canSend: false, + voiceEnabled: true, + voiceStatus: 'disconnected', + })).toBe(true) + expect(isComposerPrimaryFillHeight({ + canSend: false, + voiceEnabled: true, + voiceStatus: 'disconnected', + })).toBe(true) + expect(unifiedButtonSizeClass(true)).toContain('h-full') + expect(unifiedButtonSizeClass(true)).toContain('w-16') + expect(unifiedButtonSizeClass(true)).toContain('rounded-r-[20px]') + + renderInProviders( + {}} + onVoiceToggle={() => {}} + voiceLabel="Dictate" + fillHeight + />, + ) + const btn = getButton(/^Dictate/) + expect(btn.getAttribute('data-size')).toBe('fill') + expect(btn.className).toContain('h-full') + expect(btn.className).toContain('w-16') + }) + + it('keeps the same fill-height layout when a draft swaps the icon to Send', () => { + // Draft → Send morph; still fill-height. Empty-voice FUE helper stays false. + expect(isLargeEmptyVoicePrimary({ + canSend: true, + voiceEnabled: true, + voiceStatus: 'disconnected', + })).toBe(false) + expect(isComposerPrimaryFillHeight({ + canSend: true, + voiceEnabled: true, + voiceStatus: 'disconnected', + })).toBe(true) + + renderInProviders( + {}} + onVoiceToggle={() => {}} + fillHeight + />, + ) + const btn = getButton('Send') + expect(btn.getAttribute('data-size')).toBe('fill') + expect(btn.className).toContain('h-full') + expect(btn.className).toContain('w-16') + }) + + it('fills height while voice is connected (stop)', () => { + renderInProviders( + {}} + onVoiceToggle={() => {}} + fillHeight + />, + ) + const btn = getButton('Stop') + expect(btn.getAttribute('data-size')).toBe('fill') + }) + + it('stays compact when the composer editor is expanded', () => { + expect(isComposerPrimaryFillHeight({ + canSend: true, + voiceEnabled: true, + voiceStatus: 'disconnected', + expanded: true, + })).toBe(false) + expect(isComposerPrimaryFillHeight({ + canSend: false, + voiceEnabled: true, + voiceStatus: 'connected', + expanded: true, + })).toBe(false) + }) +}) + describe('DictationButton', () => { afterEach(cleanup) @@ -168,18 +270,71 @@ describe('DictationButton', () => { const onVoiceToggle = vi.fn() renderInProviders( , ) fireEvent.click(getButton(/^Dictate/)) expect(onVoiceToggle).toHaveBeenCalledOnce() }) + + it('hides draft voice when the draft routes to the scratchlist', () => { + expect(shouldShowDraftVoiceButton({ + canSend: true, + voiceEnabled: true, + voiceStatus: 'disconnected', + routesToScratchlist: true, + })).toBe(false) + + const { container } = renderInProviders( + , + ) + expect(container.querySelector('[data-testid="composer-draft-voice-button"]')).toBeNull() + }) + + it('keeps assistant voice as a compact toolbar circle when a draft is present', () => { + expect(shouldShowDraftVoiceButton({ + canSend: true, + voiceEnabled: true, + voiceStatus: 'disconnected', + })).toBe(true) + expect(shouldShowDraftVoiceButton({ + canSend: false, + voiceEnabled: true, + voiceStatus: 'disconnected', + })).toBe(false) + + const onVoiceToggle = vi.fn() + renderInProviders( + , + ) + const btn = getButton('Voice assistant') + expect(btn.getAttribute('data-variant')).toBe('toolbar') + expect(btn.className).toContain('h-8') + expect(btn.className).toContain('w-8') + expect(btn.className).toContain('rounded-full') + fireEvent.click(btn) + expect(onVoiceToggle).toHaveBeenCalledOnce() + }) }) describe('ComposerExpandButton', () => { diff --git a/web/src/components/AssistantChat/ComposerButtons.tsx b/web/src/components/AssistantChat/ComposerButtons.tsx index f5211408..a9b38377 100644 --- a/web/src/components/AssistantChat/ComposerButtons.tsx +++ b/web/src/components/AssistantChat/ComposerButtons.tsx @@ -46,12 +46,13 @@ function ChevronIcon() { return } -function VoiceAssistantIcon() { +function VoiceAssistantIcon(props: { size?: number }) { + const size = props.size ?? 18 return ( void onVoiceToggle: () => void voiceLabel?: string + /** + * When true, stretch to the composer card height (beside input + toolbar). + * Default true — Quest / touch need a full-height primary control. + */ + fillHeight?: boolean /** * When true, the send button repaints amber and the aria-label * announces "Send to scratchlist" instead of "Send message". The @@ -498,6 +569,8 @@ export function UnifiedButton(props: { const isVoiceActive = isConnecting || isConnected const hasText = props.canSend const routesToScratchlist = props.routesToScratchlist ?? false + const fillHeight = props.fillHeight ?? true + const iconSize = fillHeight ? 28 : 18 const handleClick = () => { if (isVoiceActive) { @@ -533,7 +606,7 @@ export function UnifiedButton(props: { className = 'bg-black text-white' ariaLabel = t('composer.send') } else if (props.voiceEnabled) { - icon = + icon = className = 'bg-black text-white' ariaLabel = props.voiceLabel ?? t('composer.voice') } else { @@ -560,7 +633,9 @@ export function UnifiedButton(props: { disabled={isDisabled} aria-label={ariaLabel} title={ariaLabel} - className={`ml-1 flex h-8 w-8 items-center justify-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${className}`} + data-testid="composer-unified-button" + data-size={fillHeight ? 'fill' : 'compact'} + className={`flex ${unifiedButtonSizeClass(fillHeight)} items-center justify-center transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${className}`} > {icon} @@ -568,32 +643,51 @@ export function UnifiedButton(props: { } export function DictationButton(props: { - enabled: boolean + /** + * When false, hide. When true/omitted, show whenever a draft steals Send + * from the primary (assistant voice and dictation modes). + */ + enabled?: boolean canSend: boolean voiceEnabled: boolean voiceStatus: ConversationStatus controlsDisabled: boolean onVoiceToggle: () => void + /** Override aria/title (dictate vs voice assistant). */ + voiceLabel?: string + /** Flush companion beside fill-height Send (HappyComposer omitPrimary). */ + variant?: 'toolbar' | 'companion' + routesToScratchlist?: boolean }) { const { t } = useTranslation() - if ( - !props.enabled - || !props.canSend - || !props.voiceEnabled - || props.voiceStatus === 'connecting' - || props.voiceStatus === 'connected' - ) return null + if (props.enabled === false) return null + if (!shouldShowDraftVoiceButton({ + canSend: props.canSend, + voiceEnabled: props.voiceEnabled, + voiceStatus: props.voiceStatus, + routesToScratchlist: props.routesToScratchlist, + })) return null + + const label = props.voiceLabel ?? t('composer.dictate') + const companion = props.variant === 'companion' + const iconSize = companion ? 24 : 18 return ( ) } @@ -652,6 +746,11 @@ export function ComposerButtons(props: { scratchlistMode?: boolean scratchlistCount?: number onScratchlistToggle?: () => void + /** + * When true, omit UnifiedButton — HappyComposer places it in a + * full-height column beside the input + toolbar. + */ + omitPrimaryButton?: boolean }) { const { t } = useTranslation() const { layout } = useComposerToolbarLayout() @@ -888,34 +987,47 @@ export function ComposerButtons(props: {
+ {/* + Draft voice/dictate: compact circle in the toolbar row (under text). + Primary column stays a single fill-height Send/voice control so we + do not steal horizontal space from the composer. + */} - - + + {props.omitPrimaryButton ? null : ( + + )}
) } diff --git a/web/src/components/AssistantChat/HappyComposer.expandSelection.test.tsx b/web/src/components/AssistantChat/HappyComposer.expandSelection.test.tsx index 7d411897..6130a255 100644 --- a/web/src/components/AssistantChat/HappyComposer.expandSelection.test.tsx +++ b/web/src/components/AssistantChat/HappyComposer.expandSelection.test.tsx @@ -32,6 +32,9 @@ vi.mock('@/components/AssistantChat/ComposerButtons', () => ({ ) : null}
), + UnifiedButton: () => null, + DictationButton: () => null, + isComposerPrimaryFillHeight: () => true, })) vi.mock('@/components/AssistantChat/StatusBar', () => ({ StatusBar: () => null })) diff --git a/web/src/components/AssistantChat/HappyComposer.sendError.test.tsx b/web/src/components/AssistantChat/HappyComposer.sendError.test.tsx index e8942626..e4beced1 100644 --- a/web/src/components/AssistantChat/HappyComposer.sendError.test.tsx +++ b/web/src/components/AssistantChat/HappyComposer.sendError.test.tsx @@ -124,7 +124,6 @@ vi.mock('@/components/AssistantChat/ComposerButtons', () => ({ onModelValueToggle?: () => void }) => (
- @@ -136,6 +135,12 @@ vi.mock('@/components/AssistantChat/ComposerButtons', () => ({ {JSON.stringify(props.pendingSchedule)}
), + // HappyComposer places UnifiedButton beside the card (omitPrimaryButton). + UnifiedButton: (props: { onSend: () => void }) => ( + + ), + DictationButton: () => null, + isComposerPrimaryFillHeight: () => true, })) type HarnessControls = { diff --git a/web/src/components/AssistantChat/HappyComposer.tsx b/web/src/components/AssistantChat/HappyComposer.tsx index 5be36c39..943ec838 100644 --- a/web/src/components/AssistantChat/HappyComposer.tsx +++ b/web/src/components/AssistantChat/HappyComposer.tsx @@ -48,7 +48,11 @@ import { useComposerEnterBehavior } from '@/hooks/useComposerEnterBehavior' import { FloatingOverlay } from '@/components/ChatInput/FloatingOverlay' import { Autocomplete } from '@/components/ChatInput/Autocomplete' import { StatusBar } from '@/components/AssistantChat/StatusBar' -import { ComposerButtons } from '@/components/AssistantChat/ComposerButtons' +import { + ComposerButtons, + UnifiedButton, + isComposerPrimaryFillHeight, +} from '@/components/AssistantChat/ComposerButtons' import type { PendingSchedule } from '@/components/AssistantChat/ScheduleTimePicker' import { SortableComposerAttachments } from '@/components/AssistantChat/SortableComposerAttachments' import { ComposerParkingContext } from '@/components/AssistantChat/composerParkingContext' @@ -1627,6 +1631,13 @@ export function HappyComposer(props: { const showAbortButton = true const voiceEnabled = Boolean(effectiveVoiceToggle) const routesToScratchlist = (props.scratchlistMode ?? false) && pendingSchedule == null + const primaryFillHeight = isComposerPrimaryFillHeight({ + canSend, + voiceEnabled, + voiceStatus: effectiveVoiceStatus, + routesToScratchlist, + expanded: isExpanded, + }) const invokeDictateHotkey = useCallback(() => { if (!shouldInvokeComposerDictateShortcut({ @@ -2260,158 +2271,184 @@ export function HappyComposer(props: { ) : null}
- {attachments.length > 0 ? ( -
- -
- ) : null} - -
- {richMentionsEnabled ? ( -
- 0 ? ( +
+ +
+ ) : null} + +
+ {richMentionsEnabled ? ( +
+ engageRichComposerFue()} + resolveSessionMentionTooltip={resolveSessionMentionTooltip} + onEdit={handleRichEdit} + className={editorClassName} + /> + {richComposerFueStatus !== 'acknowledged' ? ( + + ) : null} +
+ ) : isExpanded ? ( + engageRichComposerFue()} - resolveSessionMentionTooltip={resolveSessionMentionTooltip} - onEdit={handleRichEdit} - className={editorClassName} - /> - {richComposerFueStatus !== 'acknowledged' ? ( - +