Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions apps/desktop/src/snapShot/DesktopSnapShot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
11 changes: 8 additions & 3 deletions apps/desktop/src/snapShot/DesktopSnapShot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,9 +262,14 @@ export class DesktopSnapShotSetupError extends Schema.TaggedError<DesktopSnapSho
if (this.action === "preview-config" || this.action === "apply-config") {
if (this.reason === "unsupported-session")
return "Config setup requires a Niri or Hyprland session.";
return this.action === "preview-config"
? "Couldn't prepare your capture shortcut changes."
: "Couldn't save your capture shortcut.";
const summary =
this.action === "preview-config"
? "Couldn't prepare your capture shortcut changes."
: "Couldn't save your capture shortcut.";
// Only the message crosses IPC, and the config steps throw the reason the user needs.
return this.cause instanceof Error && this.cause.message
? `${summary} ${this.cause.message}`
: summary;
}
const kde = this.action === "install-kde-helper" || this.action === "remove-kde-helper";
const hyprland =
Expand Down
103 changes: 98 additions & 5 deletions apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
TurnItemId,
} from "@onicode/contracts";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -1343,7 +1344,11 @@ it("requestSecret saves a pasted value to a file without opening a card", async
it("requestSecret returns the unsaved note for a declined, cancelled or timed-out card", async () => {
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 {
Expand Down Expand Up @@ -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"],
},
]);
});

Expand Down Expand Up @@ -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<string> = [];
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<void>();
const release = yield* Deferred.make<void>();
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<ThreadManagementService.ThreadManagementService["Service"]>),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({
getProviders: Effect.succeed([]),
} satisfies Partial<ProviderRegistry.ProviderRegistry["Service"]>),
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;
Expand Down
90 changes: 46 additions & 44 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
49 changes: 49 additions & 0 deletions apps/server/src/mcpApps/McpAppModelContext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
);
}),
);
});
29 changes: 28 additions & 1 deletion apps/server/src/mcpApps/McpAppModelContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<McpAppModelContextEntry>`
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
Expand All @@ -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));
});
Expand Down
Loading