+
ref={scrollRef}
data={items}
@@ -216,6 +217,7 @@ export function FontFamilyPicker({
onScroll={handleMetricsChange}
onLayout={handleMetricsChange}
onReady={handleMetricsChange}
+ className="min-h-0"
style={{ height: listHeight }}
/>
diff --git a/apps/web/src/components/settings/SecretsSettings.logic.test.ts b/apps/web/src/components/settings/SecretsSettings.logic.test.ts
index f4e820481cfad..01dffa4909543 100644
--- a/apps/web/src/components/settings/SecretsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/SecretsSettings.logic.test.ts
@@ -29,7 +29,7 @@ const settings = Schema.decodeSync(ServerSettings)({
hub: { kind: "cliproxy", url: "https://hub.test", managementKey: personal("op://hub") },
},
easDeviceHosts: [
- { kind: "eas", id: "eas", label: "EAS Simulator", accessToken: personal("op://expo") },
+ { kind: "eas", id: "eas", label: "Expo Simulators", accessToken: personal("op://expo") },
],
simlockDeviceHosts: [
{
@@ -51,7 +51,7 @@ it.each([
"Codex · CODEX_TOKEN",
"GitHub · github.com",
"https://hub.test · Management Key",
- "EAS Simulator · Access Token",
+ "Expo Simulators · Access Token",
"Simlock Pool · Agent Token",
"Voice · OpenAI",
],
diff --git a/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx b/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
index 6ac9219ab2828..a701039f374ef 100644
--- a/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
+++ b/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
@@ -7,6 +7,7 @@ import { useState } from "react";
import { AsyncResult } from "effect/reactivity";
import { APP_VERSION } from "~/branding";
+import { isLocalEnvironmentDisabled } from "~/localEnvironment";
import { useDesktopUpdateState } from "~/state/desktopUpdate";
import { useEnvironments } from "~/state/environments";
import { npmReleaseAtom, npmReleaseFailureMessage } from "~/state/npmRelease";
@@ -104,6 +105,7 @@ function SwitchPlan({
databaseMigration: environment.serverConfig?.environment.databaseMigration,
})),
window.desktopBridge?.getLocalEnvironmentBootstraps().length ?? 0,
+ !isLocalEnvironmentDisabled(),
);
const run = async () => {
diff --git a/apps/web/src/components/settings/easDeviceHostsSettings.logic.test.ts b/apps/web/src/components/settings/easDeviceHostsSettings.logic.test.ts
index c3105b115e21f..d4a68d10dabbb 100644
--- a/apps/web/src/components/settings/easDeviceHostsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/easDeviceHostsSettings.logic.test.ts
@@ -7,8 +7,8 @@ import {
updateEasDeviceHosts,
} from "./easDeviceHostsSettings.logic";
-describe("EAS device host settings", () => {
- it("rejects limits EAS does not allow", () => {
+describe("Expo device host settings", () => {
+ it("rejects limits Expo does not allow", () => {
expect(Option.isSome(parseEasDeviceHostDraft(newEasDeviceHost("eas")))).toBe(true);
expect(
Option.isNone(parseEasDeviceHostDraft({ ...newEasDeviceHost("eas"), maxSessionMinutes: 10 })),
diff --git a/apps/web/src/components/settings/easDeviceHostsSettings.logic.ts b/apps/web/src/components/settings/easDeviceHostsSettings.logic.ts
index d91fe45bb9205..1657560fd8adc 100644
--- a/apps/web/src/components/settings/easDeviceHostsSettings.logic.ts
+++ b/apps/web/src/components/settings/easDeviceHostsSettings.logic.ts
@@ -9,14 +9,14 @@ export const parseEasDeviceHostDraft = Schema.decodeUnknownOption(EasDeviceHostC
export const newEasDeviceHost = (id: string): EasDeviceHostConfigType => ({
kind: "eas",
id,
- label: "EAS Simulator",
+ label: "Expo Simulators",
accessToken: "",
maxSessionMinutes: 30,
idleMinutes: 10,
maxConcurrentSessions: 2,
});
-/** Adds, replaces, or removes one EAS host. */
+/** Adds, replaces, or removes one Expo host. */
/**
* With `keepToken`, the environment keeps the token it holds: a saved token arrives redacted, and
* one environment's token says nothing about another's. One new to the host uses its own Expo login.
diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx
index 3956ab622c46b..2a3893737c0b0 100644
--- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx
+++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx
@@ -638,7 +638,7 @@ function ThreadRenameInput(props: {
}}
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
- className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground"
+ className="-mx-1 min-w-0 flex-1 rounded-sm bg-card px-1 text-sm font-medium text-card-foreground outline-none ring-1 ring-inset ring-input focus:ring-foreground"
/>
);
}
@@ -1231,7 +1231,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
sortable?.isDragging && "relative z-20",
)}
>
-
+
-
+
{
const nightly = "0.1.4-nightly.20261027.3796";
const windows = { connected: true, databaseMigration: 69 };
- expect(localSwitchBlockReason(nightly, stable, [windows], 1)).toBeNull();
+ expect(localSwitchBlockReason(nightly, stable, [windows], 1, true)).toBeNull();
// A WSL server's newer migration blocks the reinstall that would restart it.
expect(
localSwitchBlockReason(
@@ -262,17 +262,29 @@ describe("localSwitchBlockReason", () => {
stable,
[windows, { connected: true, databaseMigration: 72 }],
2,
+ true,
),
).toContain("does not support yet");
// A WSL backend still starting has no client entry, so its database is unchecked.
- expect(localSwitchBlockReason(nightly, stable, [windows], 2)).toBe(
+ expect(localSwitchBlockReason(nightly, stable, [windows], 2, true)).toBe(
"its server is not connected, so its database cannot be checked",
);
// A cached head from a disconnected server proves nothing.
expect(
- localSwitchBlockReason(nightly, stable, [{ connected: false, databaseMigration: 69 }], 1),
+ localSwitchBlockReason(
+ nightly,
+ stable,
+ [{ connected: false, databaseMigration: 69 }],
+ 1,
+ true,
+ ),
).toBe("its server is not connected, so its database cannot be checked");
- expect(localSwitchBlockReason("0.1.3", stable, [], 1)).toBeNull();
+ expect(localSwitchBlockReason("0.1.3", stable, [], 1, true)).toBeNull();
+ // A primary backend still starting has no entry or bootstrap yet, unless Local environment is off.
+ expect(localSwitchBlockReason(nightly, stable, [], 0, true)).toBe(
+ "its server is not connected, so its database cannot be checked",
+ );
+ expect(localSwitchBlockReason(nightly, stable, [], 0, false)).toBeNull();
});
});
diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts
index bc26ca9b46083..a95a06084a320 100644
--- a/apps/web/src/components/sidebar/updateEverything.logic.ts
+++ b/apps/web/src/components/sidebar/updateEverything.logic.ts
@@ -176,7 +176,8 @@ function channelSwitchBlockReason(
/** This app's reinstall restarts every server it hosts, so each of their databases must allow the
* switch. `backendCount` is the desktop's own inventory: a backend still starting has no client
- * entry yet. A cached config can outlive its connection, so only a connected server's head counts. */
+ * entry yet. A cached config can outlive its connection, so only a connected server's head counts.
+ * With Local environment off this app runs no server, so its reinstall restarts none. */
export function localSwitchBlockReason(
appVersion: string,
release: ChannelSwitchRelease,
@@ -185,8 +186,9 @@ export function localSwitchBlockReason(
readonly databaseMigration: number | undefined;
}>,
backendCount: number,
+ localEnvironmentEnabled: boolean,
): string | null {
- if (!crossesTrack(appVersion, release)) return null;
+ if (!localEnvironmentEnabled || !crossesTrack(appVersion, release)) return null;
if (
hosted.length === 0 ||
hosted.length < backendCount ||
diff --git a/apps/web/src/components/ui/middle-truncate.browser.test.tsx b/apps/web/src/components/ui/middle-truncate.browser.test.tsx
index 3fbf36523254b..91de6b169f64f 100644
--- a/apps/web/src/components/ui/middle-truncate.browser.test.tsx
+++ b/apps/web/src/components/ui/middle-truncate.browser.test.tsx
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vite-plus/test";
+import { describe, expect, it, vi } from "vite-plus/test";
import { render } from "../../../test/render";
import { MiddleTruncate } from "./middle-truncate";
@@ -24,6 +24,24 @@ describe("MiddleTruncate", () => {
expect(label()).toHaveStyle({ clipPath: "none" });
});
+ it("fits every head mounted in the same commit", async () => {
+ const values = ["t3/investigate-release-build-times", "t3/remove-stale-worktree-branches"];
+ await using screen = await render(
+ <>
+ {values.map((value) => (
+ {narrow(value)}
+ ))}
+ >,
+ );
+ const heads = () => [
+ ...screen.container.querySelectorAll("[title] > span:first-child"),
+ ];
+
+ await vi.waitFor(() =>
+ expect(heads().filter((head) => head.hasAttribute("data-overflow"))).toHaveLength(2),
+ );
+ });
+
it.each([
["Fix the sidebar", 7],
["report\u2003\u2003draft.txt", 9],
diff --git a/apps/web/src/components/ui/middle-truncate.tsx b/apps/web/src/components/ui/middle-truncate.tsx
index faf8ab6b3f397..a5213209f0ed6 100644
--- a/apps/web/src/components/ui/middle-truncate.tsx
+++ b/apps/web/src/components/ui/middle-truncate.tsx
@@ -25,8 +25,8 @@ export function MiddleTruncate({
const element = headRef.current;
// A new head can keep the same box size, so refit here, not only on resize.
if (!element || head === undefined) return;
- fitHead(element);
- return observeResize(element, () => fitHead(element));
+ scheduleFit(element);
+ return observeResize(element, () => scheduleFit(element));
}, [head]);
return (
();
+
+function scheduleFit(head: HTMLElement) {
+ if (pendingFits.size === 0) queueMicrotask(fitPendingHeads);
+ pendingFits.add(head);
+}
+
// An overflowing head is cut after its last whole character: clip the partial glyph
// and slide the tail left over the slack. Neither changes layout, so the observed
// size stays the true available width.
+function fitPendingHeads() {
+ const heads = [...pendingFits].filter((head) => head.isConnected);
+ pendingFits.clear();
+ const overflowing = heads.map(
+ (head) => head.scrollWidth > head.clientWidth && head.firstChild instanceof Text,
+ );
+ heads.forEach((head, index) => head.toggleAttribute("data-overflow", overflowing[index]));
+ const slacks = heads.map((head, index) => (overflowing[index] ? measureSlack(head) : 0));
+ heads.forEach((head, index) => {
+ const slack = slacks[index]!;
+ head.style.clipPath = slack > 0 ? `inset(-0.25em ${slack}px -0.25em 0)` : "";
+ const tail = head.nextElementSibling;
+ if (tail instanceof HTMLElement) tail.style.translate = slack > 0 ? `-${slack}px 0` : "";
+ });
+}
-function fitHead(head: HTMLElement) {
- const text = head.firstChild;
- const overflowing = head.scrollWidth > head.clientWidth && text instanceof Text;
- head.toggleAttribute("data-overflow", overflowing);
- let slack = 0;
- if (overflowing) {
- const range = document.createRange();
- const left = head.getBoundingClientRect().left;
- const widthTo = (end: number) => {
- range.setStart(text, 0);
- range.setEnd(text, end);
- return range.getBoundingClientRect().right - left;
- };
- let fits = 0;
- let over = text.length;
- while (over - fits > 1) {
- const mid = (fits + over) >> 1;
- if (widthTo(mid) <= head.clientWidth) fits = mid;
- else over = mid;
- }
- if (/[\uD800-\uDBFF]/.test(text.data[fits - 1] ?? "")) fits -= 1;
- slack = Math.max(0, head.clientWidth - widthTo(fits));
+function measureSlack(head: HTMLElement) {
+ const text = head.firstChild as Text;
+ const range = document.createRange();
+ const left = head.getBoundingClientRect().left;
+ const width = head.clientWidth;
+ const widthTo = (end: number) => {
+ range.setStart(text, 0);
+ range.setEnd(text, end);
+ return range.getBoundingClientRect().right - left;
+ };
+ let fits = 0;
+ let over = text.length;
+ while (over - fits > 1) {
+ const mid = (fits + over) >> 1;
+ if (widthTo(mid) <= width) fits = mid;
+ else over = mid;
}
- head.style.clipPath = slack > 0 ? `inset(-0.25em ${slack}px -0.25em 0)` : "";
- const tail = head.nextElementSibling;
- if (tail instanceof HTMLElement) tail.style.translate = slack > 0 ? `-${slack}px 0` : "";
+ if (/[\uD800-\uDBFF]/.test(text.data[fits - 1] ?? "")) fits -= 1;
+ return Math.max(0, width - widthTo(fits));
}
// The segments render pre so the space at the cut survives, so collapse here what CSS
diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsx
index ecbf7a6667062..005654db7bdd7 100644
--- a/apps/web/src/components/ui/popover.tsx
+++ b/apps/web/src/components/ui/popover.tsx
@@ -97,7 +97,7 @@ function PopoverPopup({
// Electron drag hit-testing ignores z-index; popups over a drag region would swallow hover.
"[-webkit-app-region:no-drag]",
tooltipStyle &&
- "w-fit text-balance rounded-md text-xs shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]",
+ "w-fit rounded-md text-xs shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]",
!tooltipStyle &&
variant !== "panel" &&
"shadow-[0_16px_40px_-18px_rgb(0_0_0/55%)] dark:shadow-[0_18px_44px_-18px_rgb(0_0_0/80%)]",
diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx
index 614943364b1e1..577aa48da87fa 100644
--- a/apps/web/src/components/ui/tooltip.tsx
+++ b/apps/web/src/components/ui/tooltip.tsx
@@ -140,7 +140,7 @@ function TooltipPopup({
{
);
});
+ it("reopens without an empty line between the quote and the comment", () => {
+ const { doc, map } = serialize(quote("quoted"), paragraph("Comment to it"));
+ const reopened = ProseMirrorNode.fromJSON(
+ schema,
+ buildDocJson(map.value, (name) => ({ label: name, description: null })),
+ );
+ expect(reopened.toJSON()).toEqual(doc.toJSON());
+ });
+
it("settles on the blank line when a draft glued it to the quote", () => {
const settled = "before\n> quoted\n\nafter";
expect(roundTrip("before\n> quoted\nafter").value).toBe(settled);
diff --git a/apps/web/src/composer-rich-text-doc.ts b/apps/web/src/composer-rich-text-doc.ts
index dfd238e71819c..d8f0a7e7b6e5e 100644
--- a/apps/web/src/composer-rich-text-doc.ts
+++ b/apps/web/src/composer-rich-text-doc.ts
@@ -1077,7 +1077,12 @@ export function buildTiptapContent(
});
openQuote = null;
};
- for (const entry of entries) {
+ const isProseLine = (entry: (typeof entries)[number] | undefined, empty: boolean) =>
+ entry !== undefined &&
+ "line" in entry &&
+ !entry.line.list &&
+ (entry.line.inline.length === 0) === empty;
+ for (const [entryIndex, entry] of entries.entries()) {
if ("quote" in entry) {
flushLists();
if (openQuote && openQuote.prefix !== entry.quote.prefix) flushQuote();
@@ -1085,7 +1090,11 @@ export function buildTiptapContent(
openQuote.content.push(entry.quote.inline);
continue;
}
+ // The serializer separates a quote from the prose after it with one blank line; it is not an empty paragraph.
+ const quoteSeparator =
+ openQuote !== null && isProseLine(entry, true) && isProseLine(entries[entryIndex + 1], false);
flushQuote();
+ if (quoteSeparator) continue;
if ("code" in entry) {
flushLists();
blocks.push(entry.code);
diff --git a/apps/web/src/diffFileActions.test.ts b/apps/web/src/diffFileActions.test.ts
index f7faf72ef8bd3..8f7b2bc597b79 100644
--- a/apps/web/src/diffFileActions.test.ts
+++ b/apps/web/src/diffFileActions.test.ts
@@ -45,15 +45,39 @@ describe("openDiffFilePrimaryAction", () => {
).toBe("frontend/Dockerfile");
});
- it("handles Windows roots and mixed diff separators", () => {
- expect(
- resolveDiffPathForWorkspace({
- filePath: "Frontend/src\\index.ts",
- workspaceRoot: "C:\\repo\\frontend",
- repositoryRoot: "C:\\repo",
- }),
- ).toBe("src/index.ts");
- });
+ it.each([
+ {
+ filePath: "Frontend/src\\index.ts",
+ workspaceRoot: "C:\\repo\\frontend",
+ repositoryRoot: "C:\\repo",
+ expected: "src/index.ts",
+ },
+ {
+ filePath: "Frontend\\src\\index.ts",
+ workspaceRoot: "C:\\repo\\frontend",
+ repositoryRoot: "C:\\repo",
+ expected: "src/index.ts",
+ },
+ {
+ filePath: "frontend/back\\slash.txt",
+ workspaceRoot: "/repo/frontend",
+ repositoryRoot: "/repo",
+ expected: "back\\slash.txt",
+ },
+ {
+ filePath: "back/slash/a.ts",
+ workspaceRoot: "/repo/back\\slash",
+ repositoryRoot: "/repo",
+ expected: null,
+ },
+ ])(
+ "resolves $filePath in $workspaceRoot",
+ ({ filePath, workspaceRoot, repositoryRoot, expected }) => {
+ expect(resolveDiffPathForWorkspace({ filePath, workspaceRoot, repositoryRoot })).toBe(
+ expected,
+ );
+ },
+ );
// regression: #6174 opening diff files broke for repositories at a filesystem root
it.each([
@@ -89,6 +113,7 @@ describe("openDiffFilePrimaryAction", () => {
"backend/server.ts",
"frontend2/app.ts",
"frontend/../secret.ts",
+ "frontend/..\\secret.ts",
"C:secret.ts",
"/repo/backend/server.ts",
"/repo/frontend/../backend/server.ts",
diff --git a/apps/web/src/diffFileActions.ts b/apps/web/src/diffFileActions.ts
index c6a3fa3d436fc..046baa4ce5b64 100644
--- a/apps/web/src/diffFileActions.ts
+++ b/apps/web/src/diffFileActions.ts
@@ -17,16 +17,22 @@ interface OpenDiffFilePrimaryActionInput {
readonly openInEditor: (targetPath: string) => void;
}
-function normalizedRelativePathSegments(filePath: string): ReadonlyArray | null {
+function normalizedRelativePathSegments(
+ filePath: string,
+ windowsRoot: boolean,
+): ReadonlyArray | null {
if (filePath.startsWith("/") || isWindowsAbsolutePath(filePath) || /^[a-zA-Z]:/.test(filePath)) {
return null;
}
- const segments = filePath
- .replaceAll("\\", "/")
- .split("/")
- .filter((segment) => segment.length > 0 && segment !== ".");
- if (segments.length === 0 || segments.includes("..")) return null;
+ // On POSIX a backslash is part of a file name; Windows treats it as a separator
+ // (tool-call patches can name files with either), so reject ".." either way.
+ const parts = filePath.split(/[\\/]/);
+ if (parts.includes("..")) return null;
+ const segments = (windowsRoot ? parts : filePath.split("/")).filter(
+ (segment) => segment.length > 0 && segment !== ".",
+ );
+ if (segments.length === 0) return null;
return segments;
}
@@ -40,16 +46,13 @@ function repositoryRelativeWorkspaceSegments(
const normalizedRepositoryRoot = normalizeProjectPathForComparison(repositoryRoot);
if (normalizedWorkspaceRoot === normalizedRepositoryRoot) return [];
- const separator = normalizedRepositoryRoot.includes("\\") ? "\\" : "/";
+ const separator = isWindowsAbsolutePath(normalizedRepositoryRoot) ? "\\" : "/";
const repositoryPrefix = normalizedRepositoryRoot.endsWith(separator)
? normalizedRepositoryRoot
: `${normalizedRepositoryRoot}${separator}`;
if (!normalizedWorkspaceRoot.startsWith(repositoryPrefix)) return null;
- return normalizedWorkspaceRoot
- .slice(repositoryPrefix.length)
- .split(/[\\/]+/)
- .filter(Boolean);
+ return normalizedWorkspaceRoot.slice(repositoryPrefix.length).split(separator).filter(Boolean);
}
export function resolveDiffPathForWorkspace(input: {
@@ -57,14 +60,18 @@ export function resolveDiffPathForWorkspace(input: {
readonly workspaceRoot: string | undefined;
readonly repositoryRoot: string | undefined;
}): string | null {
+ const windowsRoot = [input.workspaceRoot, input.repositoryRoot].some(
+ (root) => root !== undefined && isWindowsAbsolutePath(root),
+ );
// Claude and ACP tool-call diffs name files by absolute path.
if (isAbsolutePath(input.filePath)) {
const relativePath = workspaceRelativeFilePath(input.filePath, input.workspaceRoot);
- const segments = relativePath === null ? null : normalizedRelativePathSegments(relativePath);
+ const segments =
+ relativePath === null ? null : normalizedRelativePathSegments(relativePath, windowsRoot);
return segments ? segments.join("/") : null;
}
- const fileSegments = normalizedRelativePathSegments(input.filePath);
+ const fileSegments = normalizedRelativePathSegments(input.filePath, windowsRoot);
if (!fileSegments) return null;
const workspaceSegments = repositoryRelativeWorkspaceSegments(
diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx b/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx
index 9b1299aee1dea..8513f18f35ac2 100644
--- a/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx
+++ b/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx
@@ -24,6 +24,11 @@ vi.mock("../previewStateStore", () => ({
beginPreviewSessionClose: () => {},
cancelPreviewSessionClose: () => {},
}));
+vi.mock("../browser/previewRuntime", () => ({ rendersServerTabNatively: () => false }));
+vi.mock("../state/primaryEnvironment", async () => {
+ const { Atom } = await import("effect/reactivity");
+ return { primaryEnvironmentIdAtom: Atom.make(null) };
+});
vi.mock("../state/session", () => ({
useEnvironmentScope: (id: string) => fixture.allowed.has(id),
readEnvironmentScope: (id: string) => fixture.allowed.has(id),
diff --git a/apps/web/src/hooks/useThreadActions.permissions.test.ts b/apps/web/src/hooks/useThreadActions.permissions.test.ts
index d1a74e4e894fb..c15dc90bb11f3 100644
--- a/apps/web/src/hooks/useThreadActions.permissions.test.ts
+++ b/apps/web/src/hooks/useThreadActions.permissions.test.ts
@@ -142,6 +142,7 @@ vi.mock("../state/entities", () => ({
.filter((thread) => thread.environmentId === environmentId)
.map((thread) => ({ environmentId, threadId: thread.id })),
readProject: () => ({ workspaceRoot: "/project" }),
+ readDelegatedUnderParent: () => new Set(),
}));
vi.mock("../components/Sidebar.logic", () => ({
getFallbackThreadIdAfterDelete: () => null,
diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts
index 6a8ce92af5e38..9c5ae260923cd 100644
--- a/apps/web/src/hooks/useThreadActions.ts
+++ b/apps/web/src/hooks/useThreadActions.ts
@@ -38,6 +38,7 @@ import { releaseComposerDraftUploads } from "../lib/composerDraftUploads";
import { announce } from "../lib/announce";
import { readLocalApi } from "../localApi";
import {
+ readDelegatedUnderParent,
readEnvironmentServerConfigLoaded,
readEnvironmentSupportsAutoSettleOptOut,
readEnvironmentThreadRefs,
@@ -593,6 +594,7 @@ export function useThreadActions() {
deletedThreadIds,
sortOrder: sidebarThreadSortOrder,
now: new Date().toISOString(),
+ delegatedUnderParent: readDelegatedUnderParent(),
});
let navigatedDuringDelete = false;
// The missing-thread redirect and the index draft replace this entry; any other history
diff --git a/apps/web/src/previewStateStore.test.ts b/apps/web/src/previewStateStore.test.ts
index 6554dde5f1c25..d72139d374373 100644
--- a/apps/web/src/previewStateStore.test.ts
+++ b/apps/web/src/previewStateStore.test.ts
@@ -208,9 +208,13 @@ describe("previewStateStore (single-tab)", () => {
...loaded,
navStatus: { ...loaded.navStatus, url: "https://example.com/next" },
});
+ const dialog = { type: "confirm", message: "Delete it?", defaultValue: "" };
+ applyPreviewDesktopState(ref, snapshot.tabId, { ...loaded, dialog });
+ applyPreviewDesktopState(ref, snapshot.tabId, { ...loaded, dialog: { ...dialog } });
+ applyPreviewDesktopState(ref, snapshot.tabId, loaded);
unsubscribe();
- expect(updateCount).toBe(3);
+ expect(updateCount).toBe(5);
});
it("retains multiple tabs and switches active desktop state", () => {
diff --git a/apps/web/src/previewStateStore.ts b/apps/web/src/previewStateStore.ts
index 6e190e8069ee5..9d1ece685b45d 100644
--- a/apps/web/src/previewStateStore.ts
+++ b/apps/web/src/previewStateStore.ts
@@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import {
type DesktopPreviewColorScheme,
+ type DesktopPreviewDialog,
type DesktopPreviewFavicon,
type PreviewEvent,
type PreviewListResult,
@@ -25,6 +26,7 @@ export interface DesktopPreviewOverlay {
audioMuted: boolean;
audible: boolean;
controller: "human" | "agent" | "none";
+ dialog?: DesktopPreviewDialog;
favicon: DesktopPreviewFavicon | null;
}
@@ -410,6 +412,9 @@ function isPreviewStateEqual(
previous.audioMuted === next.audioMuted &&
previous.audible === next.audible &&
previous.controller === next.controller &&
+ previous.dialog?.type === next.dialog?.type &&
+ previous.dialog?.message === next.dialog?.message &&
+ previous.dialog?.defaultValue === next.dialog?.defaultValue &&
previous.favicon?.dataUrl === next.favicon?.dataUrl &&
previous.favicon?.pageUrl === next.favicon?.pageUrl &&
previous.favicon?.capturedAt === next.favicon?.capturedAt)
diff --git a/apps/web/src/state/device.ts b/apps/web/src/state/device.ts
index ee43428f740f5..b4e4923ddc719 100644
--- a/apps/web/src/state/device.ts
+++ b/apps/web/src/state/device.ts
@@ -169,7 +169,7 @@ export const NO_DEVICE_PROBE_ATOM = Atom.make(AsyncResult.initial()
);
/**
- * The Expo account an EAS host editor shows as it opens, for the saved
+ * The Expo account an Expo host editor shows as it opens, for the saved
* credential. Each open checks again; edits and manual checks use the command.
*/
export const deviceEasAccountCheck = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, {
diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts
index 0cb7bbc600937..27168e1ce7893 100644
--- a/apps/web/src/state/entities.ts
+++ b/apps/web/src/state/entities.ts
@@ -385,6 +385,10 @@ export function readThreadShells(): ReadonlyArray {
return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
}
+export function readDelegatedUnderParent(): ReadonlySet {
+ return appAtomRegistry.get(environmentThreadShells.delegatedUnderParentAtom);
+}
+
function shellParentThreadId(
thread: Pick,
): ThreadId | null {
diff --git a/apps/web/src/themePalette.test.ts b/apps/web/src/themePalette.test.ts
index daa6962ee6371..dbe2b320e1e09 100644
--- a/apps/web/src/themePalette.test.ts
+++ b/apps/web/src/themePalette.test.ts
@@ -3,10 +3,13 @@ import { converter } from "culori/fn";
import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";
import { CONTEXT_CHIP_ACCENTS, contextChipColorVariable } from "./lib/contextChipAccents";
+import { appAtomRegistry } from "./rpc/atomRegistry";
import {
applyThemePalette,
+ canonicalThemePreference,
contextChipVariables,
+ getThemeDefinition,
getThemeColorsForMode,
getThemeModes,
getCustomThemes,
@@ -15,6 +18,8 @@ import {
invalidateCustomThemes,
installCustomTheme,
parseThemeFile,
+ parseThemeHalves,
+ publishedThemeDefinitions,
removeCustomTheme,
replaceCustomThemeCollection,
resolveDesktopTheme,
@@ -704,7 +709,7 @@ describe("context chip colors", () => {
});
describe("stored theme preferences", () => {
- it("lets a configured half unlock an appearance the base theme lacks", () => {
+ it("lets built-in and published halves unlock an appearance the base theme lacks", () => {
const lightOnly = parseThemeFile({
version: THEME_FILE_VERSION,
id: "paper",
@@ -712,6 +717,17 @@ describe("stored theme preferences", () => {
appearance: "light",
colors: { canvas: "#f8fbff" },
});
+ const [publishedTheme] = publishedThemeDefinitions([
+ {
+ id: "constructor",
+ name: "Constructor",
+ appearance: "dark",
+ canvas: "#1a1b26",
+ accent: "#7aa2f7",
+ },
+ ]);
+ expect(publishedTheme).toBeDefined();
+ using _environmentThemes = vi.spyOn(appAtomRegistry, "get").mockReturnValue([publishedTheme]);
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) =>
@@ -725,6 +741,12 @@ describe("stored theme preferences", () => {
expect(resolveThemeAppearance("paper", true, true, undefined, halves)).toBe("dark");
expect(resolveThemeAppearance("paper", false, false, "dark", halves)).toBe("dark");
expect(resolveDesktopTheme("paper", true, undefined, halves)).toBe("system");
+
+ expect(getThemeDefinition("constructor")).toEqual(publishedTheme);
+ expect(canonicalThemePreference("constructor")).toBe("constructor");
+ const publishedHalves = parseThemeHalves(JSON.stringify({ dark: "constructor" }));
+ expect(publishedHalves).toEqual({ dark: "constructor" });
+ expect(resolveThemeAppearance("paper", true, true, undefined, publishedHalves)).toBe("dark");
} finally {
vi.unstubAllGlobals();
invalidateCustomThemes();
diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts
index a6bea8fb86a23..1abd73b2cecb7 100644
--- a/apps/web/src/themePalette.ts
+++ b/apps/web/src/themePalette.ts
@@ -412,7 +412,9 @@ const LEGACY_THEME_ID_ALIASES: Readonly> = {
};
function normalizeThemeId(themeId: string): string {
- return LEGACY_THEME_ID_ALIASES[themeId] ?? themeId;
+ return Object.hasOwn(LEGACY_THEME_ID_ALIASES, themeId)
+ ? (LEGACY_THEME_ID_ALIASES[themeId] ?? themeId)
+ : themeId;
}
export function canonicalThemePreference(theme: string): string {
diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts
index 5e6706d861a80..95afac498512f 100644
--- a/apps/web/test/fakeEnvironment.ts
+++ b/apps/web/test/fakeEnvironment.ts
@@ -34,6 +34,7 @@ import {
type OrchestrationV2ThreadStreamItem,
type OrchestrationV2TurnItem,
type TerminalMetadataStreamEvent,
+ type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import type {
ConnectionAttemptError,
@@ -562,6 +563,7 @@ export function installFakeEnvironment(
fixtures: ReadonlyArray,
options?: {
readonly acceptCommands?: boolean;
+ readonly keybindings?: ResolvedKeybindingsConfig;
readonly extraProjects?: ReadonlyArray>;
/** Commands left unanswered even when accepting, until `rejectPendingCommand`. */
readonly holdCommand?: (command: OrchestrationV2Command) => boolean;
@@ -569,7 +571,10 @@ export function installFakeEnvironment(
},
): Disposable {
threads = fixtures;
- baseServerConfig = makeServerConfig(options?.providers ?? [CODEX_PROVIDER]);
+ baseServerConfig = {
+ ...makeServerConfig(options?.providers ?? [CODEX_PROVIDER]),
+ keybindings: options?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS,
+ };
dispatched = [];
acceptCommands = options?.acceptCommands === true;
projects = [
diff --git a/docs/internals/devices.md b/docs/internals/devices.md
index 3fddb7c4d7a02..051f57411d07b 100644
--- a/docs/internals/devices.md
+++ b/docs/internals/devices.md
@@ -26,10 +26,10 @@ operations, so a host whose devices live elsewhere only replaces them.
SSH hosts forward both endpoints to server loopback. Every proxied request
also carries the host id; device ids alone are not unique across hosts.
-## EAS Simulator hosts are billed sessions
+## Expo hosts run billed sessions
-An [EAS host](../../apps/server/src/device/EasDeviceHost.ts) has no machine:
-each opened device is an EAS Simulator session that bills the Expo account
+An [Expo host](../../apps/server/src/device/EasDeviceHost.ts) has no machine:
+each opened device is an Expo Simulators session that bills the Expo account
until it stops. Every session is created with the host's run and idle limits,
the host refuses to start past its session limit, and closing the host stops
its sessions. Sessions it starts are recorded under the state directory and
@@ -42,7 +42,7 @@ route each request (`DeviceHostReady.upstream`) and adds the session token serve
clients never hold it. Agent config files are written per device
(`DeviceOperations.agentEndpoint`), which is why `device_open` opens the
device before targeting it. Device settings and tools run `simctl` or `adb` on
-the device's machine, which EAS does not expose, so they are unavailable there.
+the device's machine, which Expo does not expose, so they are unavailable there.
## Simlock hosts lease through the agent-device front
@@ -145,12 +145,12 @@ WebCodecs is secure-context only, so the viewer probes `isConfigSupported` and f
MJPEG on iOS when decoding is unavailable. Android's SEMU socket has no MJPEG;
there the panel reports that it cannot decode.
-serve-sim can also be locked to WebRTC, as on EAS Simulator, and then refuses
+serve-sim can also be locked to WebRTC, as on Expo Simulators, and then refuses
AVCC with a 409 naming the transport. The viewer still asks for AVCC first, so
hubs that serve it pay nothing, and switches on that 409, or when its MJPEG
image fails in a browser that has `RTCPeerConnection`. Offers are not trickled:
serve-sim takes one offer with every candidate. The video element only feeds
the same canvas sink, so the panel and the mobile WebView keep one surface.
Android asks serve-emu's `/api` before opening its video socket and streams
-WebRTC when it is advertised (EAS Simulator), keeping a separate `video=0`
+WebRTC when it is advertised (Expo Simulators), keeping a separate `video=0`
socket for input so input can reconnect without restarting video.
diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md
index 8dbf42fc45f72..25ecabd80c5a4 100644
--- a/docs/internals/performance-regressions.md
+++ b/docs/internals/performance-regressions.md
@@ -131,6 +131,13 @@ queries read item counts from a per-thread, per-run table that turn-item trigger
use a partial index for nonterminal background items, including idle items. Latest user-message
reads use an index ordered by update time.
+A projection read that orders messages by their first user or assistant turn item groups those
+items by `$.messageId` through a partial index on that expression (migration 94), so it does not
+parse every message item's payload; the index's expression and `WHERE` must stay identical to the
+query's. Migration 94 scans the turn-item table once on first start; a message item whose payload
+is not valid JSON is left out of the index. Each message-item write re-parses the old and new
+payload for the index, so its cost grows with the payload.
+
Command palette results keep live VCS and linked pull-request queries leased to the visible
viewport, including a small overscan region. Cached badges remain available while leases are
released. Local Git status reads skip divergence calculations; callers that need ahead/behind
diff --git a/docs/internals/server-updates.md b/docs/internals/server-updates.md
index 10df2ef464f8b..5e9937c03f5a0 100644
--- a/docs/internals/server-updates.md
+++ b/docs/internals/server-updates.md
@@ -130,8 +130,11 @@ and maintenance turns such as `/compact` before dispatching. Intent and delivery
refuse a thread that is archived, settled, or still snoozed, a cut turn whose provider
turn already ended, and a run waiting on the user: an approval, question, or secret that was pending,
or that recovery closed on the cut turn. Message-capable questions stay answerable, so
-they do not block. Delivery also stops after three consecutive continuations in one
-`restartContinuationOfRunId` chain, so a turn that crashes the server cannot loop. Stable
+they do not block. New continuation intents persist a cumulative process-loss count;
+delivery stops before the fourth crash recovery of an unfinished turn, regardless
+of elapsed time. Planned shutdowns and completed turns reset it. A live continuation
+retains its preceding intent past outbox retention so cleanup cannot erase the count.
+Legacy intents without a count keep the five-minute chain guard. Stable
command and message IDs prevent duplicate submissions after an outbox retry. Codex
resumes without adding provider prompt text unless the turn lost background work;
other adapters receive the continuation message through their normal turn path.
diff --git a/docs/operations/development.md b/docs/operations/development.md
index 2d078b77fb990..9523c253c7620 100644
--- a/docs/operations/development.md
+++ b/docs/operations/development.md
@@ -307,6 +307,7 @@ C/C++ build tools, libsecret development headers, pkg-config, and ImageMagick.
Bytecode preparation also runs packaged Electron and requires GTK, NSS, ALSA, and GBM runtime libraries.
Install Rust 1.95 or newer through [rustup](https://rust-lang.org/install), using the stable
toolchain as release CI does.
+The packaged ELF compatibility check uses binutils’ `readelf`, included by the C/C++ toolchain.
Ubuntu 24.04 and Debian 13:
diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md
index 3e439be81b286..198f0ec70dbba 100644
--- a/docs/orchestration-v2/orchestrator-mcp-server.md
+++ b/docs/orchestration-v2/orchestrator-mcp-server.md
@@ -390,7 +390,7 @@ this binding.
Pass the task in `message`. Project, model, and modes inherit when omitted;
workspace does not. `scratch: true` launches without a project, in a folder of
-its own under the environment's Scratch project. For stacked PRs, use the parent branch as `baseRef` with
+its own under the environment's Scratch project. A new worktree with `startFromOrigin` omitted follows the new-worktree setting. For stacked PRs, use the parent branch as `baseRef` with
`startFromOrigin: false`. The new thread may not run with broader runtime or
interaction modes than the caller. As for `delegate_task`, a runtime mode the
provider does not offer is refused, and an inherited or default one steps down
diff --git a/docs/user/devices.md b/docs/user/devices.md
index 327c3e7b5a838..3130e4aa45c6c 100644
--- a/docs/user/devices.md
+++ b/docs/user/devices.md
@@ -94,7 +94,7 @@ started from then on; your own Device panel is unaffected.
The device stream goes through the environment server, so it works over the
local network, Tailscale, and T3 Connect. Live video needs a secure page
(HTTPS or localhost); on a plain-HTTP remote origin iOS falls back to a slower
-still-image stream and Android cannot show video, except on EAS Simulator.
+still-image stream and Android cannot show video, except on Expo Simulators.
## SSH device hosts
diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md
index 0449990ee0b2b..3e4d47e7c9433 100644
--- a/docs/user/keybindings.md
+++ b/docs/user/keybindings.md
@@ -126,8 +126,8 @@ Join modifiers and a key with `+`, such as `mod+shift+d` or `ctrl+l`.
Available context keys are `terminalFocus`, `terminalOpen`, `previewFocus`,
`previewOpen`, `rightPanelOpen`, `modelPickerOpen`, `usagePageOpen`, `composerFocus`,
`draftThreadRoute`, `turnRunning`, `editableFocus`, `isWeb`, and `isDesktop`.
-`rightPanelOpen` applies only to `rightPanel.new` and is true while the right panel is
-open; the default `mod+t` uses it to open the panel's new-tab menu.
+In a thread, `rightPanelOpen` is true while its right panel is open; the default
+`mod+t` uses it to open the panel's new-tab menu.
`draftThreadRoute` is true on a draft thread, including a restored draft, until it is first sent.
`editableFocus` is true while a text field, the composer, or another editor has
the keyboard. `isWeb` is true in a browser tab. `isDesktop` is true in the
diff --git a/docs/user/updating.md b/docs/user/updating.md
index 5c543dcd0bccf..369e675d7f993 100644
--- a/docs/user/updating.md
+++ b/docs/user/updating.md
@@ -77,8 +77,10 @@ command or monitor the agent said it was waiting on is woken and told that this
stopped. Other background shells and monitors, such as a dev server and its
watchdog, do not wake it; the thread learns about them with your next message.
A thread is not resumed while it waits for your approval, answer, or secret, or
-while it is archived, snoozed, or settled. After three automatic resumes in a row,
-the thread waits for your next message.
+while it is archived, snoozed, or settled. After three consecutive crash recoveries
+of an unfinished turn, the thread waits for your next message, even when crashes
+are more than five minutes apart. A completed turn or a planned shutdown resets
+that limit.
Updates from the previous orchestration system preserve conversation transcripts but cannot carry
every kind of runtime history forward. Read [Threads from older T3 Code versions](./thread-migration.md)
diff --git a/infra/relay/src/clientConfig.test.ts b/infra/relay/src/clientConfig.test.ts
index cf61820a6a2cf..1e8515acc2576 100644
--- a/infra/relay/src/clientConfig.test.ts
+++ b/infra/relay/src/clientConfig.test.ts
@@ -37,10 +37,19 @@ describe("reconcileEnvFile", () => {
it("replaces a quoted multi-line value whole", () => {
expect(reconcileEnvFile('A="one\ntwo"\nKEEP=1\n', { A: "new" })).toBe("A=new\nKEEP=1\n");
expect(reconcileEnvFile("A='x'\nKEEP=1\n", { A: "new" })).toBe("A=new\nKEEP=1\n");
+ expect(
+ reconcileEnvFile(
+ '# earlier "quote"\nA="first\nvalue"\nKEEP=1\nA=\'second\nvalue\'\nB=`third\nvalue`',
+ { A: "new", B: "updated" },
+ ),
+ ).toBe('# earlier "quote"\nA=new\nKEEP=1\nB=updated\n');
});
it("keeps later lines when a quoted value never closes", () => {
expect(reconcileEnvFile('A="one\nKEEP=1\n', { A: "new" })).toBe("A=new\nKEEP=1\n");
+ expect(
+ reconcileEnvFile("A=\"one\nKEEP='two'\nB=`three\nKEEP=2", { A: "new", B: "updated" }),
+ ).toBe("A=new\nKEEP='two'\nB=updated\nKEEP=2\n");
});
it("leaves a commented-out assignment alone", () => {
diff --git a/infra/relay/src/clientConfig.ts b/infra/relay/src/clientConfig.ts
index a0749a205fae8..3e2329f4b572c 100644
--- a/infra/relay/src/clientConfig.ts
+++ b/infra/relay/src/clientConfig.ts
@@ -73,8 +73,12 @@ export function reconcileEnvFile(
const rawValue = match[2] ?? "";
const quote = /^(['"`])/u.exec(rawValue)?.[1];
if (quote !== undefined && !closesQuote(rawValue, quote)) {
- const closing = lines.findIndex((candidate, at) => at > index && candidate.includes(quote));
- if (closing !== -1) index = closing;
+ for (let closing = index + 1; closing < lines.length; closing += 1) {
+ if (lines[closing]!.includes(quote)) {
+ index = closing;
+ break;
+ }
+ }
}
const value = pending.get(name);
if (value !== undefined) {
diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts
index f5d0a3a369910..1fb7aaed524a8 100644
--- a/packages/client-runtime/src/connection/supervisor.test.ts
+++ b/packages/client-runtime/src/connection/supervisor.test.ts
@@ -5,6 +5,7 @@ import {
type ServerConfigStreamEvent,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
+import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -17,6 +18,7 @@ import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as Clock from "effect/Clock";
import * as TestClock from "effect/testing/TestClock";
+import * as Tracer from "effect/Tracer";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import * as TokenStore from "../authorization/tokenStore.ts";
@@ -1561,12 +1563,23 @@ describe("EnvironmentSupervisor", () => {
it.effect("releases and reconnects a relay session when credentials change", () =>
Effect.gen(function* () {
+ const relaySpans: Array = [];
+ const relayTracer = Tracer.make({
+ span(options) {
+ const span = new Tracer.NativeSpan(options);
+ relaySpans.push(span);
+ return span;
+ },
+ });
const harness = yield* makeHarness({
prepare: () => Effect.succeed(preparedFor(RELAY_TARGET)),
});
const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {
initiallyDesired: true,
- }).pipe(Effect.provide(harness.dependencies));
+ }).pipe(
+ Effect.provide(harness.dependencies),
+ Effect.provideService(RelayClientTracer, Option.some(relayTracer)),
+ );
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
yield* harness.wake("credentials-changed");
@@ -1577,6 +1590,13 @@ describe("EnvironmentSupervisor", () => {
expect(yield* Ref.get(harness.sessionCount)).toBe(2);
expect(yield* Ref.get(harness.releaseCount)).toBe(1);
+ const attempts = relaySpans.filter((span) => span.name === "relay.connection.attempt");
+ expect(attempts).toHaveLength(2);
+ for (const span of attempts) {
+ expect(span.attributes.get("environment.id")).toBe(RELAY_TARGET.environmentId);
+ expect(span.attributes.get("environment.target.kind")).toBe(RELAY_TARGET._tag);
+ expect(span.attributes.has("environment.label")).toBe(false);
+ }
}),
);
diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts
index b01f73880ab7d..5a071f8f63a0f 100644
--- a/packages/client-runtime/src/connection/supervisor.ts
+++ b/packages/client-runtime/src/connection/supervisor.ts
@@ -528,8 +528,9 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
let attemptSpan = Option.none();
const traced = Effect.gen(function* () {
attemptSpan = Option.some(yield* Effect.currentSpan.pipe(Effect.orDie));
- yield* annotateTarget(target);
yield* Effect.annotateCurrentSpan({
+ "environment.id": target.environmentId,
+ "environment.target.kind": target._tag,
"connection.attempt": attempt,
"connection.generation": generation,
"connection.retry.failure_count": Option.match(pendingRetry, {
diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts
index 8af40437cdd23..4e9b9767715a6 100644
--- a/packages/client-runtime/src/device/stream.ts
+++ b/packages/client-runtime/src/device/stream.ts
@@ -66,7 +66,7 @@ const webRtcSettingsSchema = Schema.Struct({
iceServers: Schema.optionalKey(Schema.Array(iceServerSchema)),
iceTransportPolicy: Schema.optionalKey(Schema.Literals(["all", "relay"])),
});
-// serve-sim reports its stream settings as `streamSettings` (EAS) or `stream`.
+// serve-sim reports its stream settings as `streamSettings` (Expo) or `stream`.
const serveSimApiSchema = Schema.Struct({
streamSettings: Schema.optionalKey(Schema.Unknown),
stream: Schema.optionalKey(Schema.Unknown),
@@ -864,7 +864,7 @@ export function createDeviceStreamClient(
};
/**
- * serve-sim can be locked to WebRTC (EAS Simulator always is), and then
+ * serve-sim can be locked to WebRTC (an Expo Simulator always is), and then
* refuses AVCC and MJPEG; serve-emu advertises WebRTC the same way. An
* unreadable answer keeps the default path.
*/
diff --git a/packages/client-runtime/src/mcpApps/host.test.ts b/packages/client-runtime/src/mcpApps/host.test.ts
index 4084d2c92ae6c..46e254cbb84ee 100644
--- a/packages/client-runtime/src/mcpApps/host.test.ts
+++ b/packages/client-runtime/src/mcpApps/host.test.ts
@@ -387,5 +387,24 @@ describe("makeMcpAppHost", () => {
expect(sent.find((m) => m.id === 2)?.result).toEqual({});
expect(sent.find((m) => m.id === 3)?.result).toEqual({ isError: true });
expect(sent.find((m) => m.id === 4)?.error).toMatchObject({ code: -32602 });
+
+ const unnamedUris = [
+ "https://example.invalid/report.csv?version=2",
+ "https://example.invalid/report.csv#page=2",
+ "https://example.invalid/report.csv?next=/noise.json#page=3",
+ ];
+ for (const [index, uri] of unnamedUris.entries()) {
+ const id = `download-${index}`;
+ const downloadIndex = downloads.length;
+ host.receive({
+ jsonrpc: "2.0",
+ id,
+ method: "ui/download-file",
+ params: { contents: [{ ...embedded, resource: { ...embedded.resource, uri } }] },
+ });
+ await flush();
+ expect(downloads[downloadIndex]?.[0]).toMatchObject({ _tag: "embedded", name: "report.csv" });
+ expect(sent.find((m) => m.id === id)?.result).toEqual({});
+ }
});
});
diff --git a/packages/client-runtime/src/mcpApps/host.ts b/packages/client-runtime/src/mcpApps/host.ts
index 065508a2ee44b..8c72233aa99a7 100644
--- a/packages/client-runtime/src/mcpApps/host.ts
+++ b/packages/client-runtime/src/mcpApps/host.ts
@@ -480,7 +480,7 @@ function downloadName(uri: unknown, name: unknown): string {
typeof name === "string" && name.trim() !== ""
? name
: typeof uri === "string"
- ? (uri.split(/[/?#]/).findLast(Boolean) ?? "download")
+ ? (uri.split(/[?#]/, 1)[0]?.split("/").findLast(Boolean) ?? "download")
: "download";
let safe = "";
for (const char of raw) {
diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts
index f616f35eef5fe..d4f19173758ec 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.test.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts
@@ -136,6 +136,28 @@ describe("pull request body segmentation", () => {
]);
});
+ it("does not open a fence on a line of inline triple-backtick code", () => {
+ const code = "```\nhttps://example.com/b.png\n```";
+ expect(
+ splitPullRequestBody(
+ `\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`,
+ ),
+ ).toEqual([
+ { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 },
+ {
+ id: "attachment:1",
+ kind: "attachment",
+ url: "https://example.com/demo.mp4",
+ media: "video",
+ },
+ { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 },
+ ]);
+ const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```";
+ expect(splitPullRequestBody(multilineSpan)).toEqual([
+ { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 },
+ ]);
+ });
+
it("leaves an indented code line alone even when it is only a video link", () => {
const body = " https://example.com/demo.mp4";
expect(splitPullRequestBody(body)).toEqual([
diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.ts
index a508b789045b4..8ad710325a50c 100644
--- a/packages/client-runtime/src/pullRequestMarkdown.ts
+++ b/packages/client-runtime/src/pullRequestMarkdown.ts
@@ -261,7 +261,13 @@ function splitBodyAt(body: string, baseOffset: number): ReadonlyArray run.length === fenceMatch[1]!.length);
+ if (fenceMatch !== null && !isInlineCode) {
const fence = fenceMatch[1]!;
// A fence closes only on the same marker, at least as long as the one that opened it,
// and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
diff --git a/packages/client-runtime/src/state/device.ts b/packages/client-runtime/src/state/device.ts
index 2be3d213abcb2..e189fdaa4cb59 100644
--- a/packages/client-runtime/src/state/device.ts
+++ b/packages/client-runtime/src/state/device.ts
@@ -16,9 +16,9 @@ export function createDeviceEnvironmentAtoms(
mode: "serial" as const,
key: ({ environmentId }: { environmentId: string }) => environmentId,
};
- // An EAS Simulator start can take minutes; it must not hold up powering off
+ // Starting an Expo Simulator can take minutes; it must not hold up powering off
// another device or turning device support off, so each device opens in its
- // own lane. Every EAS start opens the same catalog device, so the thread is
+ // own lane. Every Expo start opens the same catalog device, so the thread is
// part of the lane too.
const openConcurrency = {
mode: "serial" as const,
diff --git a/packages/client-runtime/src/state/projects.test.ts b/packages/client-runtime/src/state/projects.test.ts
new file mode 100644
index 0000000000000..f950b319ac332
--- /dev/null
+++ b/packages/client-runtime/src/state/projects.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { isScratchProject } from "./projects.ts";
+
+describe("isScratchProject", () => {
+ it.each([null, undefined])(
+ "recognises a loaded scratch project when its environment offers no available root (%s)",
+ (scratchWorkspaceRoot) => {
+ const project = { workspaceRoot: "/remote/scratch", isScratch: true as const };
+
+ expect(isScratchProject(project, scratchWorkspaceRoot)).toBe(true);
+ },
+ );
+});
diff --git a/packages/client-runtime/src/state/projects.ts b/packages/client-runtime/src/state/projects.ts
index e3e9f39aa32d7..1ec4d28b7882f 100644
--- a/packages/client-runtime/src/state/projects.ts
+++ b/packages/client-runtime/src/state/projects.ts
@@ -136,11 +136,13 @@ export function findProjectByPath {
);
});
+describe("tool text output formatting", () => {
+ it.each([
+ '{"id":1234567890123456789,"name":"x"}',
+ '{"id":1}\n{"id":-9007199254740993}',
+ '{"id":9.007199254740993e15}',
+ '{"id":1e309}',
+ ])("keeps %j as returned when parsing would change a number", (text) => {
+ expect(turnItemOutputText(toolItem({ content: [{ type: "text", text }] }))).toBe(text);
+ });
+
+ it.each(['{"id":42,"note":"12345678901234567890"}', '{"ratio":0.1234567890123456789}'])(
+ "still pretty-prints %j",
+ (text) => {
+ expect(turnItemOutputText(toolItem({ content: [{ type: "text", text }] }))).toBe(
+ JSON.stringify(JSON.parse(text), null, 2),
+ );
+ },
+ );
+});
+
describe("MCP app tool output", () => {
it("shows the tool result, not the app wrapper", () => {
const text = "Notice\nview\tcount\n/home\t42";
diff --git a/packages/client-runtime/src/work-log/itemDetail.ts b/packages/client-runtime/src/work-log/itemDetail.ts
index 045f2918cf229..2630f89dc2ef9 100644
--- a/packages/client-runtime/src/work-log/itemDetail.ts
+++ b/packages/client-runtime/src/work-log/itemDetail.ts
@@ -72,14 +72,33 @@ export function isJsonToolText(text: string): boolean {
return documents.length > 1 && documents.every((document) => parseJson(document) !== undefined);
}
+// Strings match whole so numbers inside them are skipped. Scan only parsed JSON: every string closes.
+const JSON_STRING_OR_NUMBER = /"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g;
+
+/** JSON.parse rounds integers beyond 2^53 and overflows to Infinity, so reformatting would change the value. */
+function hasLossyJsonNumber(json: string): boolean {
+ for (const [token] of json.matchAll(JSON_STRING_OR_NUMBER)) {
+ if (token.startsWith('"')) continue;
+ const value = Number(token);
+ if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {
+ return true;
+ }
+ }
+ return false;
+}
+
function prettyJsonText(text: string): string {
const trimmed = text.trim();
if (!/^[[{]/.test(trimmed)) return text;
const whole = parseJson(trimmed);
- if (whole !== undefined) return JSON.stringify(whole, null, 2);
+ if (whole !== undefined) {
+ return hasLossyJsonNumber(trimmed) ? text : JSON.stringify(whole, null, 2);
+ }
const lines = trimmed.split("\n").filter((line) => line.trim());
const documents = lines.map((line) => parseJson(line.trim()));
- if (documents.some((document) => document === undefined)) return text;
+ if (documents.some((document) => document === undefined) || hasLossyJsonNumber(trimmed)) {
+ return text;
+ }
return documents.map((document) => JSON.stringify(document, null, 2)).join("\n\n");
}
diff --git a/packages/client-runtime/src/worktreeSetup.ts b/packages/client-runtime/src/worktreeSetup.ts
index 0992f63fbc036..f6411cfa7a4ef 100644
--- a/packages/client-runtime/src/worktreeSetup.ts
+++ b/packages/client-runtime/src/worktreeSetup.ts
@@ -1,9 +1,9 @@
-import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
+import type { OrchestrationV2Run, WorktreeSetupSnapshot } from "@t3tools/contracts";
export function resolveVisibleWorktreeSetup(input: {
live: WorktreeSetupSnapshot | null;
recorded: WorktreeSetupSnapshot | null;
- turnStarted: boolean;
+ runs: ReadonlyArray>;
followUpSent: boolean;
}): WorktreeSetupSnapshot | null {
const snapshot =
@@ -14,7 +14,7 @@ export function resolveVisibleWorktreeSetup(input: {
if (snapshot.phase === "running") return snapshot;
if (input.followUpSent) return null;
if (snapshot.phase !== "done") return snapshot;
- if (!input.turnStarted) return snapshot;
+ if (!input.runs.some((run) => run.startedAt !== null)) return snapshot;
return snapshot.stages.some((stage) => stage.status === "failed") ? snapshot : null;
}
diff --git a/packages/contracts/src/acpRegistry.ts b/packages/contracts/src/acpRegistry.ts
index a1d03ef7bd000..c6ecb8862bc4a 100644
--- a/packages/contracts/src/acpRegistry.ts
+++ b/packages/contracts/src/acpRegistry.ts
@@ -268,6 +268,8 @@ export const AcpRegistryProbeModel = Schema.Struct({
id: AcpRegistryProbeText,
name: AcpRegistryProbeText,
description: AcpRegistryProbeDescription,
+ // The reasoning control the agent advertises for this model; null when it has none.
+ reasoningEffort: Schema.optionalKey(Schema.NullOr(ProviderOptionDescriptor)),
});
export type AcpRegistryProbeModel = typeof AcpRegistryProbeModel.Type;
diff --git a/packages/contracts/src/device.test.ts b/packages/contracts/src/device.test.ts
index e49e54a09fdf5..e85e1162931b9 100644
--- a/packages/contracts/src/device.test.ts
+++ b/packages/contracts/src/device.test.ts
@@ -14,7 +14,7 @@ const decodeSshHosts = Schema.decodeUnknownSync(SshDeviceHostConfigs);
const decodeEas = Schema.decodeUnknownSync(EasDeviceHostConfigs);
const encodeState = Schema.encodeSync(DeviceServiceState);
const decodeState = Schema.decodeUnknownSync(DeviceServiceState);
-// The host summary as clients decoded it before EAS hosts existed.
+// The host summary as clients decoded it before Expo hosts existed.
const decodeOlderState = Schema.decodeUnknownSync(
Schema.Struct({
hosts: Schema.Array(
@@ -24,15 +24,15 @@ const decodeOlderState = Schema.decodeUnknownSync(
);
describe("configured device hosts", () => {
- it("reads SSH hosts saved before hosts had a kind, and bounds EAS sessions", () => {
+ it("reads SSH hosts saved before hosts had a kind, and bounds Expo Simulators sessions", () => {
expect(decodeSshHosts([{ id: "mac", label: "Mac mini", target: "julius@mac" }])).toEqual([
{ kind: "ssh", id: "mac", label: "Mac mini", target: "julius@mac" },
]);
- expect(decodeEas([{ kind: "eas", id: "eas", label: "EAS Simulator" }])).toEqual([
+ expect(decodeEas([{ kind: "eas", id: "eas", label: "Expo Simulators" }])).toEqual([
{
kind: "eas",
id: "eas",
- label: "EAS Simulator",
+ label: "Expo Simulators",
accessToken: "",
maxSessionMinutes: 30,
idleMinutes: 10,
@@ -40,21 +40,21 @@ describe("configured device hosts", () => {
},
]);
expect(() =>
- decodeEas([{ kind: "eas", id: "eas", label: "EAS", maxSessionMinutes: 600 }]),
+ decodeEas([{ kind: "eas", id: "eas", label: "Expo", maxSessionMinutes: 600 }]),
).toThrow();
// The default idle limit of 10 is not smaller than a session limit of 10.
expect(() =>
- decodeEas([{ kind: "eas", id: "eas", label: "EAS", maxSessionMinutes: 10 }]),
+ decodeEas([{ kind: "eas", id: "eas", label: "Expo", maxSessionMinutes: 10 }]),
).toThrow();
});
- it("marks the EAS access token as a secret setting", () => {
+ it("marks the Expo access token as a secret setting", () => {
expect(secretSettingsFields(EasDeviceHostConfig)).toEqual(["accessToken"]);
expect(secretSettingsFields(SimlockDeviceHostConfig)).toEqual(["agentToken"]);
});
});
-describe("device state for clients from before EAS hosts", () => {
+describe("device state for clients from before Expo hosts", () => {
const summary = {
label: "Host",
platforms: [],
@@ -77,7 +77,7 @@ describe("device state for clients from before EAS hosts", () => {
revision: 1,
};
- it("sends EAS and Simlock hosts where an older client does not look, and reads them back", () => {
+ it("sends Expo and Simlock hosts where an older client does not look, and reads them back", () => {
const wire = encodeState(state);
expect(decodeOlderState(wire).hosts.map((host) => host.id)).toEqual(["local"]);
expect(decodeState(wire).hosts).toEqual(state.hosts);
diff --git a/packages/contracts/src/device.ts b/packages/contracts/src/device.ts
index dee7daa445242..ab77114980b9a 100644
--- a/packages/contracts/src/device.ts
+++ b/packages/contracts/src/device.ts
@@ -20,7 +20,7 @@ const ConfiguredDeviceHostId = DeviceHostId.check(
);
export const SshDeviceHostConfig = Schema.Struct({
- // Hosts saved before EAS hosts existed carry no kind.
+ // Hosts saved before Expo hosts existed carry no kind.
kind: Schema.Literal("ssh").pipe(Schema.withDecodingDefaultKey(Effect.succeed("ssh" as const))),
id: ConfiguredDeviceHostId,
label: TrimmedNonEmptyString,
@@ -31,14 +31,14 @@ export const SshDeviceHostConfig = Schema.Struct({
export type SshDeviceHostConfig = typeof SshDeviceHostConfig.Type;
/**
- * Cloud simulators from EAS Simulator. Sessions bill the Expo account until
+ * Cloud simulators from Expo Simulators. Sessions bill the Expo account until
* they stop, so every one is bounded. The Expo credential is not stored here.
*/
export const EasDeviceHostConfig = Schema.Struct({
kind: Schema.Literal("eas"),
id: ConfiguredDeviceHostId,
label: TrimmedNonEmptyString,
- /** EAS project that sessions run under, when the project's app config does not name one. */
+ /** Expo project that sessions run under, when the project's app config does not name one. */
appId: Schema.optional(TrimmedNonEmptyString),
/**
* Expo access token, kept in the secret store, or the secret provider to read
@@ -49,7 +49,7 @@ export const EasDeviceHostConfig = Schema.Struct({
Schema.withDecodingDefaultKey(Effect.succeed("")),
Schema.annotateKey({ settingsSecret: true }),
),
- /** EAS allows at most 40 minutes on free accounts and 115 on paid ones. */
+ /** Expo Simulators needs a paid Expo account, and allows sessions of at most 115 minutes. */
maxSessionMinutes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 115 })).pipe(
Schema.withDecodingDefaultKey(Effect.succeed(30)),
),
@@ -60,7 +60,7 @@ export const EasDeviceHostConfig = Schema.Struct({
Schema.withDecodingDefaultKey(Effect.succeed(2)),
),
}).check(
- // EAS requires the idle limit to be smaller than the session limit.
+ // Expo requires the idle limit to be smaller than the session limit.
Schema.makeFilter(
(host: { readonly idleMinutes: number; readonly maxSessionMinutes: number }) =>
host.idleMinutes < host.maxSessionMinutes ||
@@ -109,16 +109,16 @@ export const SshDeviceHostConfigs = Schema.Array(SshDeviceHostConfig).check(uniq
/**
* Kept apart from the SSH hosts in settings: servers and clients from before
- * EAS hosts decode `deviceHosts` as SSH hosts and would reject the whole file
- * or snapshot over one EAS entry.
+ * Expo hosts decode `deviceHosts` as SSH hosts and would reject the whole file
+ * or snapshot over one Expo entry.
*/
export const EasDeviceHostConfigs = Schema.Array(EasDeviceHostConfig).check(uniqueHostIds);
-/** Kept apart from the other host lists for the same reason as EAS hosts. */
+/** Kept apart from the other host lists for the same reason as Expo hosts. */
export const SimlockDeviceHostConfigs = Schema.Array(SimlockDeviceHostConfig).check(uniqueHostIds);
export const DeviceEasAccountInput = Schema.Struct({
- /** A saved EAS host whose stored token is checked when no new token is given. */
+ /** A saved Expo host whose stored token is checked when no new token is given. */
hostId: Schema.optional(DeviceHostId),
accessToken: Schema.optional(SettingsSecretValue),
});
@@ -264,7 +264,7 @@ const deviceServiceStateFields = {
supportsHostRetry: Schema.optional(Schema.Boolean),
supportsToolUpdate: Schema.optional(Schema.Boolean),
supportsToolInspection: Schema.optional(Schema.Boolean),
- /** Servers from before EAS hosts ignore `easDeviceHosts`, so clients offer them only when set. */
+ /** Servers from before Expo hosts ignore `easDeviceHosts`, so clients offer them only when set. */
supportsEasHosts: Schema.optional(Schema.Boolean),
/** Servers from before Simlock hosts ignore `simlockDeviceHosts`. */
supportsSimlockHosts: Schema.optional(Schema.Boolean),
@@ -283,7 +283,7 @@ const deviceServiceStateFields = {
};
/**
- * EAS host summaries travel as `easHosts`: clients from before EAS hosts
+ * Expo host summaries travel as `easHosts`: clients from before Expo hosts
* decode `hosts` with a `local | ssh` kind and would reject the whole state.
* Decoded, every host is in `hosts`.
*/
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 8f5258596c5f5..3197e2827fcbe 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -602,6 +602,12 @@ export interface DesktopPreviewFavicon {
capturedAt: number;
}
+export interface DesktopPreviewDialog {
+ type: string;
+ message: string;
+ defaultValue: string;
+}
+
export interface DesktopPreviewTabState {
tabId: string;
webContentsId: number | null;
@@ -617,6 +623,8 @@ export interface DesktopPreviewTabState {
controller: "human" | "agent" | "none";
/** A screenshot or stream of the guest is pending, so the client keeps it painting while hidden. */
capturing: boolean;
+ /** A page dialog waiting for an answer; the guest stays blocked until the client or an agent answers. */
+ dialog?: DesktopPreviewDialog;
favicon?: DesktopPreviewFavicon;
updatedAt: string;
}
@@ -1016,11 +1024,22 @@ export const DesktopPreviewSetAudioMutedInputSchema = Schema.Struct({
audioMuted: Schema.Boolean,
});
+export const DesktopPreviewAnswerDialogInputSchema = Schema.Struct({
+ tabId: DesktopPreviewTabIdSchema,
+ accept: Schema.Boolean,
+ promptText: Schema.optional(Schema.String),
+});
+
export const DesktopPreviewSetShownInputSchema = Schema.Struct({
tabId: DesktopPreviewTabIdSchema,
shown: Schema.Boolean,
});
+export const DesktopPreviewSetCaptureDrawnInputSchema = Schema.Struct({
+ tabId: DesktopPreviewTabIdSchema,
+ drawn: Schema.Boolean,
+});
+
export const DesktopPreviewAnnotationThemeInputSchema = Schema.Struct({
theme: DesktopPreviewAnnotationThemeSchema,
});
@@ -1279,6 +1298,7 @@ export interface DesktopPreviewBridge {
hardReload: (tabId: string) => Promise;
setColorScheme: (tabId: string, colorScheme: DesktopPreviewColorScheme) => Promise;
setAudioMuted: (tabId: string, audioMuted: boolean) => Promise;
+ answerDialog: (tabId: string, accept: boolean, promptText?: string) => Promise;
findInPage: (
tabId: string,
text: string,
@@ -1287,6 +1307,8 @@ export interface DesktopPreviewBridge {
stopFindInPage: (tabId: string) => Promise;
/** Tells the tab's server whether its webview is on screen. */
setShown: (tabId: string, shown: boolean) => Promise;
+ /** Tells the tab's server whether its webview is drawn at full detail for a capture. */
+ setCaptureDrawn: (tabId: string, drawn: boolean) => Promise;
openDevTools: (tabId: string) => Promise;
clearCookies: (environmentId: EnvironmentId, profileId?: string) => Promise;
clearCache: (environmentId: EnvironmentId, profileId?: string) => Promise;
diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts
index 19163466972bb..84dc4e46c98b2 100644
--- a/packages/contracts/src/orchestratorMcp.ts
+++ b/packages/contracts/src/orchestratorMcp.ts
@@ -38,6 +38,7 @@ import { LastThreadTitleRegeneration, ThreadTitleRegeneration } from "./threadTi
import {
OrchestrationV2Actor,
OrchestrationV2CreationSource,
+ OrchestrationV2DelegatedFrom,
OrchestrationV2RunStatus,
OrchestrationV2TurnItemStatus,
} from "./orchestrationV2.ts";
@@ -185,7 +186,7 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({
}),
),
timeoutMs: Schema.optional(Schema.Finite).annotate({
- description: "Mode 'wait' only. Default 4 min. A timeout does not cancel the child.",
+ description: "Mode 'wait' only. At most 45 s. A timeout does not cancel the child.",
}),
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
runtimeMode: Schema.optional(
@@ -342,7 +343,7 @@ export const OrchestratorMcpEnvironmentTarget = Schema.optional(
// Codex hides `minimum` and `maximum` from the model, so a value above the maximum clamps on
// decode instead of failing the call; pagination returns the rest. Values below 1 still fail:
// 0 asks for nothing, and answering it with one item would be a different request.
-const clampedPositiveInt = (maximum: number) =>
+export const clampedPositiveInt = (maximum: number) =>
PositiveInt.pipe(
Schema.decodeTo(
PositiveInt.check(Schema.isLessThanOrEqualTo(maximum)),
@@ -419,6 +420,8 @@ export const OrchestratorMcpThreadListItem = Schema.Struct({
pendingBackgroundTasks: Schema.optional(Schema.Array(OrchestratorMcpThreadBackgroundTask)),
parentThreadId: Schema.NullOr(ThreadId),
relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])),
+ /** The linked environment's thread that delegated this one; absent otherwise. */
+ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),
itemCount: NonNegativeInt,
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -476,6 +479,8 @@ export const OrchestratorMcpThreadDetail = Schema.Struct({
worktreePath: Schema.NullOr(Schema.String),
parentThreadId: Schema.NullOr(ThreadId),
relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])),
+ /** The linked environment's thread that delegated this one; absent otherwise. */
+ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),
runCount: NonNegativeInt,
itemCount: NonNegativeInt,
pendingRequestCount: NonNegativeInt,
diff --git a/packages/contracts/src/previewAutomation.ts b/packages/contracts/src/previewAutomation.ts
index 228297667d318..eba5b37e6034f 100644
--- a/packages/contracts/src/previewAutomation.ts
+++ b/packages/contracts/src/previewAutomation.ts
@@ -569,11 +569,19 @@ export const PreviewAutomationSnapshot = Schema.Struct({
});
export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
+// pixelsRequired is false when the caller discards the screenshot; hosts that ignore it still return a PNG.
export const PreviewAutomationSnapshotInput = Schema.Struct({
fullScreenshot: Schema.optional(Schema.Boolean),
+ pixelsRequired: Schema.optional(Schema.Boolean),
});
export type PreviewAutomationSnapshotInput = typeof PreviewAutomationSnapshotInput.Type;
+export const PreviewAutomationSnapshotMetadata = Schema.Struct({
+ ...PreviewAutomationSnapshot.fields,
+ screenshot: Schema.Struct({ width: Schema.Int, height: Schema.Int }),
+});
+export type PreviewAutomationSnapshotMetadata = typeof PreviewAutomationSnapshotMetadata.Type;
+
export const PreviewAutomationRecordingStatus = Schema.Struct({
tabId: PreviewTabId,
recording: Schema.Boolean,
diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts
index 3f1198c1212e8..df5447f21df6a 100644
--- a/packages/contracts/src/pullRequest.ts
+++ b/packages/contracts/src/pullRequest.ts
@@ -370,6 +370,7 @@ export const PullRequestListEntry = Schema.Struct({
state: PullRequestState,
isDraft: Schema.Boolean,
mergeability: PullRequestMergeability,
+ rebaseRequired: Schema.optional(Schema.Boolean),
/** Zero until fetched through `PullRequestListStatsInput`; GitHub listings omit counts. */
additions: NonNegativeInt,
deletions: NonNegativeInt,
@@ -528,6 +529,7 @@ export const PullRequestSummary = Schema.Struct({
reviewDecision: Schema.optional(Schema.NullOr(PullRequestReviewDecision)),
checksState: Schema.optional(Schema.NullOr(PullRequestChecksState)),
mergeability: Schema.optional(PullRequestMergeability),
+ rebaseRequired: Schema.optional(Schema.Boolean),
/** Null when the host says the pull request is in no stack; absent when the read did not ask. */
stack: Schema.optional(Schema.NullOr(PullRequestStackMembership)),
headSha: Schema.optional(TrimmedNonEmptyString),
@@ -651,6 +653,7 @@ export const PullRequestDetail = Schema.Struct({
state: PullRequestState,
isDraft: Schema.Boolean,
mergeability: PullRequestMergeability,
+ rebaseRequired: Schema.optional(Schema.Boolean),
additions: NonNegativeInt,
deletions: NonNegativeInt,
changedFiles: NonNegativeInt,
diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts
index d859ecb91ffa4..e2662bca07463 100644
--- a/packages/contracts/src/server.ts
+++ b/packages/contracts/src/server.ts
@@ -622,7 +622,7 @@ const EnvironmentThemeColors = Schema.Record(
TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
);
-export const THEME_CSS_MAX_LENGTH = 20_000;
+export const THEME_CSS_MAX_LENGTH = 50_000;
const environmentThemeFields = {
version: Schema.optional(Schema.Literal(1)),
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index 8ef1340b53e29..1db913e38ba3b 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -418,17 +418,17 @@ describe("ServerSettings environment icon", () => {
const decodeDeviceHostSettings = Schema.decodeSync(ServerSettings);
-// `deviceHosts` as it was decoded before EAS hosts existed: an SSH host needs a target.
+// `deviceHosts` as it was decoded before Expo hosts existed: an SSH host needs a target.
const decodeOlderDeviceHostSettings = Schema.decodeUnknownSync(
Schema.Struct({
deviceHosts: Schema.Array(Schema.Struct({ id: Schema.String, target: Schema.String })),
}),
);
-it("keeps EAS hosts out of the SSH host list servers and clients before EAS hosts decode", () => {
+it("keeps Expo hosts out of the SSH host list servers and clients before Expo hosts decode", () => {
const settings = decodeDeviceHostSettings({
deviceHosts: [{ id: "mini", label: "Mac mini", target: "user@mini" }],
- easDeviceHosts: [{ kind: "eas", id: "eas", label: "EAS Simulator" }],
+ easDeviceHosts: [{ kind: "eas", id: "eas", label: "Expo Simulators" }],
});
const wire = encodeServerSettings(settings);
expect(decodeOlderDeviceHostSettings(wire).deviceHosts).toEqual([
@@ -439,7 +439,7 @@ it("keeps EAS hosts out of the SSH host list servers and clients before EAS host
it("validates remote device hosts and rejects ambiguous host ids", () => {
const host = { id: "mini", label: "Mac mini", target: "user@mini", port: 2222 };
- // Hosts saved before EAS hosts existed have no `kind`; they are SSH hosts.
+ // Hosts saved before Expo hosts existed have no `kind`; they are SSH hosts.
expect(decodeDeviceHostSettings({ deviceHosts: [host] }).deviceHosts).toEqual([
{ kind: "ssh", ...host },
]);
diff --git a/packages/contracts/src/threadPullRequest.ts b/packages/contracts/src/threadPullRequest.ts
index 7775f0755ff0b..0c8d7a61fe92d 100644
--- a/packages/contracts/src/threadPullRequest.ts
+++ b/packages/contracts/src/threadPullRequest.ts
@@ -51,6 +51,7 @@ export const ThreadPullRequestSnapshot = Schema.Struct({
reviewDecision: Schema.optional(Schema.NullOr(PullRequestReviewDecision)),
checksState: Schema.optional(Schema.NullOr(PullRequestChecksState)),
mergeability: Schema.optional(PullRequestMergeability),
+ rebaseRequired: Schema.optional(Schema.Boolean),
});
export type ThreadPullRequestSnapshot = typeof ThreadPullRequestSnapshot.Type;
@@ -97,6 +98,7 @@ export const ThreadPullRequestWatch = Schema.Struct({
/** Reported remarks at remarksThrough, so late arrivals at that timestamp still count. */
remarkIds: Schema.Array(TrimmedNonEmptyString),
conflicting: Schema.Boolean,
+ rebaseRequired: Schema.optional(Schema.Boolean),
/** Last removal seen; null after an empty read, absent before the first read. */
mergeQueueRemovalId: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
/** Consecutive comment-only wakes; limited to prevent bot loops. */
diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.ts
index d8745bbfe7b13..889d750e1907b 100644
--- a/packages/effect-acp/src/protocol.ts
+++ b/packages/effect-acp/src/protocol.ts
@@ -1,6 +1,7 @@
import type * as AcpCompat from "./compat.ts";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
+import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Exit from "effect/Exit";
@@ -115,6 +116,15 @@ export interface AcpPatchedProtocolOptions {
};
}
+/**
+ * Provided to a request call, settles once that request is queued for writing. Messages queued
+ * later are written after it; the call itself returns only with the reply.
+ */
+export const AcpOutgoingQueued = Context.Reference | undefined>(
+ "effect-acp/protocol/AcpOutgoingQueued",
+ { defaultValue: () => undefined },
+);
+
export interface AcpPatchedProtocol {
readonly clientProtocol: RpcClient.Protocol["Service"];
readonly serverProtocol: RpcServer.Protocol["Service"];
@@ -438,6 +448,10 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
}).pipe(Effect.andThen(Deferred.fail(acknowledgement, error)), Effect.asVoid),
),
);
+ const queued = yield* AcpOutgoingQueued;
+ if (queued !== undefined) {
+ yield* Deferred.succeed(queued, undefined);
+ }
if (acknowledgement !== undefined) {
yield* Deferred.await(acknowledgement);
}
diff --git a/packages/effect-codex-app-server/src/client.test.ts b/packages/effect-codex-app-server/src/client.test.ts
index 56d9dbcebfae1..2b86e25cde567 100644
--- a/packages/effect-codex-app-server/src/client.test.ts
+++ b/packages/effect-codex-app-server/src/client.test.ts
@@ -1,5 +1,6 @@
import * as Deferred from "effect/Deferred";
import * as Exit from "effect/Exit";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
@@ -209,6 +210,64 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
assert.notInclude(JSON.stringify(warnings), secret);
}),
);
+
+ it.effect("a dying notification handler leaves no request waiting on a live app-server", () =>
+ Effect.gen(function* () {
+ const handle = yield* makeHandle();
+ const client = yield* Layer.build(CodexClient.layerChildProcess(handle)).pipe(
+ Effect.flatMap((context) =>
+ Effect.service(CodexClient.CodexAppServerClient).pipe(Effect.provide(context)),
+ ),
+ );
+ // A Codex error type must still surface as a transport failure, not as Codex's answer.
+ const handlerFailure = CodexError.CodexAppServerRequestError.internalError("Injected");
+ yield* client.handleServerNotification("error", () =>
+ Effect.fail(handlerFailure).pipe(Effect.orDie),
+ );
+ const termination = yield* client.awaitTermination.pipe(Effect.flip, Effect.forkScoped);
+
+ // The peer answers right after this notification and stays alive, so only the reader's
+ // own termination can settle the request.
+ const failure = yield* client.raw
+ .request("mock/notifyThenRespond", {
+ notification: {
+ method: "error",
+ params: {
+ error: {
+ message: "Fatal error: application network permission was revoked",
+ codexErrorInfo: "other",
+ additionalDetails: null,
+ },
+ willRetry: false,
+ threadId: "thread-1",
+ turnId: "turn-1",
+ },
+ },
+ })
+ .pipe(
+ Effect.match({
+ onFailure: (error) => error,
+ onSuccess: () => assert.fail("Expected the dead reader to fail the request"),
+ }),
+ );
+
+ assert.instanceOf(failure, CodexError.CodexAppServerTransportError);
+ assert.equal(failure.operation, "read-input-stream");
+ assert.strictEqual(failure.cause, handlerFailure);
+ assert.strictEqual(yield* Fiber.join(termination), failure);
+ assert.strictEqual(
+ yield* client.raw.request("thread/read", {}).pipe(
+ Effect.match({
+ onFailure: (error) => error,
+ onSuccess: () => assert.fail("Expected the retired transport to reject requests"),
+ }),
+ ),
+ failure,
+ );
+ // Retiring the transport closes the app-server's stdin, so it does not live on unread.
+ assert.equal(yield* handle.exitCode, 0);
+ }),
+ );
});
it.live("reports the stderr error when the process exits before initialize", () =>
diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.ts
index b4c3ac7b7558b..7d2118939fbb1 100644
--- a/packages/effect-codex-app-server/src/protocol.test.ts
+++ b/packages/effect-codex-app-server/src/protocol.test.ts
@@ -1,8 +1,10 @@
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
+import * as Logger from "effect/Logger";
import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue";
+import * as References from "effect/References";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stdio from "effect/Stdio";
@@ -510,6 +512,55 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
}),
);
+ it.effect.each([
+ { outcome: "dies", method: "item/tool/requestUserInput", logged: "item/tool/requestUserInput" },
+ { outcome: "throws", method: "codex-handler-secret-sentinel", logged: "unknown" },
+ ] as const)(
+ "answers an incoming request whose handler $outcome, keeping its text out of logs",
+ ({ outcome, method, logged: loggedMethod }) =>
+ Effect.gen(function* () {
+ const secret = "codex-handler-secret-sentinel";
+ const defect = Object.assign(new Error(secret), { name: secret });
+ const { stdio, input, output } = yield* makeInMemoryStdio();
+ const logged: Array = [];
+ yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
+ stdio,
+ onRequest: () => {
+ if (outcome === "throws") throw defect;
+ return Effect.die(defect);
+ },
+ }).pipe(
+ Effect.provide(
+ Logger.layer([
+ Logger.make(({ logLevel, message, fiber }) => {
+ if (logLevel === "Error") {
+ logged.push(
+ String([message].flat()),
+ JSON.stringify(fiber.getRef(References.CurrentLogAnnotations)),
+ );
+ }
+ }),
+ ]),
+ ),
+ );
+
+ const request = encodeUnknownJsonString({ id: 1, method, params: {} });
+ yield* Queue.offer(
+ input,
+ encoder.encode(`${request}
+`),
+ );
+
+ assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
+ id: 1,
+ error: { code: -32603, message: "Internal error" },
+ });
+ assert.lengthOf(logged, 2);
+ assert.notInclude(logged.join(), secret);
+ assert.include(logged.join(), loggedMethod);
+ }),
+ );
+
it.effect("releases a waiting request handler when Codex resolves its request", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
@@ -832,6 +883,78 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
}),
);
+ it.effect("fails pending requests when the exit status lookup dies", () =>
+ Effect.gen(function* () {
+ const { stdio, input, output } = yield* makeInMemoryStdio();
+ const defect = new Error("Injected exit status defect");
+ const terminated = yield* Deferred.make();
+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
+ stdio,
+ terminationError: Effect.die(defect),
+ onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
+ });
+ const pending = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
+ yield* Queue.take(output);
+
+ yield* Queue.end(input);
+
+ const failure = yield* Fiber.join(pending).pipe(
+ Effect.match({
+ onFailure: (error) => error,
+ onSuccess: () => assert.fail("Expected the pending request to fail"),
+ }),
+ );
+ assert.instanceOf(failure, CodexError.CodexAppServerTransportError);
+ assert.strictEqual(failure.cause, defect);
+ assert.strictEqual(yield* Deferred.await(terminated), failure);
+ }),
+ );
+
+ it.effect("retires the transport after a defect in the writer", () =>
+ Effect.gen(function* () {
+ const { stdio: baseStdio } = yield* makeInMemoryStdio();
+ const defect = new Error("Injected transport defect");
+ const terminated = yield* Deferred.make();
+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
+ stdio: Stdio.make({
+ ...baseStdio,
+ stdout: () => Sink.forEach(() => Effect.die(defect)),
+ }),
+ onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
+ });
+
+ const failure = yield* transport.request("thread/read", {}).pipe(
+ Effect.match({
+ onFailure: (error) => error,
+ onSuccess: () => assert.fail("Expected the dead writer to fail the request"),
+ }),
+ );
+ assert.instanceOf(failure, CodexError.CodexAppServerTransportError);
+ assert.equal(failure.operation, "write-output-stream");
+ assert.strictEqual(failure.cause, defect);
+ assert.strictEqual(yield* Deferred.await(terminated), failure);
+ }),
+ );
+
+ it.effect("does not report normal scope shutdown as a transport failure", () =>
+ Effect.gen(function* () {
+ let terminations = 0;
+ yield* Effect.gen(function* () {
+ const { stdio, output } = yield* makeInMemoryStdio();
+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
+ stdio,
+ onTermination: () =>
+ Effect.sync(() => {
+ terminations++;
+ }),
+ });
+ yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
+ yield* Queue.take(output);
+ }).pipe(Effect.scoped);
+ assert.equal(terminations, 0);
+ }),
+ );
+
it.effect("fails pending requests when a write fails while input stays open", () =>
Effect.gen(function* () {
const { stdio: baseStdio } = yield* makeInMemoryStdio();
@@ -869,6 +992,38 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
}),
);
+ it.effect("reports the process exit when a write fails because the process exited", () =>
+ Effect.gen(function* () {
+ const { stdio: baseStdio } = yield* makeInMemoryStdio();
+ const exitError = new CodexError.CodexAppServerProcessExitedError({ code: 1, pid: 123 });
+ const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
+ stdio: Stdio.make({
+ ...baseStdio,
+ stdout: () =>
+ Sink.forEach(() =>
+ Effect.fail(
+ PlatformError.systemError({
+ _tag: "Unknown",
+ module: "Stdio",
+ method: "stdout",
+ cause: new Error("EPIPE"),
+ }),
+ ),
+ ),
+ }),
+ terminationError: Effect.succeed(exitError),
+ });
+
+ const failure = yield* transport.request("initialize", {}).pipe(
+ Effect.match({
+ onFailure: (error) => error,
+ onSuccess: () => assert.fail("Expected the exited process to fail the request"),
+ }),
+ );
+ assert.strictEqual(failure, exitError);
+ }),
+ );
+
it.effect("reports a process exit that follows input end", () =>
Effect.gen(function* () {
const { stdio, input } = yield* makeInMemoryStdio();
diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.ts
index fdf0863af0a16..0faf9e44e4b44 100644
--- a/packages/effect-codex-app-server/src/protocol.ts
+++ b/packages/effect-codex-app-server/src/protocol.ts
@@ -11,6 +11,7 @@ import * as Schema from "effect/Schema";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
+import * as CodexRpc from "./_generated/meta.gen.ts";
import * as CodexError from "./errors.ts";
import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
const isJsonRpcId = Schema.is(JsonRpcId);
@@ -228,6 +229,26 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
] as const;
}).pipe(Effect.flatten);
+ // Node ends stdout before it reports the exit of a crashed process, so wait briefly
+ // for the exit status. Pipes can also close while the process keeps running, so the
+ // wait must not hang pending requests.
+ const exitStatusOr = (
+ fallback: CodexError.CodexAppServerError,
+ operation: "read-input-stream" | "write-output-stream",
+ ) =>
+ options.terminationError === undefined
+ ? Effect.succeed(fallback)
+ : options.terminationError.pipe(
+ Effect.timeoutOrElse({
+ duration: EXIT_STATUS_GRACE,
+ orElse: () => Effect.succeed(fallback),
+ }),
+ // A defect here would leave termination marked handled but unfinished.
+ Effect.catchDefect((cause) =>
+ Effect.succeed(new CodexError.CodexAppServerTransportError({ operation, cause })),
+ ),
+ );
+
const offerOutgoing =
/* Every protocol write reaches this helper; request spans cover the operation. */
Effect.fnUntraced(function* (message: Record) {
@@ -326,7 +347,21 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
);
}
- return handler(request).pipe(
+ return Effect.suspend(() => handler(request)).pipe(
+ // Adapter handlers end in Effect.orDie; Codex waits for an answer regardless.
+ Effect.catchDefect(() =>
+ Effect.logError("Codex request handler failed").pipe(
+ Effect.annotateLogs({
+ method:
+ request.method in CodexRpc.SERVER_REQUEST_PARAMS
+ ? request.method
+ : "unknown",
+ }),
+ Effect.andThen(
+ Effect.fail(CodexError.CodexAppServerRequestError.internalError()),
+ ),
+ ),
+ ),
Effect.matchEffect({
onFailure: (error) =>
respondError(
@@ -459,35 +494,39 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
Effect.matchEffect({
onFailure: (error) => handleTermination(() => Effect.succeed(error)),
onSuccess: () =>
- handleTermination(() => {
- const ended = new CodexError.CodexAppServerInputStreamEndedError({});
- // Node ends stdout before it reports the exit of a crashed process, so
- // wait briefly for the exit status. stdout can also close while the
- // process keeps running, so the wait must not hang pending requests.
- return options.terminationError === undefined
- ? Effect.succeed(ended)
- : options.terminationError.pipe(
- Effect.timeoutOrElse({
- duration: EXIT_STATUS_GRACE,
- orElse: () => Effect.succeed(ended),
- }),
- );
- }),
+ handleTermination(() =>
+ exitStatusOr(
+ new CodexError.CodexAppServerInputStreamEndedError({}),
+ "read-input-stream",
+ ),
+ ),
}),
),
}),
+ Effect.catchCause((cause) =>
+ handleTermination(() =>
+ Effect.succeed(
+ new CodexError.CodexAppServerTransportError({
+ operation: "read-input-stream",
+ cause: Cause.squash(cause),
+ }),
+ ),
+ ),
+ ),
Effect.forkScoped,
);
yield* Stream.fromQueue(outgoing).pipe(
Stream.run(options.stdio.stdout()),
- Effect.catch((cause) =>
+ Effect.catchCause((cause) =>
handleTermination(() =>
- Effect.succeed(
+ // Writing to a process that already exited fails with EPIPE; report the exit.
+ exitStatusOr(
new CodexError.CodexAppServerTransportError({
operation: "write-output-stream",
- cause,
+ cause: Cause.squash(cause),
}),
+ "write-output-stream",
),
),
),
diff --git a/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts b/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts
index 59e5eb28faf94..dda8240fe4f2c 100644
--- a/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts
+++ b/packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts
@@ -104,6 +104,12 @@ const handleMethod = (message: Record) => {
});
return;
}
+ case "mock/notifyThenRespond": {
+ const params = message.params as { readonly notification: unknown };
+ writeMessage(params.notification);
+ respond(message.id as number | string, { answered: true });
+ return;
+ }
default: {
if (message.id !== undefined) {
respondError(message.id as number | string, -32601, `Unhandled request: ${method}`);
diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts
index 1495cb0bb64dd..ee88901d16905 100644
--- a/packages/provider-acp-registry/src/server/driver.test.ts
+++ b/packages/provider-acp-registry/src/server/driver.test.ts
@@ -271,6 +271,44 @@ describe("acpRegistrySnapshotReadiness", () => {
expect(afterOpus.find((model) => model.slug === "opus")).toMatchObject({
capabilities: { optionDescriptors: [{ id: "thinking" }, { id: "mode" }] },
});
+
+ // Other models take the levels they advertise in `_meta`.
+ const effort = {
+ id: "effort",
+ name: "Effort",
+ category: "thought_level",
+ type: "select" as const,
+ currentValue: "high",
+ options: [{ value: "high", name: "High" }],
+ };
+ const advertised = applyAcpRegistryLiveConfiguration(
+ provider,
+ normalizeAcpRegistryLiveConfiguration([effort], undefined, {
+ currentModelId: "opus",
+ availableModels: [
+ { modelId: "opus", name: "Opus" },
+ {
+ modelId: "haiku",
+ name: "Haiku",
+ _meta: { reasoningEfforts: [{ value: "low", label: "Low" }], reasoningEffort: "low" },
+ },
+ { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } },
+ ],
+ }),
+ [],
+ ).models.map((model) => model.capabilities?.optionDescriptors ?? []);
+ expect(advertised).toEqual([
+ [{ ...liveOptions[0]!, role: "reasoning" }],
+ [
+ {
+ ...liveOptions[0]!,
+ role: "reasoning",
+ options: [{ id: "low", label: "Low" }],
+ currentValue: "low",
+ },
+ ],
+ [],
+ ]);
});
it("projects discovery without claiming authentication when no login methods are advertised", () => {
diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts
index 2db192b9c7f96..726d95a145e91 100644
--- a/packages/provider-acp-registry/src/server/driver.ts
+++ b/packages/provider-acp-registry/src/server/driver.ts
@@ -4,6 +4,7 @@ import {
resolveOfficialAcpRegistryIconUrl,
TextGenerationError,
type AcpRegistryOperationError,
+ type AcpRegistryProbeModel,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
@@ -111,12 +112,19 @@ function modelsFromDiscovery(
(descriptor) => !modelOptionIds.has(descriptor.id),
);
const sharedIds = new Set(shared.map((descriptor) => descriptor.id));
- const capabilitiesFor = (slug: string) => {
+ const capabilitiesFor = ({ id: slug, reasoningEffort }: AcpRegistryProbeModel) => {
if (slug === discovery?.currentModelId) return capabilities;
+ // The levels a model advertises replace the ones an earlier session reported.
const own = (
previousModels.find((model) => model.slug === slug)?.capabilities?.optionDescriptors ?? []
- ).filter((descriptor) => !sharedIds.has(descriptor.id));
- const optionDescriptors = [...shared, ...own];
+ ).filter(
+ (descriptor) =>
+ !sharedIds.has(descriptor.id) &&
+ (reasoningEffort === undefined ||
+ descriptor.type !== "select" ||
+ descriptor.role !== "reasoning"),
+ );
+ const optionDescriptors = [...shared, ...own, ...(reasoningEffort ? [reasoningEffort] : [])];
return optionDescriptors.length === 0
? EMPTY_CAPABILITIES
: createModelCapabilities({ optionDescriptors });
@@ -137,7 +145,7 @@ function modelsFromDiscovery(
name: model.name,
isCustom: false,
...(model.id === discovery?.currentModelId ? { isDefault: true } : {}),
- capabilities: capabilitiesFor(model.id),
+ capabilities: capabilitiesFor(model),
}));
return providerModelsFromSettings(builtInModels, customModels, capabilities);
}
diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts
index 2fcf80cbce4d9..662f28783ca45 100644
--- a/packages/provider-acp-registry/src/server/probe.ts
+++ b/packages/provider-acp-registry/src/server/probe.ts
@@ -53,6 +53,39 @@ const boundedText = (value: string, maximumLength: number): string =>
const boundedOpaqueValue = (value: string, maximumLength: number): string | undefined =>
value.length > 0 && value === value.trim() && value.length <= maximumLength ? value : undefined;
+/**
+ * The session's reasoning option with the levels a model advertises in `_meta`, in the
+ * shape Grok uses. Null when the model has none, undefined when it says nothing.
+ */
+function advertisedReasoningEffort(
+ option: EffectAcpSchema.SessionConfigOption | undefined,
+ meta: Readonly> | null | undefined,
+): AcpRegistryProbeModel["reasoningEffort"] {
+ if (option?.type !== "select" || meta == null) return undefined;
+ if (meta.supportsReasoningEffort === false) return null;
+ if (!Array.isArray(meta.reasoningEfforts)) return undefined;
+ const options = meta.reasoningEfforts.flatMap((level: unknown) =>
+ typeof level === "object" &&
+ level !== null &&
+ "value" in level &&
+ typeof level.value === "string"
+ ? [
+ {
+ value: level.value,
+ name: "label" in level && typeof level.label === "string" ? level.label : level.value,
+ },
+ ]
+ : [],
+ );
+ const currentValue = typeof meta.reasoningEffort === "string" ? meta.reasoningEffort : "";
+ return (
+ acpProviderOptionDescriptors({
+ configOptions: [{ ...option, options, currentValue }],
+ modeState: undefined,
+ })[0] ?? null
+ );
+}
+
export function normalizeAcpRegistryWebUrl(value: string): string | undefined {
if (value.length > 2_048 || !URL.canParse(value)) return undefined;
const url = new URL(value);
@@ -195,7 +228,14 @@ export function normalizeAcpRegistryLiveConfiguration(
currentModelId === undefined
? null
: (boundedOpaqueValue(currentModelId, MAX_ID_LENGTH) ?? null);
- const models = normalizeModels(candidates, boundedCurrentModelId);
+ const effortOption = configOptions.find((option) => option.category === "thought_level");
+ const models = normalizeModels(candidates, boundedCurrentModelId).map((model) => {
+ const reasoningEffort = advertisedReasoningEffort(
+ effortOption,
+ modelState?.availableModels.find((info) => info.modelId === model.id)?._meta,
+ );
+ return reasoningEffort === undefined ? model : { ...model, reasoningEffort };
+ });
const descriptors = acpProviderOptionDescriptors({ configOptions, modeState });
const modelOptionIds = new Set(
configOptions
diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts
index b8f089f410b6d..59d701eddb97b 100644
--- a/packages/provider-acp/src/server/AcpSessionRuntime.ts
+++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts
@@ -27,7 +27,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as EffectAcpClient from "effect-acp/client";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/compat";
-import type * as EffectAcpProtocol from "effect-acp/protocol";
+import * as EffectAcpProtocol from "effect-acp/protocol";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { AgentScope, AgentScopeThreadId, RAISE_OOM_SCORE_LINE } from "@t3tools/shared/AgentScope";
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -1245,8 +1245,14 @@ interface EnsureActiveAssistantSegmentResult {
interface AcpActivePrompt {
readonly fiber: Fiber.Fiber;
readonly completed: Deferred.Deferred;
+ /** Settles once the prompt is queued to the agent, or its call has ended without that. */
+ readonly queued: Deferred.Deferred;
}
+// A fiber stopped before its call began never settles queued, so its end counts too.
+const awaitPromptQueued = (prompt: AcpActivePrompt) =>
+ Effect.raceFirst(Deferred.await(prompt.queued), Fiber.await(prompt.fiber).pipe(Effect.asVoid));
+
export const make = Effect.fn("AcpSessionRuntime.make")(function* (
options: AcpSessionRuntimeOptions,
): Effect.fn.Return<
@@ -2403,8 +2409,16 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
sessionId: started.sessionId,
...(options.cancelMeta === undefined ? {} : { _meta: options.cancelMeta }),
} satisfies EffectAcpSchema.CancelNotification;
+ // An agent drops a cancel that reaches it before the prompt it targets, so the cancel waits
+ // until the prompt is queued, for at most the cancel timeout.
+ const promptQueued = Option.isSome(activePrompt)
+ ? awaitPromptQueued(activePrompt.value).pipe(
+ Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout),
+ )
+ : Effect.void;
if (options.cancelBehavior !== "wait-for-prompt") {
if (options.interruptPromptOnCancel === false) {
+ yield* promptQueued;
return yield* acp.agent.cancel(cancelPayload);
}
if (Option.isSome(activePrompt)) {
@@ -2415,6 +2429,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
return;
}
+ yield* promptQueued;
yield* acp.agent.cancel(cancelPayload);
if (Option.isNone(activePrompt)) {
return;
@@ -2649,12 +2664,18 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
...payload,
} satisfies EffectAcpSchema.PromptRequest;
const completed = yield* Deferred.make();
+ const queued = yield* Deferred.make();
const fiber = yield* runLoggedRequest(
"session/prompt",
requestPayload,
- acp.agent.prompt(requestPayload),
+ acp.agent
+ .prompt(requestPayload)
+ .pipe(
+ Effect.provideService(EffectAcpProtocol.AcpOutgoingQueued, queued),
+ Effect.ensuring(Deferred.succeed(queued, undefined)),
+ ),
).pipe(Effect.forkIn(runtimeScope));
- const active = { fiber, completed } satisfies AcpActivePrompt;
+ const active = { fiber, completed, queued } satisfies AcpActivePrompt;
yield* Ref.set(activePromptRef, Option.some(active));
if (promptOptions?.dispatched) {
yield* Deferred.succeed(promptOptions.dispatched, undefined);
@@ -2711,8 +2732,10 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
: joinPrompt(outcome.fiber),
),
),
+ // A cancel that waits for its prompt holds the dispatch permit, so a next prompt cannot reach
+ // the agent ahead of it and take the cancel meant for the prompt before.
cancel:
- options.cancelBehavior === "wait-for-prompt"
+ options.cancelBehavior === "wait-for-prompt" || options.interruptPromptOnCancel === false
? promptDispatchSemaphore.withPermit(cancel)
: cancel,
...(options.ownDetachedProcessGroup === true ? { terminateProcessGroup } : {}),
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 0875b039d79eb..e0fb9d0f61ae2 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -1497,6 +1497,15 @@ interface ActiveAcpTurn {
{
readonly id: OrchestrationV2PlanArtifact["id"];
readonly startedAt: DateTime.Utc;
+ /** The turn that first reported the plan; later turns update its rows. */
+ readonly origin: {
+ readonly runId: ActiveAcpTurn["input"]["runId"];
+ readonly rootNodeId: ActiveAcpTurn["input"]["rootNodeId"];
+ readonly providerThreadId: ActiveAcpTurn["input"]["providerThread"]["id"];
+ readonly providerTurnId: ActiveAcpTurn["providerTurnId"];
+ readonly nativeItemId: string;
+ readonly ordinal: number;
+ };
latest: OrchestrationV2PlanArtifact | null;
}
>;
@@ -1662,11 +1671,13 @@ function acpPostSettleMonitorPromptShouldSuppress(
}
export function acpCompletedTurnShouldTerminalizeTool(
- tool: AcpToolCallState,
+ tool: AcpToolCallState & { readonly backgroundCommandTaskId?: string },
flavor: Pick,
): boolean {
const status = toolStatus(tool.status);
if (status !== "pending" && status !== "running") return false;
+ // Progress output replaces the start ACK, so the registered task id outlives it.
+ if (tool.backgroundCommandTaskId !== undefined) return false;
if (flavor.extractBackgroundTaskId?.(tool) !== undefined) return false;
return flavor.extractSubagentUpdate?.(tool) === undefined;
}
@@ -2051,6 +2062,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
new Map(),
);
const nativeBuildConfigurationBySessionId = new Map();
+ const plansBySessionId = new Map();
const initialSessionActivationFailure = yield* Ref.make<{
readonly sessionId: string;
readonly error: EffectAcpErrors.AcpError;
@@ -2375,6 +2387,36 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
// Grok re-prompts on stale monitor notices; suppress output until a genuine terminal or app turn.
const suppressPostSettleMonitorPrompt = yield* Ref.make(false);
const runningBackgroundTaskIds = yield* Ref.make>(new Set());
+ // Background command task id → the completed turn that owns its row. Ended commands stay,
+ // bounded, so a later authoritative terminal still corrects the row on its run.
+ const detachedBackgroundCommands = yield* Ref.make>(
+ new Map(),
+ );
+ const endedDetachedBackgroundCommandLimit = 16;
+ const detachedBackgroundCommandTurn = (taskId: string) =>
+ Ref.get(detachedBackgroundCommands).pipe(Effect.map((turns) => turns.get(taskId)));
+ /** The turn a background task's terminal belongs to: its detached turn, else the live one. */
+ const backgroundCommandTurn = Effect.fnUntraced(function* (taskId: string) {
+ const detached = yield* detachedBackgroundCommandTurn(taskId);
+ if (detached !== undefined) return detached;
+ const active = yield* Ref.get(activeTurn);
+ return active?.finalized === false ? active : undefined;
+ });
+ const detachBackgroundCommands = (context: ActiveAcpTurn) =>
+ Ref.update(detachedBackgroundCommands, (current) => {
+ const next = new Map(current);
+ for (const taskId of context.backgroundCommands.keys()) next.set(taskId, context);
+ const ended = [...next].filter(([taskId, turn]) => {
+ const toolCallId = turn.toolCallIdsByBackgroundTaskId.get(taskId);
+ const tool = toolCallId === undefined ? undefined : turn.tools.get(toolCallId);
+ const status = tool === undefined ? "completed" : toolStatus(tool.status);
+ return status !== "pending" && status !== "running";
+ });
+ for (const [taskId] of ended.slice(0, -endedDetachedBackgroundCommandLimit)) {
+ next.delete(taskId);
+ }
+ return next;
+ });
// Tombstones prevent mid-stream exit_code 0 and stale monitor events from resurrecting ended tasks.
const endedBackgroundTaskIds = yield* Ref.make>(new Set());
const endedBackgroundTaskIdLimit = 128;
@@ -3948,6 +3990,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
if (context.pendingInjectedReport.size > 0) return true;
for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) {
if (context.persistentBackgroundTaskIds.has(taskId)) continue;
+ // Commands are as often a dev server as a wait; only their wake follows up.
+ if (context.backgroundCommands.has(taskId)) continue;
const tool = context.tools.get(toolCallId);
if (tool === undefined) continue;
const status = toolStatus(tool.status);
@@ -4133,14 +4177,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
if (backgroundCompletion.status !== "running") {
context.awaitingBackgroundHydration.delete(backgroundCompletion.taskId);
}
- const targetToolCallId = context.toolCallIdsByBackgroundTaskId.get(
+ const owner = context.toolCallIdsByBackgroundTaskId.has(backgroundCompletion.taskId)
+ ? context
+ : ((yield* detachedBackgroundCommandTurn(backgroundCompletion.taskId)) ?? context);
+ const targetToolCallId = owner.toolCallIdsByBackgroundTaskId.get(
backgroundCompletion.taskId,
);
if (targetToolCallId !== undefined) {
hydratedRegisteredMonitor = true;
}
const target =
- targetToolCallId !== undefined ? context.tools.get(targetToolCallId) : undefined;
+ targetToolCallId !== undefined ? owner.tools.get(targetToolCallId) : undefined;
if (target !== undefined && target.toolCallId !== toolCall.toolCallId) {
const nextStatus =
backgroundCompletion.status === "running"
@@ -4165,14 +4212,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
// completion for settlement when no task_completed recorded one.
if (
backgroundCompletion.status !== "running" &&
- context.backgroundCommands.get(backgroundCompletion.taskId) === null
+ owner.backgroundCommands.get(backgroundCompletion.taskId) === null
) {
- context.backgroundCommands.set(backgroundCompletion.taskId, {
+ owner.backgroundCommands.set(backgroundCompletion.taskId, {
status: backgroundCompletion.status,
output: toolOutputText(hydrated),
});
}
- yield* emitTool(context, hydrated);
+ yield* emitTool(owner, hydrated);
}
}
@@ -4565,30 +4612,51 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const emitPlan = Effect.fnUntraced(function* (
context: ActiveAcpTurn,
update: AcpPlanUpdate,
+ sessionScoped: boolean,
) {
yield* closeTextStreams(context);
- const existing = context.plans.get(update.nativePlanId);
+ let plans = sessionScoped ? plansBySessionId.get(context.nativeThreadId) : context.plans;
+ if (plans === undefined) {
+ plans = new Map();
+ plansBySessionId.set(context.nativeThreadId, plans);
+ }
+ const existing = plans.get(update.nativePlanId);
if (update.kind === "removed" && existing === undefined) return;
- const nativeItemId = `${context.nativeTurnId}:plan:${encodeURIComponent(update.nativePlanId)}`;
- const ordinal = yield* resolveItemOrdinal(context, nativeItemId);
const now = yield* DateTime.now;
- const nodeId = providerNodeId(nativeItemId);
- const turnItemId = providerTurnItemId(nativeItemId);
- const planState = existing ?? {
- id: yield* idAllocator.allocate.plan({
- threadId: context.input.threadId,
- runId: context.input.runId,
- driver,
- }),
- startedAt: now,
- latest: null,
- };
+ let planState = existing;
+ if (planState === undefined) {
+ const nativeItemId = `${context.nativeTurnId}:plan:${encodeURIComponent(update.nativePlanId)}`;
+ planState = {
+ id: yield* idAllocator.allocate.plan({
+ threadId: context.input.threadId,
+ runId: context.input.runId,
+ driver,
+ }),
+ startedAt: now,
+ origin: {
+ runId: context.input.runId,
+ rootNodeId: context.input.rootNodeId,
+ providerThreadId: context.input.providerThread.id,
+ providerTurnId: context.providerTurnId,
+ nativeItemId,
+ ordinal: yield* resolveItemOrdinal(context, nativeItemId),
+ },
+ latest: null,
+ };
+ }
+ const { origin } = planState;
+ const nodeId = providerNodeId(origin.nativeItemId);
+ const turnItemId = providerTurnItemId(origin.nativeItemId);
const planId = planState.id;
- const nativeItemRef = { driver, nativeId: nativeItemId, strength: "weak" as const };
+ const nativeItemRef = {
+ driver,
+ nativeId: origin.nativeItemId,
+ strength: "weak" as const,
+ };
const base = {
id: planId,
threadId: context.input.threadId,
- runId: context.input.runId,
+ runId: origin.runId,
nodeId,
} as const;
let plan: OrchestrationV2PlanArtifact;
@@ -4639,7 +4707,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
};
}
planState.latest = plan;
- context.plans.set(update.nativePlanId, planState);
+ plans.set(update.nativePlanId, planState);
const completed = plan.status === "completed" || plan.status === "superseded";
const nodeKind = plan.kind === "todo_list" ? "todo_list" : "plan";
yield* emitProviderEvent({
@@ -4648,14 +4716,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
node: {
id: nodeId,
threadId: context.input.threadId,
- runId: context.input.runId,
- parentNodeId: context.input.rootNodeId,
- rootNodeId: context.input.rootNodeId,
+ runId: origin.runId,
+ parentNodeId: origin.rootNodeId,
+ rootNodeId: origin.rootNodeId,
kind: nodeKind,
status: completed ? "completed" : "running",
countsForRun: false,
- providerThreadId: context.input.providerThread.id,
- providerTurnId: context.providerTurnId,
+ providerThreadId: origin.providerThreadId,
+ providerTurnId: origin.providerTurnId,
nativeItemRef,
runtimeRequestId: null,
checkpointScopeId: null,
@@ -4670,13 +4738,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
turnItem: {
id: turnItemId,
threadId: context.input.threadId,
- runId: context.input.runId,
+ runId: origin.runId,
nodeId,
- providerThreadId: context.input.providerThread.id,
- providerTurnId: context.providerTurnId,
+ providerThreadId: origin.providerThreadId,
+ providerTurnId: origin.providerTurnId,
nativeItemRef,
parentItemId: null,
- ordinal,
+ ordinal: origin.ordinal,
status: completed ? "completed" : "running",
title: null,
startedAt: planState.startedAt,
@@ -4886,8 +4954,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
readonly status: "completed" | "failed";
readonly output?: string;
}) {
- const context = yield* Ref.get(activeTurn);
- if (context === null || context.finalized || !context.promptSettled) return;
+ const context = yield* backgroundCommandTurn(mutation.taskId);
+ if (context === undefined || !context.promptSettled) return;
const toolCallId = context.toolCallIdsByBackgroundTaskId.get(mutation.taskId);
const tool = toolCallId === undefined ? undefined : context.tools.get(toolCallId);
if (tool === undefined) return;
@@ -4909,6 +4977,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
yield* rearmDeferredFinalize(context);
});
+ // Output and replays for a detached command land on its row, not in the wake buffer.
+ const projectDetachedBackgroundCommand = Effect.fnUntraced(function* (
+ notification: EffectAcpSchema.SessionNotification,
+ active: ActiveAcpTurn | null,
+ ) {
+ const update = notification.update;
+ if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
+ return false;
+ }
+ if (active?.finalized === false && active.tools.has(update.toolCallId)) return false;
+ if (notification.sessionId !== (yield* Ref.get(activeSessionId))) return false;
+ const owner = [...(yield* Ref.get(detachedBackgroundCommands)).values()].find(
+ (turn) => turn.tools.get(update.toolCallId)?.backgroundCommandTaskId !== undefined,
+ );
+ if (owner === undefined) return false;
+ for (const event of parseSessionUpdateEvent(notification).events) {
+ if (event._tag === "ToolCallUpdated") yield* emitTool(owner, event.toolCall);
+ }
+ return true;
+ });
+
const bufferPostSettleWake = Effect.fnUntraced(function* (
notification: EffectAcpSchema.SessionNotification,
) {
@@ -5202,6 +5291,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
)
return;
if (yield* projectAgentTerminalUpdate(notification, context)) return;
+ if (yield* projectDetachedBackgroundCommand(notification, context)) return;
if (
update.sessionUpdate === "usage_update" ||
update.sessionUpdate === "session_info_update"
@@ -5785,7 +5875,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
if (event._tag === "ToolCallUpdated") {
yield* emitTool(context, event.toolCall);
} else if (event._tag === "PlanUpdated") {
- yield* emitPlan(context, event.payload);
+ yield* emitPlan(context, event.payload, update.sessionUpdate !== "plan");
} else if (event._tag === "NoticeReceived") {
yield* emitNotice(context, event);
} else if (event._tag === "UnknownUpdate") {
@@ -7086,12 +7176,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
Effect.gen(function* () {
if (yield* Ref.get(stoppedRunQuarantine)) return;
if ((yield* Ref.get(activeSessionId)) !== incoming.sessionId) return;
- const context = yield* Ref.get(activeTurn);
+ const context = yield* backgroundCommandTurn(incoming.taskId);
let mutation = incoming;
if (
incoming.status !== "running" &&
- context !== null &&
- !context.finalized &&
+ context !== undefined &&
(incoming.report?.kind === "command" ||
context.backgroundCommands.has(incoming.taskId))
) {
@@ -7390,6 +7479,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
yield* Ref.set(wakeReports, noWakeReports);
yield* Ref.set(continuationRequested, false);
yield* Ref.set(runningBackgroundTaskIds, new Set());
+ yield* Ref.set(detachedBackgroundCommands, new Map());
yield* Ref.set(endedBackgroundTaskIds, new Set());
yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set());
yield* Ref.set(handledBackgroundTaskIdsInActiveTurn, new Set());
@@ -7887,6 +7977,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
yield* Ref.set(wakeReports, noWakeReports);
yield* Ref.set(continuationRequested, false);
yield* Ref.set(runningBackgroundTaskIds, new Set());
+ yield* Ref.set(detachedBackgroundCommands, new Map());
yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set());
yield* Ref.set(carryoverSubagents, null);
yield* Ref.set(lastTurnRoute, null);
@@ -8071,6 +8162,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
}
}
yield* Ref.set(activeTurn, null);
+ if (settledStatus === "completed" && !directStopQuarantine) {
+ yield* detachBackgroundCommands(context);
+ }
steerInjections.clear();
if (
postSettleContinuationEnabled &&
diff --git a/packages/provider-core/src/server/McpProviderSessions.ts b/packages/provider-core/src/server/McpProviderSessions.ts
index b9bc89fecb49b..a58498a0c2e7b 100644
--- a/packages/provider-core/src/server/McpProviderSessions.ts
+++ b/packages/provider-core/src/server/McpProviderSessions.ts
@@ -96,6 +96,10 @@ const matchingPageIndex = (kept: ReadonlyArray, input: PageInput
? [index]
: [],
);
+ // Identical pages are interchangeable, so repeats are taken in publish order.
+ if (matches.length > 1 && matches.every((index) => kept[index]!.htmlHash === htmlHash)) {
+ return matches[0]!;
+ }
return matches.length === 1 ? matches[0]! : -1;
};
diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts
index f476bdc70ff80..f2c3092bf17da 100644
--- a/packages/provider-core/src/server/subagentProjection.ts
+++ b/packages/provider-core/src/server/subagentProjection.ts
@@ -61,8 +61,10 @@ export function makeSubagentChildThread(input: {
readonly createdBy: OrchestrationV2Actor;
readonly creationSource: OrchestrationV2CreationSource;
}): OrchestrationV2AppThread {
+ // The remote parent delegated the parent thread, not its subagents.
+ const { delegatedFrom: _delegatedFrom, ...inherited } = input.parentThread;
return {
- ...input.parentThread,
+ ...inherited,
createdBy: input.createdBy,
creationSource: input.creationSource,
id: input.childThreadId,
diff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json
index 95ebdf9a89db0..c105c7c3be364 100644
--- a/packages/provider-cursor/package.json
+++ b/packages/provider-cursor/package.json
@@ -45,7 +45,7 @@
"test": "vp test run --config ../../vite.config.ts --dir ."
},
"dependencies": {
- "@cursor/sdk": "1.2.0",
+ "@cursor/sdk": "1.3.1",
"@t3tools/contracts": "workspace:*",
"@t3tools/provider-core": "workspace:*",
"@t3tools/shared": "workspace:*",
diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts
index 4a62c946f67ea..8809849c53b61 100644
--- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts
+++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts
@@ -162,7 +162,7 @@ describe("CursorAgentSdkRunner", () => {
const platform = yield* Effect.promise(() =>
sdk.createAgentPlatform({ localStore: store, workspaceRef: storeCwd }),
);
- const { agent } = yield* Effect.promise(() =>
+ const { agent, run } = yield* Effect.promise(() =>
platform.store.createAgent({ agentId: "agent-moved", workspaceRef: storeCwd }),
);
const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe(
@@ -182,6 +182,25 @@ describe("CursorAgentSdkRunner", () => {
assert.equal(session.agentId, agent.agentId);
assert.deepStrictEqual(yield* session.listMessages, []);
assert.strictEqual(yield* session.readContextUsage!, undefined);
+
+ // Cursor's conversation holds a run's request only once that run saved its own checkpoint.
+ assert.isFalse(yield* session.runCheckpointed!());
+ yield* Effect.promise(() =>
+ platform.store.patchCheckpoint(agent.agentId, run.runId, {
+ blobId: "checkpoint-1",
+ storeKind: "local",
+ }),
+ );
+ assert.isTrue(yield* session.runCheckpointed!());
+ yield* Effect.promise(() =>
+ platform.store.markRunTerminal(agent.agentId, run.runId, { status: "CANCELLED" }),
+ );
+ const followUp = yield* Effect.promise(() =>
+ platform.store.createFollowUpRun(agent.agentId, {}),
+ );
+ assert.isFalse(yield* session.runCheckpointed!(), "the follow-up has no checkpoint yet");
+ assert.isTrue(yield* session.runCheckpointed!(run.runId));
+ assert.isFalse(yield* session.runCheckpointed!(followUp.runId));
yield* session.close;
}).pipe(Effect.provide(NodeServices.layer)),
);
diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts
index 3162e32a5fd8d..e76d5cf4a6ea8 100644
--- a/packages/provider-cursor/src/server/CursorAgentSdk.ts
+++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts
@@ -3,6 +3,7 @@ import type {
AgentOptions,
InteractionUpdate,
Run,
+ RunRecord,
RunResult,
SDKUserMessage,
SendOptions,
@@ -96,6 +97,8 @@ export interface CursorAgentSdkSendInput {
readonly onDelta?: (update: InteractionUpdate) => Effect.Effect;
/** Runs `agent.summarize()` instead, which takes no message or options. */
readonly summarize?: boolean;
+ /** Runs `agent.resume()`: Cursor's ResumeAction from the latest checkpoint, with no message. */
+ readonly resume?: boolean;
}
export interface CursorAgentSdkRun {
@@ -129,6 +132,11 @@ export interface CursorAgentSdkSession {
CursorContextUsage | undefined,
CursorAgentSdkRunnerError
>;
+ /**
+ * Whether a run (the latest when omitted) saved a checkpoint of its own. Cursor keeps a stopped
+ * run only from its first checkpoint on; before that the conversation lacks the run's request.
+ */
+ readonly runCheckpointed?: (runId?: string) => Effect.Effect;
readonly close: Effect.Effect;
}
@@ -201,6 +209,14 @@ export type CursorAgentSdkProtocolLogEvent =
readonly options: CursorAgentSdkLoggedSendOptions;
};
}
+ | {
+ readonly direction: "outgoing";
+ readonly stage: "decoded";
+ readonly payload: {
+ readonly type: "run.resume";
+ readonly options: CursorAgentSdkLoggedSendOptions;
+ };
+ }
| {
readonly direction: "incoming";
readonly stage: "decoded";
@@ -514,20 +530,31 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
...(input.options.local?.store === undefined ? {} : { store: input.options.local.store }),
};
let abandonedRunRecoveryAvailable = input.operation === "resume";
+ const storeView = async () =>
+ storePlatform ??
+ (await createAgentPlatform({
+ ...(cwd === undefined ? {} : { workspaceRef: cwd }),
+ ...(input.options.local?.store === undefined
+ ? {}
+ : { localStore: input.options.local.store }),
+ }));
return {
agentId: agent.agentId,
send: Effect.fn("CursorAgentSdkSession.send")(function* (sendInput) {
const context = yield* Effect.context();
- yield* log({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "run.start",
- message: sendInput.message,
- options: loggedCursorSendOptions(sendInput.options),
- },
- });
+ const options = loggedCursorSendOptions(sendInput.options);
+ yield* sendInput.resume === true
+ ? log({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: { type: "run.resume", options },
+ })
+ : log({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: { type: "run.start", message: sendInput.message, options },
+ });
let callbacksReady = false;
const pendingUpdates: Array = [];
@@ -560,20 +587,26 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
const startRun = () =>
Effect.tryPromise({
- try: () =>
- sendInput.summarize === true
- ? agent.summarize()
- : agent.send(sendInput.message, {
- ...sendInput.options,
- onDelta: async ({ update }) => {
- if (!callbacksReady) {
- pendingUpdates.push(update);
- return;
- }
- await dispatchUpdate(update);
- },
- }),
- catch: (cause) => runnerError(cause, "run.start"),
+ try: () => {
+ if (sendInput.summarize === true) return agent.summarize();
+ const options: SendOptions = {
+ ...sendInput.options,
+ onDelta: async ({ update }) => {
+ if (!callbacksReady) {
+ pendingUpdates.push(update);
+ return;
+ }
+ await dispatchUpdate(update);
+ },
+ };
+ if (sendInput.resume !== true) return agent.send(sendInput.message, options);
+ if (agent.resume === undefined) {
+ throw new Error("This Cursor SDK agent cannot resume.");
+ }
+ return agent.resume(options);
+ },
+ catch: (cause) =>
+ runnerError(cause, sendInput.resume === true ? "run.resume" : "run.start"),
});
const run = yield* startRun().pipe(
Effect.catchIf(
@@ -767,17 +800,7 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
),
),
readContextUsage: Effect.tryPromise({
- try: async () => {
- const platform =
- storePlatform ??
- (await createAgentPlatform({
- ...(cwd === undefined ? {} : { workspaceRef: cwd }),
- ...(input.options.local?.store === undefined
- ? {}
- : { localStore: input.options.local.store }),
- }));
- return platform.checkpointStore.loadLatest(agent.agentId);
- },
+ try: async () => (await storeView()).checkpointStore.loadLatest(agent.agentId),
catch: (cause) => runnerError(cause, "agent.checkpoint.load"),
}).pipe(
Effect.map((checkpoint) => {
@@ -786,6 +809,31 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
return usage === undefined || usage.maxTokens === 0 ? undefined : usage;
}),
),
+ runCheckpointed: (runId) =>
+ Effect.tryPromise({
+ try: async () => {
+ const { store } = await storeView();
+ let run: RunRecord | null | undefined;
+ if (runId !== undefined) {
+ run = await store.getRun(agent.agentId, runId);
+ } else {
+ let cursor: string | undefined;
+ do {
+ const page = await store.listRuns(
+ agent.agentId,
+ cursor === undefined ? {} : { cursor },
+ );
+ for (const candidate of page.items) {
+ if (!run || candidate.turnNumber >= run.turnNumber) run = candidate;
+ }
+ cursor = page.nextCursor;
+ } while (cursor !== undefined);
+ }
+ const checkpoint = run?.latestCheckpointRef?.blobId;
+ return checkpoint !== undefined && checkpoint !== run?.startCheckpointRef?.blobId;
+ },
+ catch: (cause) => runnerError(cause, "agent.run.get"),
+ }),
close: log({
direction: "outgoing",
stage: "decoded",
diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts
index 38c4119ad94ac..a4cb1a5aa7c63 100644
--- a/packages/provider-cursor/src/server/adapter.test.ts
+++ b/packages/provider-cursor/src/server/adapter.test.ts
@@ -381,7 +381,10 @@ describe("CursorAdapterV2", () => {
model: { id: "claude-fable-5" },
durationMs: 1,
}),
- failure: { class: "transport_error", message: "Provider turn failed." },
+ failure: {
+ class: "transport_error",
+ message: "Error: RetriableError: WritableIterable is closed",
+ },
},
{
reason: "no failure when Cursor's resume after the turn ended made no progress",
@@ -901,11 +904,14 @@ describe("CursorAdapterV2", () => {
),
);
- it.effect("carries an interrupted prompt into the steer that restarts the turn", () =>
+ it.effect("carries a dropped prompt forward, and resumes a checkpointed one natively", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-steer-" });
const sentMessages: Array = [];
+ const resumedRuns: Array = [];
+ // Cursor keeps a cancelled run in the conversation only once it saved a checkpoint.
+ const checkpointedRuns = new Set();
const runEnds: Array> = [];
const instanceId = ProviderInstanceId.make("cursor");
const threadId = ThreadId.make("cursor-steer-thread");
@@ -926,8 +932,15 @@ describe("CursorAdapterV2", () => {
agentId: "native-cursor-steer",
listMessages: Effect.succeed([]),
close: Effect.void,
+ runCheckpointed: (runId) =>
+ Effect.succeed(
+ runId === undefined
+ ? checkpointedRuns.has(`native-cursor-run-${sentMessages.length}`)
+ : checkpointedRuns.has(runId),
+ ),
send: (input) =>
Effect.gen(function* () {
+ if (input.resume === true) resumedRuns.push(sentMessages.length + 1);
sentMessages.push(
typeof input.message === "string" ? input.message : input.message.text,
);
@@ -1008,6 +1021,24 @@ describe("CursorAdapterV2", () => {
attachments: [],
},
});
+ const { message: _message, ...resumeBase } = turnInput(4, "");
+ const resumeInput = (runOrdinal: number) => ({
+ ...resumeBase,
+ runId: RunId.make(`cursor-steer-run-${runOrdinal}`),
+ runOrdinal,
+ providerTurnOrdinal: runOrdinal,
+ attemptId: RunAttemptId.make(`cursor-steer-attempt-${runOrdinal}`),
+ messageId: MessageId.make(`cursor-steer-message-${runOrdinal}`),
+ });
+ const unknown = yield* Effect.flip(runtime.resumeTurn!(resumeInput(1)));
+ assert(unknown._tag === "ProviderAdapterTurnStartError");
+ assert.strictEqual(
+ (unknown.cause as { readonly _tag?: string })._tag,
+ "ProviderResumeUnsupportedError",
+ "nothing Cursor checkpointed and no known stopped request: nothing to resume",
+ );
+ assert.lengthOf(sentMessages, 0);
+
const firstPrompt = "Write me a 1000 word story about a dog.";
const steerText = "No wait, a pig please.";
@@ -1038,6 +1069,59 @@ describe("CursorAdapterV2", () => {
);
yield* runtime.startTurn(turnInput(3, "Now a cow."));
assert.notInclude(sentMessages[2]!, firstPrompt, "a finished turn carries nothing forward");
+
+ const interruptRunning = Effect.gen(function* () {
+ const running = Option.getOrThrow(
+ yield* runtime.events.pipe(
+ Stream.filter(
+ (event) =>
+ event.type === "provider_turn.updated" && event.providerTurn.status === "running",
+ ),
+ Stream.runHead,
+ ),
+ );
+ assert(running.type === "provider_turn.updated");
+ yield* runtime.interruptTurn({ providerThread, providerTurnId: running.providerTurn.id });
+ });
+
+ // Stopped before Cursor checkpointed it: resume replays the exact request Cursor dropped.
+ yield* interruptRunning;
+ yield* runtime.resumeTurn!(resumeInput(4));
+ assert.deepEqual(resumedRuns, []);
+ assert.strictEqual(sentMessages[3], sentMessages[2]);
+
+ // Stopped after a checkpoint: Cursor's own ResumeAction continues it, with no message.
+ checkpointedRuns.add("native-cursor-run-4");
+ yield* interruptRunning;
+ yield* runtime.resumeTurn!(resumeInput(5));
+ assert.deepEqual(resumedRuns, [5]);
+ assert.strictEqual(sentMessages[4], "");
+
+ // The resumed run is stopped before its own checkpoint; the request is still in history.
+ yield* interruptRunning;
+ yield* runtime.resumeTurn!(resumeInput(6));
+ assert.deepEqual(resumedRuns, [5, 6]);
+
+ yield* interruptRunning;
+ yield* runtime.startTurn(turnInput(7, "Make it shorter."));
+ assert.notInclude(
+ sentMessages[6]!,
+ "Now a cow.",
+ "a request Cursor checkpointed is not carried forward",
+ );
+
+ // A turn that ended without a Stop (a usage limit, say) resumes from Cursor's checkpoint,
+ // and stays resumable when that resume is stopped before saving its own.
+ checkpointedRuns.add("native-cursor-run-7");
+ yield* Deferred.succeed(runEnds[6]!, "finished");
+ yield* runtime.events.pipe(
+ Stream.filter((event) => event.type === "turn.terminal" && event.status === "completed"),
+ Stream.runHead,
+ );
+ yield* runtime.resumeTurn!(resumeInput(8));
+ yield* interruptRunning;
+ yield* runtime.resumeTurn!(resumeInput(9));
+ assert.deepEqual(resumedRuns, [5, 6, 8, 9]);
}).pipe(
Effect.scoped,
Effect.provide(
@@ -1746,6 +1830,168 @@ describe("CursorAdapterV2", () => {
),
);
+ it.effect("streams Cursor Task updates into the child thread before the task completes", () =>
+ Effect.gen(function* () {
+ const read = { type: "read" as const, args: { path: "package.json" } };
+ const { events, childThreadId } = yield* runCursorTaskTurn(
+ [
+ { type: "thinking-delta", text: "Reading package.json." },
+ { type: "thinking-completed", thinkingDurationMs: 1 },
+ { type: "text-delta", text: "Looking." },
+ { type: "step-completed", stepId: 1, stepDurationMs: 1 },
+ { type: "text-delta", text: "Reading it." },
+ {
+ type: "tool-call-started",
+ modelCallId: "nested",
+ callId: "nested-read",
+ toolCall: read,
+ },
+ {
+ type: "tool-call-completed",
+ modelCallId: "nested",
+ callId: "nested-read",
+ toolCall: {
+ ...read,
+ result: {
+ status: "success",
+ value: { content: '{"name":"fixture"}', totalLines: 1, fileSize: 18 },
+ },
+ },
+ },
+ ],
+ [
+ { assistantMessage: { text: "Looking." } },
+ { assistantMessage: { text: "Reading it." } },
+ {
+ toolCall: {
+ toolCallId: "nested-read",
+ readToolCall: { args: { path: "package.json" }, result: { success: {} } },
+ },
+ },
+ { assistantMessage: { text: "The name is fixture." } },
+ ],
+ );
+ const taskCompletedAt = events.findIndex(
+ (event) => event.type === "subagent.updated" && event.subagent.status === "completed",
+ );
+ const childItems = events.flatMap((event, index) =>
+ event.type === "turn_item.updated" && event.turnItem.threadId === childThreadId
+ ? [{ index, item: event.turnItem }]
+ : [],
+ );
+ for (const type of ["reasoning", "dynamic_tool", "assistant_message"] as const) {
+ assert.isTrue(
+ childItems.some(({ index, item }) => item.type === type && index < taskCompletedAt),
+ `${type} reached the child thread before the task completed`,
+ );
+ }
+ assert.deepEqual(
+ childItems.flatMap(({ item }): ReadonlyArray =>
+ item.status !== "completed"
+ ? []
+ : item.type === "reasoning" || item.type === "assistant_message"
+ ? [{ type: item.type, text: item.text }]
+ : item.type === "dynamic_tool"
+ ? [{ type: item.type, toolName: item.toolName }]
+ : [],
+ ),
+ [
+ { type: "reasoning", text: "Reading package.json." },
+ { type: "assistant_message", text: "Looking." },
+ { type: "assistant_message", text: "Reading it." },
+ { type: "dynamic_tool", toolName: "Read" },
+ { type: "assistant_message", text: "The name is fixture." },
+ ],
+ );
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
+ ),
+ ),
+ );
+
+ it.effect("fills a Cursor Task child from its saved steps where live updates fell short", () =>
+ Effect.gen(function* () {
+ const { events, childThreadId } = yield* runCursorTaskTurn(
+ [
+ { type: "step-started", stepId: 1 },
+ {
+ type: "tool-call-started",
+ modelCallId: "nested",
+ callId: "open",
+ toolCall: { type: "read", args: { path: "open.json" } },
+ },
+ {
+ type: "tool-call-started",
+ modelCallId: "nested",
+ callId: "lost",
+ toolCall: { type: "read", args: { path: "lost.json" } },
+ },
+ {
+ type: "tool-call-completed",
+ modelCallId: "nested",
+ callId: "live",
+ toolCall: {
+ type: "read",
+ args: { path: "live.json" },
+ result: {
+ status: "success",
+ value: { content: "{}", totalLines: 1, fileSize: 2 },
+ },
+ },
+ },
+ { type: "step-completed", stepId: 1, stepDurationMs: 1 },
+ ],
+ [
+ {
+ toolCall: {
+ toolCallId: "open",
+ readToolCall: { args: { path: "open.json" }, result: { success: {} } },
+ },
+ },
+ {
+ toolCall: {
+ toolCallId: "live",
+ readToolCall: { args: { path: "live.json" }, result: { success: {} } },
+ },
+ },
+ {
+ toolCall: {
+ toolCallId: "saved",
+ readToolCall: { args: { path: "saved.json" }, result: { success: {} } },
+ },
+ },
+ { assistantMessage: { text: "Saved answer." } },
+ ],
+ );
+ const finalItems = new Map();
+ for (const event of events) {
+ if (event.type !== "turn_item.updated" || event.turnItem.threadId !== childThreadId) {
+ continue;
+ }
+ const item = event.turnItem;
+ if (item.type === "dynamic_tool") {
+ finalItems.set(item.title ?? "", item.status);
+ } else if (item.type === "assistant_message") {
+ finalItems.set(item.text, item.status);
+ }
+ }
+ assert.deepEqual(Object.fromEntries(finalItems), {
+ "Read open.json": "completed",
+ "Read lost.json": "interrupted",
+ "Read live.json": "completed",
+ "Read saved.json": "completed",
+ "Saved answer.": "completed",
+ });
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
+ ),
+ ),
+ );
+
it.effect("keeps the last 256 KiB of streamed shell output when the result carries none", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -2728,6 +2974,155 @@ describe("CursorAdapterV2", () => {
});
});
+type CursorTaskUpdate = Extract<
+ InteractionUpdate,
+ { readonly type: "tool-call-delta" }
+>["taskUpdate"];
+
+// Runs one Cursor turn whose only tool is a Task that streams `taskUpdates`, then completes with
+// `conversationSteps` as the saved transcript.
+const runCursorTaskTurn = Effect.fnUntraced(function* (
+ taskUpdates: ReadonlyArray,
+ conversationSteps: ReadonlyArray,
+) {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-task-" });
+ const instanceId = ProviderInstanceId.make("cursor");
+ const threadId = ThreadId.make("cursor-task-thread");
+ const modelSelection = { instanceId, model: "composer-2.5" };
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: workspace,
+ });
+ const args = {
+ description: "Explore",
+ prompt: "Read package.json.",
+ subagentType: { kind: "unspecified" as const },
+ agentId: "cursor-task-agent",
+ mode: "unspecified" as const,
+ };
+ const adapter = yield* makeCursorAdapterV2({
+ instanceId,
+ environment: { HOME: workspace },
+ }).pipe(
+ Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
+ assertComplete: Effect.void,
+ open: () =>
+ Effect.succeed({
+ agentId: "native-cursor-task",
+ listMessages: Effect.succeed([]),
+ close: Effect.void,
+ send: (input) =>
+ Effect.gen(function* () {
+ yield* input.onDelta!({
+ type: "tool-call-started",
+ modelCallId: "model-call",
+ callId: "task-call",
+ toolCall: { type: "task", args },
+ });
+ for (const taskUpdate of taskUpdates) {
+ yield* input.onDelta!({
+ type: "tool-call-delta",
+ modelCallId: "model-call",
+ callId: "task-call",
+ taskUpdate,
+ });
+ }
+ yield* input.onDelta!({
+ type: "tool-call-completed",
+ modelCallId: "model-call",
+ callId: "task-call",
+ toolCall: {
+ type: "task",
+ args,
+ result: {
+ status: "success",
+ value: {
+ conversationSteps: [...conversationSteps],
+ isBackground: false,
+ backgroundReason: "unspecified",
+ },
+ },
+ },
+ });
+ return {
+ agentId: "native-cursor-task",
+ runId: "native-cursor-run",
+ wait: Effect.succeed({
+ id: "native-cursor-run",
+ requestId: "native-request",
+ status: "finished" as const,
+ model: { id: "composer-2.5" },
+ durationMs: 1,
+ }),
+ cancel: Effect.void,
+ };
+ }).pipe(Effect.orDie),
+ }),
+ }),
+ Effect.provide(TestProviderHost.layer({ cwd: workspace })),
+ );
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("cursor-task-session"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
+ const now = yield* DateTime.now;
+ yield* runtime.startTurn({
+ threadId,
+ providerThread,
+ modelSelection,
+ runtimePolicy,
+ runId: RunId.make("cursor-task-run"),
+ runOrdinal: 1,
+ providerTurnOrdinal: 1,
+ attemptId: RunAttemptId.make("cursor-task-attempt"),
+ rootNodeId: NodeId.make("cursor-task-root"),
+ appThread: {
+ id: threadId,
+ projectId: ProjectId.make("cursor-task-project"),
+ createdBy: "user",
+ creationSource: "web",
+ title: "Cursor subagent",
+ providerInstanceId: instanceId,
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: providerThread.id,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ message: {
+ messageId: MessageId.make("cursor-task-message"),
+ createdBy: "user",
+ creationSource: "web",
+ text: "Spawn a subagent.",
+ attachments: [],
+ },
+ });
+ const events = yield* runtime.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.runCollect,
+ );
+ assert.equal(events.find((event) => event.type === "turn.terminal")?.status, "completed");
+ const childThreadId = events.findLast((event) => event.type === "subagent.updated")?.subagent
+ .childThreadId;
+ assert.isDefined(childThreadId);
+ return { events, childThreadId };
+});
+
const scopedProcessEnv = (values: Record) =>
Effect.acquireRelease(
Effect.sync(() => {
diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts
index 496a2bd5460e8..90c55675af296 100644
--- a/packages/provider-cursor/src/server/adapter.ts
+++ b/packages/provider-cursor/src/server/adapter.ts
@@ -937,11 +937,18 @@ interface ActiveCursorSubagent {
readonly turnItemOrdinal: number;
nextChildOrdinal: number;
resultProjected: boolean;
+ // Nested tools and text Cursor streamed live; the completion transcript fills in only the rest.
+ readonly liveToolCallIds: Set;
+ streamedAssistantText: string;
+ readonly tools: Map;
+ readonly assistant: ActiveCursorTextStream;
+ readonly reasoning: ActiveCursorTextStream;
}
interface ActiveCursorTextSegment {
readonly nativeItemId: string;
readonly startedAt: DateTime.Utc;
+ readonly ordinal: number;
text: string;
}
@@ -962,8 +969,9 @@ interface ActiveCursorTurn {
readonly assistant: ActiveCursorTextStream;
assistantReply: CursorTransportFailure;
readonly reasoning: ActiveCursorTextStream;
- /** The user text this run sent, before runtime instructions; absent for /compress. */
+ /** The user text this run sent, before runtime instructions; absent for /compress and resume. */
readonly prompt: string | undefined;
+ readonly message: string | SDKUserMessage;
interrupted: boolean;
finalized: boolean;
/** The agent's latest turn ended and no new work has started since. */
@@ -1047,11 +1055,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
readonly orchestration: boolean;
readonly device: boolean;
} | null>(null);
- // Cursor drops a cancelled run from the conversation, so the next message carries its prompt.
+ // Cursor drops a run cancelled before its first checkpoint, so the next message carries its prompt.
const interruptedPrompt = yield* Ref.make<{
readonly agent: string;
+ readonly runId: string;
readonly text: string;
+ readonly message: string | SDKUserMessage;
} | null>(null);
+ // A native resume's own run may stop before it checkpoints; the request is still in history.
+ const resumedAgent = yield* Ref.make(null);
const warnedUnsupportedSandbox = yield* Ref.make(false);
const activeTurn = yield* Ref.make(null);
const planIds = yield* Ref.make(new Map());
@@ -1100,16 +1112,24 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
providerTurnId: context.providerTurnId,
});
+ const childProjectionTarget = (subagent: ActiveCursorSubagent): CursorProjectionTarget => ({
+ threadId: subagent.childThreadId,
+ runId: null,
+ rootNodeId: subagent.childRootNodeId,
+ parentNodeId: subagent.childRootNodeId,
+ providerThreadId: null,
+ providerTurnId: null,
+ });
+
const emitAssistant = Effect.fnUntraced(function* (
- context: ActiveCursorTurn,
+ target: CursorProjectionTarget,
+ segment: ActiveCursorTextSegment | null,
completed: boolean,
) {
- const segment = context.assistant.current;
if (segment === null || segment.text.length === 0) {
return;
}
const now = yield* DateTime.now;
- const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver: CursorAgentSdk.CURSOR_PROVIDER,
nativeItemId: segment.nativeItemId,
@@ -1132,15 +1152,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
driver: CursorAgentSdk.CURSOR_PROVIDER,
node: {
id: nodeId,
- threadId: context.input.threadId,
- runId: context.input.runId,
- parentNodeId: context.input.rootNodeId,
- rootNodeId: context.input.rootNodeId,
+ threadId: target.threadId,
+ runId: target.runId,
+ parentNodeId: target.parentNodeId,
+ rootNodeId: target.rootNodeId,
kind: "assistant_message",
status: completed ? "completed" : "running",
countsForRun: false,
- providerThreadId: context.input.providerThread.id,
- providerTurnId: context.providerTurnId,
+ providerThreadId: target.providerThreadId,
+ providerTurnId: target.providerTurnId,
nativeItemRef,
runtimeRequestId: null,
checkpointScopeId: null,
@@ -1155,8 +1175,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
createdBy: "agent",
creationSource: "provider",
id: messageId,
- threadId: context.input.threadId,
- runId: context.input.runId,
+ threadId: target.threadId,
+ runId: target.runId,
nodeId,
role: "assistant",
text: segment.text,
@@ -1171,14 +1191,14 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
driver: CursorAgentSdk.CURSOR_PROVIDER,
turnItem: {
id: turnItemId,
- threadId: context.input.threadId,
- runId: context.input.runId,
+ threadId: target.threadId,
+ runId: target.runId,
nodeId,
- providerThreadId: context.input.providerThread.id,
- providerTurnId: context.providerTurnId,
+ providerThreadId: target.providerThreadId,
+ providerTurnId: target.providerTurnId,
nativeItemRef,
parentItemId: null,
- ordinal,
+ ordinal: segment.ordinal,
status: completed ? "completed" : "running",
title: null,
startedAt: segment.startedAt,
@@ -1193,15 +1213,14 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
});
const emitReasoning = Effect.fnUntraced(function* (
- context: ActiveCursorTurn,
+ target: CursorProjectionTarget,
+ segment: ActiveCursorTextSegment | null,
completed: boolean,
) {
- const segment = context.reasoning.current;
if (segment === null || segment.text.length === 0) {
return;
}
const now = yield* DateTime.now;
- const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver: CursorAgentSdk.CURSOR_PROVIDER,
nativeItemId: segment.nativeItemId,
@@ -1220,15 +1239,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
driver: CursorAgentSdk.CURSOR_PROVIDER,
node: {
id: nodeId,
- threadId: context.input.threadId,
- runId: context.input.runId,
- parentNodeId: context.input.rootNodeId,
- rootNodeId: context.input.rootNodeId,
+ threadId: target.threadId,
+ runId: target.runId,
+ parentNodeId: target.parentNodeId,
+ rootNodeId: target.rootNodeId,
kind: "reasoning",
status: completed ? "completed" : "running",
countsForRun: false,
- providerThreadId: context.input.providerThread.id,
- providerTurnId: context.providerTurnId,
+ providerThreadId: target.providerThreadId,
+ providerTurnId: target.providerTurnId,
nativeItemRef,
runtimeRequestId: null,
checkpointScopeId: null,
@@ -1241,14 +1260,14 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
driver: CursorAgentSdk.CURSOR_PROVIDER,
turnItem: {
id: turnItemId,
- threadId: context.input.threadId,
- runId: context.input.runId,
+ threadId: target.threadId,
+ runId: target.runId,
nodeId,
- providerThreadId: context.input.providerThread.id,
- providerTurnId: context.providerTurnId,
+ providerThreadId: target.providerThreadId,
+ providerTurnId: target.providerTurnId,
nativeItemRef,
parentItemId: null,
- ordinal,
+ ordinal: segment.ordinal,
status: completed ? "completed" : "running",
title: null,
startedAt: segment.startedAt,
@@ -1269,9 +1288,11 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
}) {
if (input.stream.current === null) {
input.stream.nextSegment += 1;
+ const nativeItemId = `${input.kind}:${input.context.run.runId}:${input.stream.nextSegment}`;
input.stream.current = {
- nativeItemId: `${input.kind}:${input.context.run.runId}:${input.stream.nextSegment}`,
+ nativeItemId,
startedAt: yield* DateTime.now,
+ ordinal: yield* resolveItemOrdinal(input.context, nativeItemId),
text: "",
};
}
@@ -1282,7 +1303,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
if (context.assistant.current === null) {
return;
}
- yield* emitAssistant(context, true);
+ yield* emitAssistant(parentTarget(context), context.assistant.current, true);
context.assistant.current = null;
});
@@ -1290,7 +1311,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
if (context.reasoning.current === null) {
return;
}
- yield* emitReasoning(context, true);
+ yield* emitReasoning(parentTarget(context), context.reasoning.current, true);
context.reasoning.current = null;
});
@@ -1704,12 +1725,11 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
? "failed"
: "completed"
: "running");
- const resultText = [
+ const resultParts = [
...assistantTextsFromConversationSteps(result?.conversationSteps ?? []),
...(result?.resultSuffix === undefined ? [] : [result.resultSuffix]),
- ]
- .filter((part) => part.trim().length > 0)
- .join("\n");
+ ].filter((part) => part.trim().length > 0);
+ const resultText = resultParts.join("\n");
const nativeItemId = input.callId;
const nodeId =
existing?.task.id ??
@@ -1778,6 +1798,11 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
existing?.turnItemOrdinal ?? (yield* resolveItemOrdinal(input.context, nativeItemId)),
nextChildOrdinal: existing?.nextChildOrdinal ?? 100,
resultProjected: existing?.resultProjected ?? false,
+ liveToolCallIds: existing?.liveToolCallIds ?? new Set(),
+ streamedAssistantText: existing?.streamedAssistantText ?? "",
+ tools: existing?.tools ?? new Map(),
+ assistant: existing?.assistant ?? { current: null, nextSegment: 0 },
+ reasoning: existing?.reasoning ?? { current: null, nextSegment: 0 },
};
input.context.subagents.set(input.callId, subagent);
@@ -1917,29 +1942,48 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
});
if (input.completed && !subagent.resultProjected) {
- for (const [index, nestedTool] of toolCallsFromConversationSteps(
- result?.conversationSteps ?? [],
- ).entries()) {
+ yield* completeSubagentReasoning(subagent);
+ yield* completeSubagentAssistant(subagent);
+ // A tool with neither a live completion nor a saved step has an unknown outcome.
+ const unfinishedStatus =
+ status === "interrupted" || status === "failed" || status === "cancelled"
+ ? status
+ : "interrupted";
+ const savedTools = toolCallsFromConversationSteps(result?.conversationSteps ?? []);
+ for (const tool of subagent.tools.values()) {
+ const saved = savedTools.find(
+ (nestedTool) => `${nativeItemId}:child-tool:${nestedTool.callId}` === tool.callId,
+ );
+ if (saved !== undefined) {
+ tool.toolCall = saved.toolCall;
+ }
+ yield* emitToolArtifacts({
+ active: tool,
+ completed: true,
+ ...(saved === undefined ? { unfinishedStatus } : {}),
+ });
+ }
+ subagent.tools.clear();
+ for (const [index, nestedTool] of savedTools.entries()) {
+ if (subagent.liveToolCallIds.has(nestedTool.callId)) {
+ continue;
+ }
const callId = `${nativeItemId}:child-tool:${nestedTool.callId || index + 1}`;
const startedAt = task.startedAt ?? now;
const active: ActiveCursorToolCall = {
callId,
toolCall: nestedTool.toolCall,
- target: {
- threadId: childThreadId,
- runId: null,
- rootNodeId: childRootNodeId,
- parentNodeId: childRootNodeId,
- providerThreadId: null,
- providerTurnId: null,
- },
+ target: childProjectionTarget(subagent),
ordinal: ++subagent.nextChildOrdinal,
startedAt,
streamedOutput: "",
};
yield* emitToolArtifacts({ active, completed: true });
}
- if (task.result !== null && task.result.length > 0) {
+ const unstreamedResult = resultParts
+ .filter((part) => !subagent.streamedAssistantText.includes(part.trim()))
+ .join("\n");
+ if (unstreamedResult.length > 0) {
const resultNativeId = `${nativeItemId}:result`;
const resultArtifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
@@ -1960,7 +2004,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
strength: "weak",
},
role: "assistant",
- text: task.result,
+ text: unstreamedResult,
ordinal: ++subagent.nextChildOrdinal,
now,
});
@@ -1979,6 +2023,125 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
}
});
+ const appendSubagentText = Effect.fnUntraced(function* (input: {
+ readonly subagent: ActiveCursorSubagent;
+ readonly stream: ActiveCursorTextStream;
+ readonly kind: "assistant" | "reasoning";
+ readonly text: string;
+ }) {
+ if (input.stream.current === null) {
+ input.stream.nextSegment += 1;
+ input.stream.current = {
+ nativeItemId: `${input.subagent.callId}:${input.kind}:${input.stream.nextSegment}`,
+ startedAt: yield* DateTime.now,
+ ordinal: ++input.subagent.nextChildOrdinal,
+ text: "",
+ };
+ }
+ input.stream.current.text += input.text;
+ });
+
+ const completeSubagentAssistant = Effect.fnUntraced(function* (
+ subagent: ActiveCursorSubagent,
+ ) {
+ if (subagent.assistant.current === null) {
+ return;
+ }
+ yield* emitAssistant(childProjectionTarget(subagent), subagent.assistant.current, true);
+ subagent.assistant.current = null;
+ });
+
+ const completeSubagentReasoning = Effect.fnUntraced(function* (
+ subagent: ActiveCursorSubagent,
+ ) {
+ if (subagent.reasoning.current === null) {
+ return;
+ }
+ yield* emitReasoning(childProjectionTarget(subagent), subagent.reasoning.current, true);
+ subagent.reasoning.current = null;
+ });
+
+ const handleTaskUpdate = Effect.fnUntraced(function* (
+ context: ActiveCursorTurn,
+ update: Extract,
+ ) {
+ const subagent = context.subagents.get(update.callId);
+ if (subagent === undefined || !isOrchestrationV2WorkActive(subagent.task.status)) {
+ return;
+ }
+ const taskUpdate = update.taskUpdate;
+ switch (taskUpdate.type) {
+ case "text-delta":
+ subagent.streamedAssistantText += taskUpdate.text;
+ yield* completeSubagentReasoning(subagent);
+ yield* appendSubagentText({
+ subagent,
+ stream: subagent.assistant,
+ kind: "assistant",
+ text: taskUpdate.text,
+ });
+ yield* emitAssistant(
+ childProjectionTarget(subagent),
+ subagent.assistant.current,
+ false,
+ );
+ return;
+ case "thinking-delta":
+ yield* completeSubagentAssistant(subagent);
+ yield* appendSubagentText({
+ subagent,
+ stream: subagent.reasoning,
+ kind: "reasoning",
+ text: taskUpdate.text,
+ });
+ yield* emitReasoning(
+ childProjectionTarget(subagent),
+ subagent.reasoning.current,
+ false,
+ );
+ return;
+ case "thinking-completed":
+ yield* completeSubagentReasoning(subagent);
+ return;
+ case "step-completed":
+ yield* completeSubagentAssistant(subagent);
+ yield* completeSubagentReasoning(subagent);
+ return;
+ case "tool-call-started":
+ case "partial-tool-call":
+ case "tool-call-completed": {
+ subagent.liveToolCallIds.add(taskUpdate.callId);
+ yield* completeSubagentAssistant(subagent);
+ yield* completeSubagentReasoning(subagent);
+ const nestedCallId = `${subagent.callId}:child-tool:${taskUpdate.callId}`;
+ const completed = taskUpdate.type === "tool-call-completed";
+ let active = subagent.tools.get(nestedCallId);
+ if (active === undefined) {
+ active = {
+ callId: nestedCallId,
+ toolCall: taskUpdate.toolCall,
+ target: childProjectionTarget(subagent),
+ ordinal: ++subagent.nextChildOrdinal,
+ startedAt: yield* DateTime.now,
+ streamedOutput: "",
+ };
+ subagent.tools.set(nestedCallId, active);
+ yield* emitToolArtifacts({ active, completed: false });
+ }
+ active.toolCall = taskUpdate.toolCall;
+ if (taskUpdate.type !== "tool-call-started") {
+ yield* emitToolArtifacts({ active, completed });
+ }
+ if (completed) {
+ subagent.tools.delete(nestedCallId);
+ }
+ return;
+ }
+ default:
+ return;
+ }
+ });
+
const handleToolUpdate = Effect.fnUntraced(function* (
context: ActiveCursorTurn,
update: Extract<
@@ -2058,7 +2221,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
update.type === "text-delta" ||
update.type === "thinking-delta" ||
update.type === "partial-tool-call" ||
- update.type === "tool-call-started"
+ update.type === "tool-call-started" ||
+ update.type === "tool-call-delta"
) {
context.turnEnded = false;
}
@@ -2077,7 +2241,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
kind: "assistant",
text: update.text,
});
- yield* emitAssistant(context, false);
+ yield* emitAssistant(parentTarget(context), context.assistant.current, false);
return;
case "thinking-delta":
yield* completeAssistant(context);
@@ -2087,7 +2251,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
kind: "reasoning",
text: update.text,
});
- yield* emitReasoning(context, false);
+ yield* emitReasoning(parentTarget(context), context.reasoning.current, false);
return;
case "thinking-completed":
yield* completeReasoning(context);
@@ -2099,6 +2263,9 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
yield* completeReasoning(context);
yield* handleToolUpdate(context, update);
return;
+ case "tool-call-delta":
+ yield* handleTaskUpdate(context, update);
+ return;
case "step-completed":
case "turn-ended":
yield* completeAssistant(context);
@@ -2290,7 +2457,9 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
if (input.status === "interrupted" && input.context.prompt !== undefined) {
yield* Ref.set(interruptedPrompt, {
agent: input.context.run.agentId,
+ runId: input.context.run.runId,
text: input.context.prompt,
+ message: input.context.message,
});
}
yield* Ref.update(activeTurn, (current) =>
@@ -2542,14 +2711,44 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
? known
: { orchestration: turnInput.runOrdinal > 1, device: false };
const interrupted = yield* Ref.get(interruptedPrompt);
- const { message, prompt } = yield* resolveUserMessage(
- turnInput,
- mcpServers,
- hasDeviceTools,
- delivered,
- interrupted?.agent === agent.nativeThreadId ? interrupted.text : undefined,
- );
- const compacted = prompt === undefined;
+ const runCheckpointed = (runId?: string) =>
+ agent.session.runCheckpointed?.(runId) ?? Effect.succeed(false);
+ const dropped =
+ interrupted?.agent === agent.nativeThreadId &&
+ !(yield* runCheckpointed(interrupted.runId))
+ ? interrupted
+ : undefined;
+ // Cursor's ResumeAction continues from the latest checkpoint, which only holds a stopped
+ // request once that run checkpointed; an earlier stop replays the request it dropped.
+ const resume =
+ turnInput.resume !== true
+ ? undefined
+ : dropped !== undefined
+ ? ("replay" as const)
+ : interrupted?.agent === agent.nativeThreadId ||
+ (yield* Ref.get(resumedAgent)) === agent.nativeThreadId ||
+ (yield* runCheckpointed())
+ ? ("native" as const)
+ : undefined;
+ if (turnInput.resume === true && resume === undefined) {
+ return yield* new ProviderAdapter.ProviderResumeUnsupportedError({
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
+ providerThreadId: turnInput.providerThread.id,
+ });
+ }
+ const { message, prompt } =
+ resume === "native"
+ ? { message: "", prompt: undefined }
+ : resume === "replay"
+ ? { message: dropped!.message, prompt: dropped!.text }
+ : yield* resolveUserMessage(
+ turnInput,
+ mcpServers,
+ hasDeviceTools,
+ delivered,
+ dropped?.text,
+ );
+ const compacted = resume === undefined && prompt === undefined;
const pendingUpdates: Array = [];
let context: ActiveCursorTurn | null = null;
// A send-time set replaces the create-time set, so the workspace servers go only here and are
@@ -2562,6 +2761,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
.send({
message,
summarize: compacted,
+ resume: resume === "native",
options: {
model: cursorSdkModelSelection(
turnInput.modelSelection,
@@ -2582,14 +2782,20 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
},
})
.pipe(Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection)));
- yield* Ref.set(told, {
- agent: agent.nativeThreadId,
- orchestration: !compacted && (delivered.orchestration || mcpServers !== undefined),
- device: !compacted && hasDeviceTools,
- });
- if (!compacted) {
+ // A resume sends no new instructions, and a native one still continues the stopped request.
+ if (resume === undefined) {
+ yield* Ref.set(told, {
+ agent: agent.nativeThreadId,
+ orchestration: !compacted && (delivered.orchestration || mcpServers !== undefined),
+ device: !compacted && hasDeviceTools,
+ });
+ }
+ if (!compacted && resume !== "native") {
yield* Ref.set(interruptedPrompt, null);
}
+ if (!compacted) {
+ yield* Ref.set(resumedAgent, resume === "native" ? agent.nativeThreadId : null);
+ }
const startedAt = yield* DateTime.now;
const completed = yield* Deferred.make();
const providerTurnId = idAllocator.derive.providerTurn({
@@ -2615,6 +2821,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
nextSegment: 0,
},
prompt,
+ message,
interrupted: false,
finalized: false,
turnEnded: false,
@@ -2696,7 +2903,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
: "provider_error",
})
: makeProviderFailure({
- cause: transportFailure,
+ message: transportFailure,
class: "transport_error",
}),
}
@@ -2847,6 +3054,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
),
),
startTurn,
+ resumeTurn: (input) => startTurn(ProviderAdapter.resumeTurnInput(input)),
compactThread: (turnInput) =>
startTurn({
...turnInput,
diff --git a/packages/provider-cursor/src/server/status.test.ts b/packages/provider-cursor/src/server/status.test.ts
index 82651cc254326..0ce81df747e30 100644
--- a/packages/provider-cursor/src/server/status.test.ts
+++ b/packages/provider-cursor/src/server/status.test.ts
@@ -7,11 +7,13 @@ import * as TestClock from "effect/testing/TestClock";
import type { CursorSettings } from "../settings.ts";
import { CursorSettings as CursorSettingsSchema } from "../settings.ts";
import { createModelCapabilities } from "@t3tools/shared/model";
+import { COMPACT_SLASH_COMMAND } from "@t3tools/provider-core/server/snapshotProbe";
import {
buildCursorCapabilitiesFromSdkModel,
buildCursorDiscoveredModelsFromSdk,
buildCursorProviderSnapshot,
+ buildInitialCursorProviderSnapshot,
checkCursorProviderStatus,
} from "./status.ts";
import * as CursorSdkCatalog from "./CursorSdkCatalog.ts";
@@ -96,6 +98,19 @@ const sdkParameterizedModel = {
],
} satisfies SDKModel;
+describe("buildInitialCursorProviderSnapshot", () => {
+ it.effect.each([true, false])("advertises manual compaction only when enabled (%s)", (enabled) =>
+ Effect.gen(function* () {
+ const provider = yield* buildInitialCursorProviderSnapshot({
+ ...baseCursorSettings,
+ enabled,
+ });
+
+ expect(provider.slashCommands).toEqual(enabled ? [COMPACT_SLASH_COMMAND] : []);
+ }),
+ );
+});
+
describe("buildCursorProviderSnapshot", () => {
it("downgrades ready status to warning when SDK model discovery returns no models", () => {
expect(
@@ -113,6 +128,7 @@ describe("buildCursorProviderSnapshot", () => {
status: "warning",
message: "Cursor SDK model discovery returned no built-in models.",
models: [],
+ slashCommands: [COMPACT_SLASH_COMMAND],
supportsConversationRollback: false,
});
});
@@ -196,6 +212,7 @@ describe("checkCursorProviderStatus", () => {
expect(provider).toMatchObject({
status: "ready",
+ slashCommands: [COMPACT_SLASH_COMMAND],
auth: {
status: "authenticated",
type: "api-key",
diff --git a/packages/provider-cursor/src/server/status.ts b/packages/provider-cursor/src/server/status.ts
index 7c0167579f20b..570a7ac34f453 100644
--- a/packages/provider-cursor/src/server/status.ts
+++ b/packages/provider-cursor/src/server/status.ts
@@ -19,6 +19,7 @@ import {
buildBooleanOptionDescriptor,
buildSelectOptionDescriptor,
buildServerProvider,
+ COMPACT_SLASH_COMMAND,
providerModelsFromSettings,
type ServerProviderDraft,
} from "@t3tools/provider-core/server/snapshotProbe";
@@ -62,6 +63,7 @@ export const buildInitialCursorProviderSnapshot = Effect.fn(
enabled: true,
checkedAt,
models,
+ slashCommands: [COMPACT_SLASH_COMMAND],
probe: {
installed: true,
version: null,
@@ -236,6 +238,7 @@ export function buildCursorProviderSnapshot(input: {
input.cursorSettings.customModels,
EMPTY_CAPABILITIES,
),
+ slashCommands: [COMPACT_SLASH_COMMAND],
probe: {
installed: true,
version: input.parsed.version,
diff --git a/packages/provider-grok/src/server/usage.test.ts b/packages/provider-grok/src/server/usage.test.ts
index 1ed6585a31f73..867e0ccd6fbb0 100644
--- a/packages/provider-grok/src/server/usage.test.ts
+++ b/packages/provider-grok/src/server/usage.test.ts
@@ -72,7 +72,9 @@ describe("parseGrokLine", () => {
reasoningTokens: 180,
});
expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
- expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok-4.5-build");
+ expect(record?.dedupeKey).toBe(
+ "019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:1786372566485:grok-4.5-build",
+ );
});
it("emits one record per model when modelUsage has several entries", () => {
@@ -142,7 +144,9 @@ describe("parseGrokLine", () => {
reasoningTokens: 180,
});
expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
- expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok");
+ expect(record?.dedupeKey).toBe(
+ "019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:1786372566485:grok",
+ );
});
it("pro-rates top-level cost ticks across multi-model turns without per-model ticks", () => {
@@ -230,6 +234,17 @@ describe("parseGrokLine", () => {
expect(parseGrokLine(line)[0]?.dedupeKey).toBeNull();
});
+ it("keeps later turns that reuse a prompt id after the session resumes in a new process", () => {
+ const first = parseGrokLine(turnCompleted({ promptId: "t3-xai-prompt-1" }))[0];
+ const resumed = parseGrokLine(
+ turnCompleted({ promptId: "t3-xai-prompt-1", agentTimestampMs: 1_786_459_000_000 }),
+ )[0];
+ const copied = parseGrokLine(turnCompleted({ promptId: "t3-xai-prompt-1" }))[0];
+
+ expect(resumed?.dedupeKey).not.toBe(first?.dedupeKey);
+ expect(copied?.dedupeKey).toBe(first?.dedupeKey);
+ });
+
it("ignores non-turn lines and empty usage", () => {
expect(parseGrokLine(JSON.stringify({ method: "session/update", params: {} }))).toEqual([]);
expect(parseGrokLine("not json")).toEqual([]);
diff --git a/packages/provider-grok/src/server/usage.ts b/packages/provider-grok/src/server/usage.ts
index 52d5b600ba091..1e0b75cc796b1 100644
--- a/packages/provider-grok/src/server/usage.ts
+++ b/packages/provider-grok/src/server/usage.ts
@@ -92,6 +92,7 @@ function parseGrokRecord(parsed: unknown): readonly UsageRecord[] {
const usageRecord = usage as Record;
const sessionId = typeof paramsRecord["sessionId"] === "string" ? paramsRecord["sessionId"] : "";
+ // T3's prompt ids restart with each Grok process, so a resumed session reuses them.
const promptId = typeof updateRecord["prompt_id"] === "string" ? updateRecord["prompt_id"] : null;
const meta = paramsRecord["_meta"];
@@ -136,7 +137,7 @@ function parseGrokRecord(parsed: unknown): readonly UsageRecord[] {
reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks),
speed: "standard",
// No prompt id means we cannot tell two same-second updates apart.
- dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:grok`,
+ dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${timestampMs}:grok`,
},
];
}
@@ -174,7 +175,8 @@ function parseGrokRecord(parsed: unknown): readonly UsageRecord[] {
totals,
reportedCostUsd,
speed: "standard",
- dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${entry.model}`,
+ dedupeKey:
+ promptId === null ? null : `${sessionId}:${promptId}:${timestampMs}:${entry.model}`,
});
}
return results;
diff --git a/packages/provider-opencode/src/server/toolItems.ts b/packages/provider-opencode/src/server/toolItems.ts
index 606788f088554..bb1bb3b9a7010 100644
--- a/packages/provider-opencode/src/server/toolItems.ts
+++ b/packages/provider-opencode/src/server/toolItems.ts
@@ -1,4 +1,5 @@
import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
+import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender";
import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity";
import {
@@ -122,6 +123,26 @@ export function openCodeCommandFailed(toolName: string, completedMetadata: unkno
);
}
+/** Code Mode reports nested calls with their input but no result, so pages are found by input. */
+export function openCodeCodeModeHtmlRenders(
+ completedMetadata: unknown,
+ mcpServerName: string,
+): ReadonlyArray<{ readonly index: number; readonly input: Record }> {
+ if (typeof completedMetadata !== "object" || completedMetadata === null) return [];
+ const toolCalls = (completedMetadata as Record