diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts index ab6660895a..18f7c48144 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts @@ -2233,3 +2233,15 @@ it.effect.each([false, true])( ); }, ); + +it.each([ + ["preview-config", "Alt+Super+C is already used by Hyprland. Choose another shortcut."], + ["apply-config", "Your config changed since this preview. Review changes again before saving."], +] as const)("tells the renderer why %s failed", (action, reason) => { + const error = new DesktopSnapShot.DesktopSnapShotSetupError({ + action, + reason: "setup-failed", + cause: new Error(reason), + }); + assert.include(error.message, reason); +}); diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index e0c0c8a71b..0832af10a0 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -262,9 +262,14 @@ export class DesktopSnapShotSetupError extends Schema.TaggedError { const outcomes = ["declined", "cancelled", "pending"] as const; const results = await Effect.forEach(outcomes, (outcome) => { - const dispatched: Array<{ readonly type: string; readonly turnItemId?: string }> = []; + const dispatched: Array<{ + readonly type: string; + readonly turnItemId?: string; + readonly secretStatus?: string; + }> = []; const projection = () => { const card = dispatched.find((command) => command.type === "secret_request.record"); return { @@ -1402,14 +1407,24 @@ it("requestSecret returns the unsaved note for a declined, cancelled or timed-ou }) .pipe(Effect.forkChild({ startImmediately: true })); yield* TestClock.adjust("2 seconds"); - return yield* Fiber.join(request); + const result = yield* Fiber.join(request); + return { result, recorded: dispatched.map((command) => command.secretStatus) }; }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer()))); }).pipe(Effect.runPromise); expect(results).toEqual([ - { status: "declined", note: SECRET_REQUEST_UNSAVED_NOTE.declined }, - { status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled }, - { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out }, + { + result: { status: "declined", note: SECRET_REQUEST_UNSAVED_NOTE.declined }, + recorded: ["pending"], + }, + { + result: { status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled }, + recorded: ["pending"], + }, + { + result: { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out }, + recorded: ["pending", "cancelled"], + }, ]); }); @@ -1501,6 +1516,84 @@ it("requestSecret cancels its card when a steering restart supersedes the reques }).pipe(Effect.provide(layer), Effect.runPromise); }); +it("requestSecret closes its card when the call is aborted while the card is being recorded", async () => { + const statuses: Array = []; + const projection = () => + ({ + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [ + { ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }, + ], + visibleTurnItems: [], + turnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + contextTransfers: [], + subagents: [], + updatedAt: now, + }) as unknown as OrchestrationV2ThreadProjection; + + await Effect.gen(function* () { + const recorded = yield* Deferred.make(); + const release = yield* Deferred.make(); + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.sync(projection), + getThreadShell: () => + Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell), + // The pending card is stored before the dispatch returns to the caller. + dispatch: (command) => + Effect.gen(function* () { + if (command.type !== "secret_request.record") return {} as never; + statuses.push(command.secretStatus); + if (command.secretStatus === "pending") { + yield* Deferred.succeed(recorded, undefined); + yield* Deferred.await(release); + } + return {} as never; + }), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), + NodeCrypto.layer, + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const request = yield* service + .requestSecret(makeScope(), { + label: "Staging password", + reason: "Signs in the QA account.", + }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(recorded); + const abort = yield* Fiber.interrupt(request).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(abort); + }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer()))); + }).pipe(Effect.runPromise); + + expect(statuses).toEqual(["pending", "cancelled"]); +}); + it("requestSecret delivers a fields card as one file per field", async () => { const dispatched: Array<{ readonly type: string; diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 4f20e6366f..40b1bc10f1 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2717,7 +2717,6 @@ const make = Effect.gen(function* () { ), ), ); - yield* record("pending"); // Only this call can hand the agent its ref, so the card must not // outlive it: a timeout, a failed wait or an aborted call closes it as // cancelled. @@ -2727,54 +2726,57 @@ const make = Effect.gen(function* () { ), ); - const answered = yield* Effect.gen(function* () { - while (true) { - const projection = yield* threadManagement - .getThreadRecords(threadId, ["runs", "turnItems"], { - turnItemTypes: ["secret_request"], - messageRoles: [], - }) - .pipe( - Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to read the secret request: ${errorMessage(error)}`, + const answered = yield* Effect.acquireUseRelease( + record("pending"), + () => + Effect.gen(function* () { + while (true) { + const projection = yield* threadManagement + .getThreadRecords(threadId, ["runs", "turnItems"], { + turnItemTypes: ["secret_request"], + messageRoles: [], + }) + .pipe( + Effect.mapError((error) => + failure( + "orchestration_error", + `Unable to read the secret request: ${errorMessage(error)}`, + ), + ), + ); + const item = projection.turnItems.find((candidate) => candidate.id === turnItemId); + if (item?.type === "secret_request" && item.secretStatus !== "pending") { + return item.secretStatus; + } + const current = projection.runs.find((candidate) => candidate.id === runId); + if ( + current === undefined || + ThreadManagementService.isTerminalRunStatus(current.status) + ) { + yield* record("cancelled"); + return "cancelled" as const; + } + // A steering restart replaced the run's root, so this request belonged to + // the superseded attempt: its card can never be answered into that attempt, + // and the call must stop blocking the agent's turn. + if (current.rootNodeId !== nodeId) { + yield* record("cancelled"); + return "cancelled" as const; + } + yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS)); + } + }).pipe( + Effect.timeoutOption( + Duration.millis( + Math.min( + input.timeoutMs ?? DEFAULT_SECRET_REQUEST_TIMEOUT_MS, + MAX_SECRET_REQUEST_TIMEOUT_MS, ), ), - ); - const item = projection.turnItems.find((candidate) => candidate.id === turnItemId); - if (item?.type === "secret_request" && item.secretStatus !== "pending") { - return item.secretStatus; - } - const current = projection.runs.find((candidate) => candidate.id === runId); - if ( - current === undefined || - ThreadManagementService.isTerminalRunStatus(current.status) - ) { - yield* record("cancelled"); - return "cancelled" as const; - } - // A steering restart replaced the run's root, so this request belonged to - // the superseded attempt: its card can never be answered into that attempt, - // and the call must stop blocking the agent's turn. - if (current.rootNodeId !== nodeId) { - yield* record("cancelled"); - return "cancelled" as const; - } - yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS)); - } - }).pipe( - Effect.timeoutOption( - Duration.millis( - Math.min( - input.timeoutMs ?? DEFAULT_SECRET_REQUEST_TIMEOUT_MS, - MAX_SECRET_REQUEST_TIMEOUT_MS, ), ), - ), - Effect.onError(() => closeCard), + (_, exit) => (Exit.isSuccess(exit) && Option.isSome(exit.value) ? Effect.void : closeCard), ); - if (Option.isNone(answered)) yield* closeCard; const status = Option.isSome(answered) ? answered.value : yield* threadManagement diff --git a/apps/server/src/mcpApps/McpAppModelContext.test.ts b/apps/server/src/mcpApps/McpAppModelContext.test.ts index eea5477177..0c7de2fd19 100644 --- a/apps/server/src/mcpApps/McpAppModelContext.test.ts +++ b/apps/server/src/mcpApps/McpAppModelContext.test.ts @@ -62,4 +62,53 @@ layer("McpAppModelContext", (it) => { assert.deepEqual(yield* texts(threadId), []); }), ); + + it.effect("drops pre-/clear MCP app notes, but not for a restarted scheduled fresh run", () => + Effect.gen(function* () { + yield* runMigrations(); + const sql = yield* SqlClient.SqlClient; + const store = yield* McpAppModelContext.McpAppModelContext; + const clearedThread = ThreadId.make("thread-cleared-context"); + + yield* sql` + INSERT INTO orchestration_v2_projection_runs + (run_id, thread_id, ordinal, provider, status, requested_at, payload_json) + VALUES + ('run-before-clear', ${clearedThread}, 1, 'codex', 'completed', '2026-01-01', '{"startedAt":"2026-01-01"}'), + ('run-clear', ${clearedThread}, 2, 'codex', 'completed', '2026-01-02', '{"freshContext":true,"startedAt":"2026-01-02","userMessageId":"msg-clear"}'), + ('run-after-clear', ${clearedThread}, 3, 'codex', 'completed', '2026-01-03', '{"startedAt":"2026-01-03"}'), + ('run-scheduled-fresh', ${clearedThread}, 4, 'codex', 'completed', '2026-01-04', '{"freshContext":true,"startedAt":"2026-01-04","userMessageId":"msg-restart"}') + `; + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items + (turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json) + VALUES + ('item-before-clear', ${clearedThread}, 'run-before-clear', 1, 'dynamic_tool', 'completed', '2026-01-01', '{}'), + ('item-after-clear', ${clearedThread}, 'run-after-clear', 2, 'dynamic_tool', 'completed', '2026-01-03', '{}'), + ('item-scheduled-prompt', ${clearedThread}, 'run-scheduled-fresh', 3, 'user_message', 'completed', '2026-01-04', '{"messageId":"msg-scheduled","scheduledTaskId":"sched-1"}'), + ('item-restart-prompt', ${clearedThread}, 'run-scheduled-fresh', 4, 'user_message', 'completed', '2026-01-04', '{"messageId":"msg-restart"}') + `; + + yield* store.set({ + threadId: clearedThread, + itemId: TurnItemId.make("item-before-clear"), + server: "todos", + tool: "list_todos", + text: "stale pre-clear note", + }); + yield* store.set({ + threadId: clearedThread, + itemId: TurnItemId.make("item-after-clear"), + server: "todos", + tool: "list_todos", + text: "fresh post-clear note", + }); + + const entries = yield* store.forThread(clearedThread); + assert.deepEqual( + entries.map((entry) => entry.text), + ["fresh post-clear note"], + ); + }), + ); }); diff --git a/apps/server/src/mcpApps/McpAppModelContext.ts b/apps/server/src/mcpApps/McpAppModelContext.ts index c59300689c..389b2e59d5 100644 --- a/apps/server/src/mcpApps/McpAppModelContext.ts +++ b/apps/server/src/mcpApps/McpAppModelContext.ts @@ -90,10 +90,33 @@ export const layer = Layer.effect( }); const forThread = Effect.fn("McpAppModelContext.forThread")(function* (threadId: ThreadId) { - // Match by id across fork lineage; later source rollbacks leave the fork's copy intact. + // Match by id across fork lineage; later source rollbacks leave the fork's copy intact, + // while a started /clear (fresh, not scheduled) run on this thread drops older notes. return yield* sql` + WITH boundary AS ( + SELECT COALESCE(MAX(b.ordinal), 0) AS min_ordinal + FROM orchestration_v2_projection_runs AS b + WHERE b.thread_id = ${threadId} + AND json_extract(b.payload_json, '$.freshContext') = 1 + AND b.status <> 'queued' + -- Mirrors startedFreshRun: a run that never started cleared nothing. + AND NOT ( + b.status IN ('cancelled', 'rolled_back') + AND json_extract(b.payload_json, '$.startedAt') IS NULL + AND json_extract(b.payload_json, '$.restartContinuationOfRunId') IS NULL + ) + -- Mirrors scheduledRunIds: the run's first prompt says whether a schedule sent it. + AND ( + SELECT json_extract(ti.payload_json, '$.scheduledTaskId') + FROM orchestration_v2_projection_turn_items AS ti + WHERE ti.run_id = b.run_id AND ti.type = 'user_message' + ORDER BY ti.ordinal + LIMIT 1 + ) IS NULL + ) SELECT context.item_id AS "itemId", context.server, context.tool, context.text FROM mcp_app_model_context AS context + CROSS JOIN boundary JOIN orchestration_v2_projection_turn_items AS item ON item.turn_item_id = context.item_id LEFT JOIN orchestration_v2_projection_runs AS run @@ -104,6 +127,10 @@ export const layer = Layer.effect( OR run.status <> 'rolled_back' OR run.thread_id <> context.thread_id ) + AND ( + boundary.min_ordinal = 0 + OR (run.thread_id = context.thread_id AND run.ordinal >= boundary.min_ordinal) + ) ORDER BY context.updated_at, context.item_id `.pipe(NodeSqliteClient.readOnly, Effect.mapError(fail)); }); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 7d5b513aa1..0a30a957d3 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -4170,6 +4170,56 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("sends a $skill named in a message that steers the running turn", () => + Effect.gen(function* () { + const prompts: Array = []; + const steerId = "msg_recorded_steer_skill"; + const greet = { + id: "greet", + name: "greet", + path: `${WORK}/.opencode/skills/greet/SKILL.md`, + content: "Say hello.", + }; + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.started", { sessionID: SESSION }), + out("skill.list", { "location[directory]": WORK }), + reply("skill.list", { location: { directory: WORK }, data: [greet] }), + out("session.prompt", { sessionID: SESSION, id: steerId, delivery: "steer" }), + replyData("session.prompt", { + id: steerId, + sessionID: SESSION, + time: { created: 1790656601500 }, + type: "user", + payload: { text: "$greet first" }, + delivery: "steer", + }), + event("session.inbox.delivered", { sessionID: SESSION, inboxID: steerId }), + event("session.execution.succeeded", { sessionID: SESSION }), + ], + { onPrompt: (input) => prompts.push(input) }, + ); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + const input = turnInput(thread); + yield* runtime.startTurn(input); + yield* runtime.steerTurn({ + threadId, + runId: input.runId, + providerThread: thread, + providerTurnId: yield* providerTurnId, + message: { + ...input.message, + messageId: MessageId.make("message:opencode2-adapter:steer"), + text: "$greet first", + }, + }); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + assert.deepInclude(prompts[1], { delivery: "steer", skills: [{ id: "greet" }] }); + }), + ); + it.effect.each([ { server: "an external server keeps rejecting requests", diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts index 86a495483c..c2b7fce6dc 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts @@ -357,8 +357,9 @@ it.effect("a portable fork carries no context its source discarded for a fresh s const supersededForkId = ThreadId.make("thread:fork-history-superseded-fork"); const parentRun = forkTestRun(parentId, 1, "PARENT_WORK"); const scheduledRun = forkTestRun(parentId, 2, "SCHEDULED_SIDE_RUN", "scheduled-fresh"); - const forkFresh = forkTestRun(freshForkId, 1, "FRESH_START", "fresh"); - const forkLater = forkTestRun(freshForkId, 2, "FORK_FOLLOW_UP"); + const forkBefore = forkTestRun(freshForkId, 1, "BEFORE_CLEAR"); + const forkFresh = forkTestRun(freshForkId, 2, "FRESH_START", "fresh"); + const forkLater = forkTestRun(freshForkId, 3, "FORK_FOLLOW_UP"); // Its fresh first run was cancelled before starting, so only the transfer records the discard. const supersededRun = forkTestRun(supersededForkId, 1, "AFTER_DISCARD"); const forkedFromParent = { type: "run", threadId: parentId, runId: parentRun.run.id } as const; @@ -376,6 +377,7 @@ it.effect("a portable fork carries no context its source discarded for a fresh s }); const parent = projection(forkTestThread(parentId), [parentRun, scheduledRun]); const freshFork = projection(forkTestThread(freshForkId, forkedFromParent), [ + forkBefore, forkFresh, forkLater, ]); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index f01ca90e20..f0c50d6446 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -10214,15 +10214,29 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const mergeBackDeltaItems = mergeBackSourceProjection === null || mergeBackSourceRun === null ? [] - : visibleConversationItems( - mergeBackSourceProjection, - yield* readHandoffItems( + : yield* Effect.gen(function* () { + const sourceRuns = mergeBackSourceProjection.runs.filter( + (run) => run.ordinal <= mergeBackSourceRun.ordinal, + ); + const rawItems = yield* readHandoffItems( mergeBackSourceProjection.thread.id, - mergeBackSourceProjection.runs - .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal) - .map((run) => run.id), - ), - ); + sourceRuns.map((run) => run.id), + ); + // Everything since the fork's latest /clear merges back, its scheduled sessions too. + const conversation = conversationRuns( + { + runs: sourceRuns, + turnItems: rawItems, + providerThreads: mergeBackSourceProjection.providerThreads, + }, + undefined, + { withScheduledRuns: true }, + ); + return visibleConversationItems( + mergeBackSourceProjection, + rawItems.filter((item) => item.runId !== null && conversation.runIds.has(item.runId)), + ); + }); const mergeBackHandoff = pendingMergeBackTransfer === undefined || mergeBackSourceProjection === null || diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index a3ac281ab1..b648ad67bb 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -1789,6 +1789,77 @@ it.effect.each<{ }).pipe(Effect.provide(forkCases[0]!.layer)), ); +it.effect("merge-back carries only the fork's context since its latest /clear", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const parentId = ThreadId.make("merge-back-clear-parent"); + const parentRunId = RunId.make("merge-back-clear-parent-run"); + const forkId = ThreadId.make("merge-back-clear-fork"); + const clearRunId = RunId.make("merge-back-clear-fork-run-2"); + yield* createParent(parentId); + yield* writeParentRun({ + threadId: parentId, + runId: parentRunId, + ordinal: 1, + status: "completed", + text: "Parent work", + }); + yield* orchestrator.dispatch({ + type: "thread.fork", + commandId: CommandId.make("merge-back-clear-fork"), + sourceThreadId: parentId, + targetThreadId: forkId, + sourcePoint: { type: "run", runId: parentRunId }, + createdBy: "user", + creationSource: "web", + }); + yield* writeParentRun({ + threadId: forkId, + runId: RunId.make("merge-back-clear-fork-run-1"), + ordinal: 1, + status: "completed", + text: "BEFORE_CLEAR_MARKER", + stable: true, + }); + yield* writeParentRun({ + threadId: forkId, + runId: clearRunId, + ordinal: 2, + status: "completed", + text: "AFTER_CLEAR_MARKER", + stable: true, + freshContext: true, + }); + // A fresh-session schedule is a side conversation, not a /clear of the fork's own. + yield* writeParentRun({ + threadId: forkId, + runId: RunId.make("merge-back-clear-fork-run-3"), + ordinal: 3, + status: "completed", + text: "SCHEDULED_MARKER", + stable: true, + freshContext: true, + scheduled: true, + }); + yield* orchestrator.dispatch({ + type: "thread.merge_back", + commandId: CommandId.make("merge-back-clear-merge"), + sourceThreadId: forkId, + targetThreadId: parentId, + sourcePoint: { type: "latest_stable" }, + createdBy: "user", + creationSource: "web", + }); + yield* askSideChat(parentId, "merge-back-clear-consume"); + + const parent = yield* orchestrator.getThreadProjection(parentId); + const context = parent.contextHandoffs.map((handoff) => handoff.summaryText).join("\n"); + assert.include(context, "AFTER_CLEAR_MARKER"); + assert.include(context, "SCHEDULED_MARKER"); + assert.notInclude(context, "BEFORE_CLEAR_MARKER"); + }).pipe(Effect.provide(forkCases[0]!.layer)), +); + it.effect("merge-back rejects a second fork's context until the first is consumed", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index 9fa1820572..a3cfc2be8d 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -1109,6 +1109,76 @@ effectIt.effect("stops only a job's own process group", () => }), ); +effectIt.effect.each([ + { + case: "its parent's arguments", + leader: { command: "node server.js", env: "COMMAND=cmd-a" }, + parent: { command: "/bin/bash -c set -m; COMMAND=cmd-a node server.js & wait", env: "" }, + stops: ["cmd-a"], + }, + { + case: "its own arguments", + leader: { command: "node server.js COMMAND=cmd-a", env: "" }, + parent: { command: "/bin/bash -c node server.js & wait", env: "" }, + stops: [], + }, +])("on macOS, a stop names the command in the leader's environment, not $case", (scenario) => { + const port = 43_127; + // macOS `ps -E` prints the environment after the arguments; plain `ps` prints only the arguments. + const command = (row: { command: string; env: string }, withEnvironment: boolean) => + withEnvironment + ? `${row.command} PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-a ${row.env}`.trim() + : row.command; + const layer = layerScanner.pipe( + Layer.provide( + Layer.mergeAll( + layerNoProc, + Layer.succeed(ProcessRunner.ProcessRunner, { + run: (input) => { + if (input.command === "lsof") { + return Effect.succeed(processOutput(`p4242\ncnode\nn127.0.0.1:${port}\n`)); + } + if (input.args[0] === "-A") { + return Effect.succeed( + processOutput(`4242 4300 4242\n4300 4200 4300\n4200 ${process.pid} 4200\n`), + ); + } + const withEnvironment = input.args.includes("-E"); + const withParent = input.args.includes("pid=,ppid=,command="); + return Effect.succeed( + processOutput( + ` 4242${withParent ? " 4300" : ""} ${command(scenario.leader, withEnvironment)}\n` + + ` 4300${withParent ? " 4200" : ""} ${command(scenario.parent, withEnvironment)}\n`, + ), + ); + }, + }), + Layer.succeed(HostProcess.Platform, "darwin"), + FetchHttpClient.layer, + ), + ), + ); + + return Effect.gen(function* () { + const signal = vi.spyOn(ProcessGroup, "signalProcessGroup").mockImplementation(() => { + throw Object.assign(new Error("No such process"), { code: "ESRCH" }); + }); + yield* Effect.addFinalizer(() => Effect.sync(() => signal.mockRestore())); + const scanner = yield* PortScanner.PortDiscovery; + scanner.trackAgent(); + const stops: string[] = []; + yield* scanner.watchAgentCommandStops({ + variable: "COMMAND", + onStop: (stopped) => Effect.sync(() => stops.push(stopped)), + onStopAbandoned: () => Effect.void, + }); + expect(yield* scanner.scan()).toMatchObject([{ pid: 4242, agent: { threadId: "thread-a" } }]); + yield* scanner.stopServer({ pid: 4242, port }); + expect(signal).toHaveBeenCalledExactlyOnceWith(4242, "SIGTERM"); + expect(stops).toEqual(scenario.stops); + }).pipe(Effect.scoped, Effect.provide(layer)); +}); + const AGENT_SERVER_SCRIPT = ` const server = require("node:http").createServer((_, response) => { response.writeHead(200, { "content-type": "text/html" }); diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index 6e87dcc89b..77fb19dc76 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -431,6 +431,15 @@ const parsePsEnvironmentThreads = ( return threads; }; +const parsePsCommandLines = (raw: string): ReadonlyMap => { + const lines = new Map(); + for (const line of raw.split("\n")) { + const match = /^\s*(\d+)\s(.*)$/.exec(line); + if (match) lines.set(Number(match[1]), match[2]!); + } + return lines; +}; + /** Splits `/proc//environ` on NUL, or the environment macOS `ps -E` appends on spaces. */ const parseEnvironmentVariables = ( raw: string, @@ -1167,19 +1176,36 @@ export const make = Effect.gen(function* PortDiscoveryMake() { ); return new Map(read.flatMap(Option.toArray)); } - const result = yield* processRunner - .run({ - command: "ps", - args: ["-E", "-ww", "-o", "pid=,command=", "-p", pids.join(",")], - timeout: Duration.millis(PS_TIMEOUT_MS), - maxOutputBytes: PS_MAX_OUTPUT_BYTES, - }) - .pipe(Effect.option); + const readCommandLines = (withEnvironment: boolean) => + processRunner + .run({ + command: "ps", + args: [ + ...(withEnvironment ? ["-E"] : []), + "-ww", + "-o", + "pid=,command=", + "-p", + pids.join(","), + ], + timeout: Duration.millis(PS_TIMEOUT_MS), + maxOutputBytes: PS_MAX_OUTPUT_BYTES, + }) + .pipe( + Effect.map((result) => parsePsCommandLines(result.stdout)), + Effect.orElseSucceed(() => new Map()), + ); + // `ps -E` prints the environment after the arguments, so the arguments alone are read + // separately and only what follows them counts as environment. + const [withEnvironment, argumentsOnly] = yield* Effect.all( + [readCommandLines(true), readCommandLines(false)], + { concurrency: 2 }, + ); const variables = new Map>(); - for (const line of Option.isSome(result) ? result.value.stdout.split("\n") : []) { - const match = /^\s*(\d+)\s(.*)$/.exec(line); - if (match) { - variables.set(Number(match[1]), parseEnvironmentVariables(match[2]!, /\s+/, names)); + for (const [pid, line] of withEnvironment) { + const commandLine = argumentsOnly.get(pid); + if (commandLine !== undefined && line.startsWith(commandLine)) { + variables.set(pid, parseEnvironmentVariables(line.slice(commandLine.length), /\s+/, names)); } } return variables; diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index cbfbe17796..82aa678443 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1214,6 +1214,45 @@ it.layer( }).pipe(Effect.provide(TestClock.layer())), ); + it.effect("backs off polling a steady command and still sees it exit within five seconds", () => + Effect.gen(function* () { + const shell = { pid: 9000, ppid: 1, name: "zsh" }; + let table = [shell, { pid: 200, ppid: 9000, name: "node" }]; + let queries = 0; + const { manager, ptyAdapter, getEvents } = yield* createManager(5, { + subprocessPollIntervalMs: 1_000, + processKillGraceMs: 0, + processTable: Effect.sync(() => { + queries += 1; + return table; + }), + }).pipe(Effect.provide(layerWithHostPlatform("linux"))); + const activity = Effect.map(getEvents, (events) => + events.flatMap((event) => + event.type === "activity" ? [event.hasRunningSubprocess ? event.label : null] : [], + ), + ); + yield* manager.open(openInput()); + + yield* TestClock.adjust("10 minutes"); + expect(yield* activity).toEqual(["node"]); + expect(queries).toBeGreaterThanOrEqual(115); + expect(queries).toBeLessThanOrEqual(125); + + table = [...table, { pid: 201, ppid: 200, name: "esbuild" }]; + ptyAdapter.processes[0]!.emitData("rebuilt\r\n"); + queries = 0; + yield* TestClock.adjust("1 second"); + expect(queries).toBe(1); + + yield* TestClock.adjust("1 minute"); + table = [shell]; + yield* TestClock.adjust("5 seconds"); + expect(yield* activity).toEqual(["node", null]); + yield* manager.close({ threadId: "thread-1" }); + }).pipe(Effect.provide(TestClock.layer())), + ); + // Answers process-table queries after `queryDuration`, honoring the caller's // timeout the way ProcessRunner's `timedOutResult` mode does. const slowProcessTable = ( diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 6470a7c62a..97fe8ec940 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -114,6 +114,8 @@ const PROCESS_TABLE_QUERY_TIMEOUT = "15 seconds"; const CLOSE_IDLE_QUERY_TIMEOUT = { posix: "1 second", win32: "1500 millis" } as const; // Discover children started without terminal input or output. const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30; +// Bounds how late a steady command's silent exit or new child is seen. +const STEADY_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 5; const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128; const DEFAULT_OPEN_COLS = 120; @@ -516,6 +518,7 @@ function terminalActivityMark(session: TerminalSessionState): number { interface QuietTerminalSession { readonly process: PtyAdapter.PtyProcess | null; readonly mark: number; + readonly processKey: string | null; readonly idleSnapshots: number; } @@ -3094,15 +3097,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func // Process identity prevents a restarted shell from inheriting quiet state. let quietSessions = new WeakMap(); let skippedQuietTicks = 0; - const isQuiet = (session: TerminalSessionState & { pid: number }) => { + const quietSnapshotEveryTicks = (session: TerminalSessionState & { pid: number }) => { const quiet = quietSessions.get(session); - return ( - quiet !== undefined && - quiet.idleSnapshots === 2 && - quiet.process === session.process && - quiet.mark === terminalActivityMark(session) && - !session.hasRunningSubprocess - ); + if ( + quiet === undefined || + quiet.idleSnapshots < 2 || + quiet.process !== session.process || + quiet.mark !== terminalActivityMark(session) + ) { + return 1; + } + return quiet.processKey === null + ? QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS + : STEADY_SUBPROCESS_SNAPSHOT_EVERY_TICKS; }; const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () { @@ -3122,10 +3129,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func if (runningSessions.length === 0) { return { snapshotSucceeded: true, queryElapsedMs: 0 }; } - if ( - runningSessions.every(({ session }) => isQuiet(session)) && - skippedQuietTicks < QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS - 1 - ) { + const snapshotEveryTicks = Math.min( + ...runningSessions.map(({ session }) => quietSnapshotEveryTicks(session)), + ); + if (skippedQuietTicks < snapshotEveryTicks - 1) { skippedQuietTicks += 1; return { snapshotSucceeded: true, queryElapsedMs: 0 }; } @@ -3217,9 +3224,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* publishEvent(event.value); } + const processKey = next.hasRunningSubprocess + ? `${nextChildLabel}:${next.processIds.toSorted((a, b) => a - b).join(",")}` + : null; if ( snapshotSucceeded && - !next.hasRunningSubprocess && session.status === "running" && session.pid === terminalPid && session.process === process && @@ -3228,7 +3237,13 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func quietSessions.set(session, { process, mark, - idleSnapshots: previous?.process === process && previous.mark === mark ? 2 : 1, + processKey, + idleSnapshots: + previous?.process === process && + previous.mark === mark && + previous.processKey === processKey + ? 2 + : 1, }); } }); diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 682e783337..b27f84bd90 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -74,8 +74,15 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { const tmp = yield* makeTempDir; const root = path.join(tmp, "wrapper"); const outside = path.join(tmp, "outside"); + // Labels are cut at 128 UTF-16 units; an emoji across the cut is left out whole. + const cut = `${"a".repeat(127)}🚀`; + const fits = `${"b".repeat(126)}🚀`; + const padded = `${" ".repeat(127)}🚀`; for (const folder of [ ".git", + `${cut}/.git`, + `${fits}/.git`, + `${padded}/.git`, "api/.git", "web/.git", "sub/.git", @@ -134,6 +141,14 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { source: "code-workspace", }, { path: outside, name: "outside", isGitRepository: true, source: "code-workspace" }, + { path: path.join(root, padded), name: "🚀", isGitRepository: true, source: "child" }, + { + path: path.join(root, cut), + name: "a".repeat(127), + isGitRepository: true, + source: "child", + }, + { path: path.join(root, fits), name: fits, isGitRepository: true, source: "child" }, // One level below a plain folder is looked into. { path: path.join(root, "src", "svc"), diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index c2a65f9b98..7d19e7524f 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -11,6 +11,7 @@ import { type WorkspaceScanFoldersResult, } from "@onicode/contracts"; import { expandHomePath } from "@onicode/provider-core/server/pathExpansion"; +import { splitsSurrogatePair } from "@onicode/shared/assistantCitations"; import * as HostProcess from "@onicode/shared/HostProcess"; import { fromLenientJson } from "@onicode/shared/schemaJson"; import { ONICODE_PROJECT_FILE_NAME } from "@onicode/contracts"; @@ -80,7 +81,11 @@ export class WorkspaceFolders extends Context.Service< const DETECTION_CONCURRENCY = 8; // What `ProjectTrackedFolder.name` allows. const FOLDER_NAME_MAX = 128; -const boundedName = (name: string) => name.slice(0, FOLDER_NAME_MAX).trim(); +const boundedName = (name: string) => { + const trimmed = name.trimStart(); + const end = splitsSurrogatePair(trimmed, FOLDER_NAME_MAX) ? FOLDER_NAME_MAX - 1 : FOLDER_NAME_MAX; + return trimmed.slice(0, end).trimEnd(); +}; const CODE_WORKSPACE_EXTENSION = ".code-workspace"; const decodeCodeWorkspace = Schema.decodeUnknownEffect( diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 0c7e4d800d..d57b271e7f 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -549,6 +549,24 @@ Third}`; expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design"); }); + it("hides ODS values kept in cells a merge covers", async () => { + const archive = new Map( + Object.entries({ + "content.xml": + '' + + 'Total2Lead' + + 'Q2' + + "", + }), + ); + const result = await openDocument(archive, "ods"); + if (result.type !== "ods") throw new Error("Expected workbook"); + expect(result.sheets[0]!.rows).toEqual([ + ["Total", "", "", "", "Lead"], + ["", "", "", "", "Q2"], + ]); + }); + it("reads an ODS time cell that has no display paragraph", async () => { const archive = new Map( Object.entries({ diff --git a/apps/web/src/components/files/PreviewImageContent.browser.test.tsx b/apps/web/src/components/files/PreviewImageContent.browser.test.tsx new file mode 100644 index 0000000000..f19eb0b2a9 --- /dev/null +++ b/apps/web/src/components/files/PreviewImageContent.browser.test.tsx @@ -0,0 +1,29 @@ +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; +import "~/index.css"; +import PreviewImageContent from "./PreviewImageContent"; + +function png(width: number, height: number) { + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas.toDataURL("image/png"); +} + +it("fits the image inside a pane with a fractional width", async () => { + const host = document.createElement("div"); + host.style.cssText = "display:flex;flex-direction:column;width:500.5px;height:600px"; + await using _screen = await render( + , + { container: host }, + ); + const image = host.querySelector("img")!; + const padding = 32; + + await vi.waitFor(() => { + const width = image.getBoundingClientRect().width + padding; + expect(width).toBeGreaterThan(499.5); + expect(width).toBeLessThanOrEqual(500.5); + }); +}); diff --git a/apps/web/src/components/files/PreviewImageContent.tsx b/apps/web/src/components/files/PreviewImageContent.tsx index 1a67025736..2bc25776d2 100644 --- a/apps/web/src/components/files/PreviewImageContent.tsx +++ b/apps/web/src/components/files/PreviewImageContent.tsx @@ -23,7 +23,15 @@ export default function PreviewImageContent(props: { useLayoutEffect(() => { const node = ref.current; if (!node) return; - const update = () => setViewport({ width: node.clientWidth, height: node.clientHeight }); + // clientWidth rounds a fractional pane size up, and an image fitted to it overflows the pane. + // The computed size keeps the fraction; it reads "auto" while an ancestor is display:none. + const update = () => { + const size = getComputedStyle(node); + setViewport({ + width: Math.floor(Number.parseFloat(size.width) || 0), + height: Math.floor(Number.parseFloat(size.height) || 0), + }); + }; update(); return observeResize(node, update); }, []); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 907bebe0c5..708f692c47 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -387,13 +387,15 @@ export async function openDocument( ["table:table-cell", "table:covered-table-cell"].includes(child.name), )) { const value = - find(cell, "text:p", "office:annotation").map(text).join("\n") || - cell.attrs["office:value"] || - cell.attrs["office:date-value"] || - cell.attrs["office:time-value"] || - cell.attrs["office:boolean-value"] || - cell.attrs["office:string-value"] || - ""; + cell.name === "table:covered-table-cell" + ? "" + : find(cell, "text:p", "office:annotation").map(text).join("\n") || + cell.attrs["office:value"] || + cell.attrs["office:date-value"] || + cell.attrs["office:time-value"] || + cell.attrs["office:boolean-value"] || + cell.attrs["office:string-value"] || + ""; const count = repeat( cell.attrs["table:number-columns-repeated"], TABLE_PREVIEW_MAX_COLUMNS + 1, diff --git a/apps/web/src/components/settings/EnvironmentsMap.tsx b/apps/web/src/components/settings/EnvironmentsMap.tsx index d90accb55a..161136026a 100644 --- a/apps/web/src/components/settings/EnvironmentsMap.tsx +++ b/apps/web/src/components/settings/EnvironmentsMap.tsx @@ -843,8 +843,8 @@ function FleetCanvas({ autoComplete="off" onChange={(event) => setQuery(event.target.value)} onKeyDown={(event) => { - if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Enter") { + if (event.nativeEvent.isComposing || event.keyCode === 229) return; event.preventDefault(); goToFirstMatch(); } else clearSearchOnEscape(event, query, () => setQuery("")); diff --git a/apps/web/src/components/settings/TextGeneratorsSettings.browser.test.tsx b/apps/web/src/components/settings/TextGeneratorsSettings.browser.test.tsx new file mode 100644 index 0000000000..434429dd13 --- /dev/null +++ b/apps/web/src/components/settings/TextGeneratorsSettings.browser.test.tsx @@ -0,0 +1,76 @@ +import { DEFAULT_SERVER_SETTINGS, EnvironmentId } from "@onicode/contracts"; +import { AsyncResult } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; +import "~/index.css"; + +import { act, render } from "../../../test/render"; +import { TextGeneratorsSettings } from "./TextGeneratorsSettings"; + +vi.mock("../../hooks/useSettings", async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironmentSettings: () => ({ + ...DEFAULT_SERVER_SETTINGS, + textGenerators: { + local: { + kind: "openaiCompatible", + baseUrl: "http://localhost:1234/v1", + apiKey: "", + enabled: true, + }, + }, + }), + useUpdateEnvironmentSettings: () => () => {}, +})); + +vi.mock("../../textGenerators", async (importOriginal) => ({ + ...(await importOriginal()), + useTextGeneratorModels: () => + AsyncResult.success( + Array.from({ length: 9 }, (_, index) => ({ id: `model-${index}`, name: `Model ${index}` })), + ), +})); + +it("clears the model search on Escape without closing the models dialog", async () => { + await using _screen = await render( + , + ); + await userEvent.click(page.getByRole("button", { name: "More actions for localhost:1234" })); + await userEvent.click(page.getByRole("menuitem", { name: "Show models" })); + const dialog = page.getByRole("dialog", { name: "localhost:1234 models" }); + const search = page.getByRole("searchbox", { name: "Search models" }); + await userEvent.fill(search, "model 1"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + search + .element() + .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true })); + }); + await expect.element(search).toHaveValue("model 1"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + await expect.element(search).toHaveFocus(); + await expect.element(search).toHaveAttribute("type", "text"); + // Holding Escape repeats the keydown, which must not also close the dialog. + await act(() => { + search + .element() + .dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true })); + }); + await expect.element(dialog).toBeInTheDocument(); + + await userEvent.keyboard("{Escape}"); + await expect.element(dialog).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/settings/TextGeneratorsSettings.tsx b/apps/web/src/components/settings/TextGeneratorsSettings.tsx index 604b3cad08..c26be6ce38 100644 --- a/apps/web/src/components/settings/TextGeneratorsSettings.tsx +++ b/apps/web/src/components/settings/TextGeneratorsSettings.tsx @@ -668,6 +668,7 @@ function TextGeneratorModelList({ { await expect.element(settings).not.toBeInTheDocument(); }); +it("clears the transcription model search on Esc without closing Settings", async () => { + const target = new PrimaryConnectionTarget({ + environmentId: EnvironmentId.make("voice-search-escape"), + label: "Test environment", + httpBaseUrl: window.location.origin, + wsBaseUrl: "ws://localhost", + }); + const prepared = { + ...target, + target, + socketUrl: target.wsBaseUrl, + httpAuthorization: { _tag: "Bearer" as const, token: "test-token" }, + }; + const model: EnvironmentSpeechModel = { + id: "tiny", + name: "Tiny", + description: "", + size: 100, + languages: ["en"], + accuracy: 1, + speed: 1, + recommended: true, + supportsStreaming: false, + supportsTranslation: false, + supportsLanguageDetection: false, + active: false, + state: "downloadable", + }; + const status = { + supported: true, + state: "missing-model", + modelId: model.id, + model: model.name, + size: model.size, + supportsStreaming: false, + supportsTranslation: false, + acceleration: "cpu", + benchmarkTier: "cpu", + modelUnloadTimeout: "never", + gpuDevices: [], + } satisfies EnvironmentSpeechStatus; + const fetch = globalThis.fetch; + using _network = vi.spyOn(globalThis, "fetch").mockImplementation((input, init) => { + const url = new URL(input instanceof Request ? input.url : input, window.location.href); + if (url.pathname === "/api/voice/status") return Promise.resolve(Response.json(status)); + if (url.pathname === "/api/voice/models") + return Promise.resolve(Response.json({ models: [model] })); + return fetch(input, init); + }); + await vi.mocked(useVoiceTranscriptionDestination).withImplementation( + () => ({ environmentId: target.environmentId, label: target.label, grantId: "test", prepared }), + async () => { + await using screen = await render( + + {}}> + + + , + { router: "/settings/voice" }, + ); + const settings = screen.getByRole("dialog", { name: "Settings" }); + const search = screen.getByRole("searchbox", { name: "Search transcription models" }); + await expect.element(search).toBeVisible(); + + await userEvent.fill(search, "tiny"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + search + .element() + .dispatchEvent( + new KeyboardEvent("keydown", { ...composition, bubbles: true, cancelable: true }), + ); + }); + await expect.element(search).toHaveValue("tiny"); + await expect.element(settings).toHaveAttribute("data-open"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + await expect.element(search).toHaveFocus(); + // Holding Escape repeats the keydown, which must not also close Settings. + await act(() => { + search.element().dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + repeat: true, + bubbles: true, + cancelable: true, + }), + ); + }); + await expect.element(settings).toHaveAttribute("data-open"); + + await userEvent.keyboard("{Escape}"); + await expect.element(settings).not.toBeInTheDocument(); + }, + ); +}); + it("records from the first connected microphone in the saved order", async () => { const previous = getClientSettings(); using cleanup = new DisposableStack(); diff --git a/apps/web/src/components/settings/searchFieldEscape.test.ts b/apps/web/src/components/settings/searchFieldEscape.test.ts index 879498d567..30c13407b3 100644 --- a/apps/web/src/components/settings/searchFieldEscape.test.ts +++ b/apps/web/src/components/settings/searchFieldEscape.test.ts @@ -3,7 +3,15 @@ import { describe, expect, it } from "vite-plus/test"; import { clearSearchOnEscape } from "./searchFieldEscape"; function press( - init: { key?: string; isComposing?: boolean; keyCode?: number; repeat?: boolean }, + init: { + key?: string; + isComposing?: boolean; + keyCode?: number; + repeat?: boolean; + defaultPrevented?: boolean; + shiftKey?: boolean; + metaKey?: boolean; + }, query: string, ) { const outcome = { prevented: false, stopped: false, cleared: false }; @@ -12,6 +20,11 @@ function press( key: init.key ?? "Escape", keyCode: init.keyCode ?? 27, repeat: init.repeat ?? false, + defaultPrevented: init.defaultPrevented ?? false, + altKey: false, + ctrlKey: false, + metaKey: init.metaKey ?? false, + shiftKey: init.shiftKey ?? false, nativeEvent: { isComposing: init.isComposing ?? false }, preventDefault: () => { outcome.prevented = true; @@ -38,10 +51,17 @@ describe("clearSearchOnEscape", () => { expect(press({ repeat: true }, "")).toEqual({ prevented: true, stopped: true, cleared: false }); }); - it("leaves the Esc that cancels an IME composition and other keys alone", () => { + it("lets the Esc that cancels an IME composition cancel it without closing the page", () => { + const kept = { prevented: false, stopped: true, cleared: false }; + expect(press({ isComposing: true }, "にほ")).toEqual(kept); + expect(press({ keyCode: 229 }, "")).toEqual(kept); + }); + + it("leaves modified, already handled and other keys alone", () => { const untouched = { prevented: false, stopped: false, cleared: false }; - expect(press({ isComposing: true }, "にほ")).toEqual(untouched); - expect(press({ keyCode: 229 }, "にほ")).toEqual(untouched); + expect(press({ shiftKey: true }, "mac")).toEqual(untouched); + expect(press({ metaKey: true }, "mac")).toEqual(untouched); + expect(press({ defaultPrevented: true }, "mac")).toEqual(untouched); expect(press({ key: "Enter", keyCode: 13 }, "mac")).toEqual(untouched); }); }); diff --git a/apps/web/src/components/settings/searchFieldEscape.ts b/apps/web/src/components/settings/searchFieldEscape.ts index 1a0257b643..4b342ef144 100644 --- a/apps/web/src/components/settings/searchFieldEscape.ts +++ b/apps/web/src/components/settings/searchFieldEscape.ts @@ -2,7 +2,16 @@ import type { KeyboardEvent } from "react"; type SearchFieldKeyDown = Pick< KeyboardEvent, - "key" | "keyCode" | "repeat" | "preventDefault" | "stopPropagation" + | "key" + | "keyCode" + | "repeat" + | "defaultPrevented" + | "altKey" + | "ctrlKey" + | "metaKey" + | "shiftKey" + | "preventDefault" + | "stopPropagation" > & { readonly nativeEvent: Pick }; /** @@ -15,10 +24,14 @@ export function clearSearchOnEscape( query: string, clear: () => void, ): void { - if (event.key !== "Escape" || event.nativeEvent.isComposing || event.keyCode === 229) return; + if (event.key !== "Escape" || event.defaultPrevented) return; + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return; + const composing = event.nativeEvent.isComposing || event.keyCode === 229; // A held Esc that just emptied the field must not go on to close the page. - if (query === "" && !event.repeat) return; - event.preventDefault(); + if (!composing && query === "" && !event.repeat) return; event.stopPropagation(); + // The Esc that cancels an IME composition belongs to the IME, not to the dialog around it. + if (composing) return; + event.preventDefault(); if (query !== "") clear(); } diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index ee8ff9c230..92cb3d770b 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4839,8 +4839,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr // OpenCode 2.2.5 answers its model list only once the scan has ended (observed, not documented). const skillsMentioned = Effect.fnUntraced(function* ( location: { readonly directory: string }, - mentions: ReadonlyArray, + text: string, ) { + const mentions = skillMentions(text); + if (mentions.length === 0) return []; const known = yield* listSkills(location); if (mentions.some((name) => !known.has(name))) { yield* readModels(location.directory); @@ -4949,8 +4951,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); } } - const mentions = skillMentions(text); - const skills = mentions.length === 0 ? [] : yield* skillsMentioned(location, mentions); + const skills = yield* skillsMentioned(location, text); const files = yield* promptFiles(turnInput.message.attachments); const messageText = turnInput.resume ? "" : yield* promptText(turnInput); if (!sending()) return; @@ -5302,7 +5303,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (turn.settledInbox.has(inboxID)) return; turn.steers.add(inboxID); state.strandedSteers.delete(inboxID); - const { files, messageText } = yield* Effect.gen(function* () { + const { files, messageText, skills } = yield* Effect.gen(function* () { const files = yield* promptFiles(steerInput.message.attachments); const messageText = (yield* providerMessageTextWithAttachmentPaths({ text: steerInput.message.text, @@ -5310,7 +5311,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr resolveAttachmentPath: host.resolveAttachmentPath, resolveExtractedTextPath: host.resolveExtractedTextPath, })).trim(); - return { files, messageText }; + const skills = yield* skillsMentioned( + { directory: directoryOf(turn.input.runtimePolicy.cwd) }, + steerInput.message.text, + ); + return { files, messageText, skills }; }).pipe( Effect.onInterrupt(() => lock.withPermit( @@ -5347,6 +5352,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr id: inboxID, text: messageText, ...(files.length === 0 ? {} : { files }), + ...(skills.length === 0 + ? {} + : { skills: skills.map((id) => ({ id: Skill.ID.make(id) })) }), delivery: "steer", }) .pipe( diff --git a/scripts/upstream-sync.ledger.tsv b/scripts/upstream-sync.ledger.tsv index e4623fed63..a96db4d9be 100644 --- a/scripts/upstream-sync.ledger.tsv +++ b/scripts/upstream-sync.ledger.tsv @@ -3723,3 +3723,15 @@ b6a04be41c take fix(antigravity): keep child skills visible under an uppercase S d7ae1e1791 take fix(web): report server rollback after an app update 43a0e74fb9 take fix(server): oni_thread_launch validates and normalizes modelSelection options f692811b95 take applied to apps/server/src/service, where Onicode keeps upstream's cloud/serviceSelectionLock +9842ca0c12 take fix(web): an image no longer jumps while its pane is resized +849d19447f take kept Onicode's clearSearchOnEscape helper over upstream's inline handler: upstream's new browser test passes against it, IME and held-Esc cases included (AppRouteModal already ignores a composing Esc); took the test with a Bearer authorization, which Onicode's voice requests need +3b829b6aa6 take kept Onicode's clearSearchOnEscape helper over upstream's inline handler (upstream's test passes against it); took enterKeyHint=search and the browser test +854f02bc2d take kept Onicode's conversationRuns fork-history boundary (also handles scheduled fresh sessions) over upstream's turnItemsSinceContextBoundary; merge-back delta now bounded via conversationRuns, with a ThreadFork test that fails on main; MCP app notes boundary SQL mirrors Onicode's startedFreshRun and first-prompt scheduledRunIds and uses the (run_id, ordinal) index instead of upstream's OR on messageId; dropped upstream's two ContextHandoffService tests, covered by existing fresh-fork and steered-schedule cases +a1ed691d8a take perf(server): terminals running a steady command stop polling the process table every second +354d9f1675 take fix(server): keep discovered workspace folder labels valid when an emoji crosses the name limit +fc92aefd26 take adopted upstream's acquireUseRelease over Onicode's onError + timeout closeCard: recording the pending card becomes uninterruptible, so an abort right after it opens still closes it; same behavior otherwise +00070b8031 skip kept Onicode's writeProjectSettings (beforeCommit): already saves create/update actions to the Settings overrides, plus model, env mode and auto-pull; it writes before the commit so a refused settings write commits nothing and its retry writes again, where upstream's onCommitted would leave a committed command with unsaved actions that a replayed retry never saves; covered by 'project defaults reach new threads…' and 'a refused settings write commits nothing…' +9bce8843de take taken as is +4f1dc5db12 take taken as is +26c21a86cf take taken as is +94190c63f9 take taken as is