Compare commits

..
Author SHA1 Message Date
Theo Browne 6923a71376 Guard concurrent task tab creation 2026-07-27 03:23:17 -07:00
Theo Browne 44499ae62f Fix lazy activity projection comparison 2026-07-27 03:21:41 -07:00
Theo Browne 76f7bd1e57 Merge remote-tracking branch 'origin/main' into t3code/task-tabs-context-fork 2026-07-27 03:20:42 -07:00
Theo Browne 0273d5d63b Restore closed server task tabs 2026-07-27 03:15:52 -07:00
Alex Southwell b4680cbfd0 perf(mobile): defer work-log detail serialization (#4607) 2026-07-27 03:03:49 -07:00
Theo Browne f7bcc489f9 Polish task tabs and restore closed tabs 2026-07-27 03:02:05 -07:00
Theo Browne d60f6e971f fix: cut websocket throughput in half by pruning activity payloads (#4622) 2026-07-27 02:56:34 -07:00
Theo Browne ad25d0b247 Merge remote-tracking branch 'origin/main' into t3code/task-tabs-context-fork 2026-07-27 02:33:21 -07:00
Theo Browne 89c5a192f4 fix(dev): skip browser-blocked ports (#4608) 2026-07-26 20:26:21 -07:00
Theo BrowneandClaude Opus 5 23b5502217 feat(dev): Make t3 code dev instances shareable over Tailscale (#4556)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-07-26 19:48:09 -07:00
Theo BrowneandClaude Opus 5 a17cbc3b40 feat(dev): keep worktree dev state isolated on T3 Code dev servers (#4555)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-07-26 15:26:59 -07:00
Theo BrowneandClaude Opus 5 5719e8ac40 feat(web): show fast mode as a bolt instead of a "Normal" label (#4488)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-07-24 19:28:37 -07:00
Theo Browne c8cf535780 polish task tab context UI 2026-07-24 16:54:54 -07:00
jan 38cfc25e54 feat(web): add collapse-all toggle to diff panel (#4475) 2026-07-24 18:15:45 -04:00
41a430a88e Add Claude Opus 5 model (#4472)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-07-24 13:16:33 -07:00
Theo Browne 9b5063bcd4 fix: preserve task tab invariants 2026-07-24 07:54:30 -07:00
Theo Browne 0ed495a122 feat(sidebar-v2): add task tabs and context forks 2026-07-24 07:43:45 -07:00
Julius Marmingeandcodex ece05087a7 [codex] Fix glass hover compositing artifacts (#4446)
Co-authored-by: codex <[email protected]>
2026-07-24 12:25:01 +00:00
Julius Marmingeandcodex a7ee3092c3 Color settled PR labels on hover (#4451)
Co-authored-by: codex <[email protected]>
2026-07-24 14:08:39 +02:00
Julius Marmingeandcodex f7cc776488 Restore model picker layout and retain iterative test state (#4450)
Co-authored-by: codex <[email protected]>
2026-07-24 14:01:47 +02:00
Julius Marminge 15e875a2d9 Increase light-mode contrast for user message bubbles (#4441) 2026-07-24 10:02:36 +00:00
Julius Marminge 5d173547ff Upgrade Clerk packages and Expo integration (#4440) 2026-07-24 11:21:19 +02:00
183 changed files with 8554 additions and 15339 deletions

No files matched your search

+35 -5
View File
@@ -1,6 +1,6 @@
---
name: test-t3-app
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
description: Launch, retain, and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, cross-turn dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, iteratively test UI behavior with a human, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
---
# Test T3 App
@@ -13,13 +13,35 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
2. Choose a base directory that belongs only to the current worktree or test:
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
3. Start the full web stack with `vp run dev`. Add `--share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.
Ports are derived from the worktree path but can shift when occupied. Always read the actual values from the `[dev-runner]` line.
Shared browser dev is single-origin: Vite proxies the backend paths, so never set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
### Verify a shared environment before human handoff
When another person will use the printed pairing URL, first open the shared origin without the pairing path or fragment in the controlled browser and confirm the T3 Code app loads. This browser navigation is required even when curl succeeds because browsers block some otherwise reachable ports before making a network request.
Do not open the other person's complete pairing URL during this reachability check; doing so consumes its one-time token. If the agent also needs an authenticated browser, create and consume a separate pairing token, then leave a fresh token for the other person.
## Preserve the environment while iterating
Treat the overall testing or implementation loop—not an assistant turn or one verification pass—as the environment lifecycle boundary.
- Keep the dev process, base directory, selected ports, authenticated browser tab, registered projects, and seeded fixtures alive while the user may inspect the result or request follow-up changes.
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
## Authenticate the browser on the first navigation
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
@@ -45,7 +67,7 @@ T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
## Inspect or seed SQLite state
@@ -58,9 +80,17 @@ Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before chang
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
## Finish the test
## Tear down only when the testing loop is finished
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
Tear down when the user explicitly asks, confirms the iteration is finished, or the overall task is genuinely complete with no pending human review. Do not infer completion from the end of an assistant turn.
When teardown is appropriate:
1. Stop the dev process with its terminal interrupt.
2. Preserve the isolated base directory when it contains useful reproduction evidence or state for a likely follow-up.
3. Otherwise remove only a path created for this test after resolving and verifying the exact target.
If completion is uncertain, keep the environment alive and mention that it is retained for further iteration. A fresh isolated base directory remains the safest reset when authentication, migrations, or fixture state becomes ambiguous.
## Troubleshoot predictably
@@ -1,4 +1,4 @@
interface:
display_name: "T3 App Testing"
short_description: "Launch and seed isolated T3 test environments"
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
short_description: "Launch and retain isolated T3 test environments"
default_prompt: "Use $test-t3-app to launch an isolated T3 environment and iteratively test it in the browser while preserving state."
-2
View File
@@ -35,5 +35,3 @@ node_modules/
*.log
.env*
!.env.example
__pycache__/
*.py[cod]
File diff suppressed because it is too large. Load diff
+8
View File
@@ -13,6 +13,14 @@
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## Dev Servers
- In a linked git worktree, dev state defaults to that worktree's gitignored `.t3`. This deliberately outranks an ambient `T3CODE_HOME`, which could otherwise select the installed app's live `~/.t3/userdata` database. An explicit `--home-dir` still wins.
- Start the web stack with `vp run dev`. Add `--share` when someone needs to open it from another device on the tailnet.
- Browser dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
- Worktree paths supply stable preferred port offsets. Read the actual server and web ports from the `[dev-runner]` line because occupied ports can still shift them.
- Before handing off a `--share` URL, open its origin in a controlled browser and confirm the app loads. A successful curl is insufficient because browsers reject some otherwise reachable ports.
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
@@ -108,7 +108,8 @@ export function ThreadWorkLog(props: {
<View className="gap-px">
{rows.map((row) => {
const expanded = props.expandedRows[row.id] ?? false;
const canExpand = row.fullDetail !== null;
const canExpand = row.canExpand;
const fullDetail = expanded ? row.getFullDetail() : null;
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
@@ -133,7 +134,7 @@ export function ThreadWorkLog(props: {
props.onToggleRow(row.id);
}
}}
onLongPress={() => props.onCopyRow(row.id, row.copyText)}
onLongPress={() => props.onCopyRow(row.id, row.getCopyText())}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
@@ -204,7 +205,7 @@ export function ThreadWorkLog(props: {
</View>
</Pressable>
{expanded && row.fullDetail ? (
{fullDetail ? (
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
<ScrollView
nestedScrollEnabled
@@ -217,7 +218,7 @@ export function ThreadWorkLog(props: {
selectable
className="font-mono text-2xs leading-normal text-foreground-muted"
>
{row.fullDetail}
{fullDetail}
</Text>
</ScrollView>
</View>
+68 -18
View File
@@ -161,20 +161,22 @@ describe("buildThreadFeed", () => {
return;
}
expect(group.activities).toEqual([
{
id: "tool-completed",
createdAt: "2026-04-01T00:00:02.000Z",
turnId: "turn-1",
summary: "Run tests",
detail: "bun run test",
fullDetail: "/bin/zsh -lc 'bun run test'",
copyText: "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
icon: "command",
toolLike: true,
status: "success",
},
]);
expect(group.activities).toHaveLength(1);
expect(group.activities[0]).toMatchObject({
id: "tool-completed",
createdAt: "2026-04-01T00:00:02.000Z",
turnId: "turn-1",
summary: "Run tests",
detail: "bun run test",
canExpand: true,
icon: "command",
toolLike: true,
status: "success",
});
expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'");
expect(group.activities[0]?.getCopyText()).toBe(
"Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
);
});
it("keeps MCP inputs available to expanded mobile work rows", () => {
@@ -223,8 +225,55 @@ describe("buildThreadFeed", () => {
}
expect(group.activities[0]?.icon).toBe("wrench");
expect(group.activities[0]?.fullDetail).toContain('"query": "work log"');
expect(group.activities[0]?.fullDetail).toContain("repository.search");
expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"');
expect(group.activities[0]?.getFullDetail()).toContain("repository.search");
});
it("defers large tool output expansion until a work row is opened or copied", () => {
let serializedToolOutputs = 0;
const activities = Array.from({ length: 5_000 }, (_, index) =>
makeActivity({
id: EventId.make(`large-tool-${index}`),
kind: "tool.completed",
tone: "tool",
summary: `Tool ${index}`,
createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(),
payload: {
title: `Tool ${index}`,
itemType: "mcp_tool_call",
status: "completed",
data: {
item: {
toJSON: () => {
serializedToolOutputs += 1;
return { output: "x".repeat(32_768) };
},
},
},
},
}),
);
const thread = makeThread({
id: ThreadId.make("thread-large-tools"),
projectId: ProjectId.make("project-1"),
title: "Large tools",
activities,
});
const feed = buildThreadFeed(thread);
expect(serializedToolOutputs).toBe(0);
const group = feed[0];
expect(group).toMatchObject({ type: "activity-group" });
if (!group || group.type !== "activity-group") {
return;
}
expect(group.activities).toHaveLength(5_000);
expect(group.activities[0]?.getFullDetail()).toContain('"output"');
expect(serializedToolOutputs).toBe(1);
expect(group.activities[0]?.getCopyText()).toContain('"output"');
expect(serializedToolOutputs).toBe(1);
});
it("folds settled turn work while leaving the terminal answer visible", () => {
@@ -439,8 +488,9 @@ describe("buildThreadFeed", () => {
turnId: null,
summary: `Tool ${id}`,
detail: null,
fullDetail: null,
copyText: id,
canExpand: false,
getFullDetail: () => null,
getCopyText: () => id,
icon: "command",
toolLike: true,
status,
+35 -9
View File
@@ -36,8 +36,9 @@ export interface ThreadFeedActivity {
readonly turnId: TurnId | null;
readonly summary: string;
readonly detail: string | null;
readonly fullDetail: string | null;
readonly copyText: string;
readonly canExpand: boolean;
readonly getFullDetail: () => string | null;
readonly getCopyText: () => string;
readonly icon:
| "agent"
| "alert"
@@ -554,6 +555,27 @@ function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
return blocks.length > 0 ? blocks.join("\n\n") : null;
}
function workEntryHasExpandedBody(entry: WorkLogEntry): boolean {
return (
(entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) ||
Boolean((entry.rawCommand ?? entry.command)?.trim()) ||
Boolean(entry.detail?.trim()) ||
(entry.changedFiles?.some((path) => path.trim().length > 0) ?? false)
);
}
function memoizeValue<T>(build: () => T): () => T {
let value: T;
let initialized = false;
return () => {
if (!initialized) {
value = build();
initialized = true;
}
return value;
};
}
function workEntryPreview(
workEntry: Pick<WorkLogEntry, "detail" | "command" | "changedFiles">,
): string | null {
@@ -1353,7 +1375,14 @@ export function buildThreadFeed(
.map<RawThreadFeedEntry>((entry) => {
const summary = workEntryHeading(entry);
const detail = workEntryPreview(entry);
const fullDetail = buildWorkEntryExpandedBody(entry);
const getFullDetail = memoizeValue(() => buildWorkEntryExpandedBody(entry));
const getCopyText = memoizeValue(() =>
[summary, detail, getFullDetail()]
.filter((value, index, values): value is string => {
return Boolean(value) && values.indexOf(value) === index;
})
.join("\n"),
);
return {
type: "activity",
id: entry.id,
@@ -1365,13 +1394,10 @@ export function buildThreadFeed(
turnId: entry.turnId,
summary,
detail,
fullDetail,
canExpand: workEntryHasExpandedBody(entry),
getFullDetail,
getCopyText,
icon: workEntryIcon(entry),
copyText: [summary, detail, fullDetail]
.filter((value, index, values): value is string => {
return Boolean(value) && values.indexOf(value) === index;
})
.join("\n"),
toolLike: workLogEntryIsToolLike(entry),
status: workEntryStatus(entry),
},
+15 -36
View File
@@ -8,9 +8,13 @@ import * as ServerConfig from "../config.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import { resolveSessionCookieName } from "./utils.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
/** Pinned so dev-mode cookie tests can assert the port-scoped name. */
const TEST_SERVER_PORT = 13_773;
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
Layer.effect(
ServerConfig.ServerConfig,
@@ -18,8 +22,13 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
const config = yield* ServerConfig.ServerConfig;
return {
...config,
port: 3773,
...overrides,
// Last, so the port cannot be overridden out from under
// makeCookieRequest — which builds the cookie name from this constant.
// An override that changed it would leave the server reading
// t3_session_<other> while every request still sent t3_session_13773,
// and the tests would fail for a reason unrelated to what they assert.
port: TEST_SERVER_PORT,
} satisfies ServerConfig.ServerConfig["Service"];
}),
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
@@ -33,11 +42,14 @@ const makeEnvironmentAuthLayer = (overrides?: Partial<ServerConfig.ServerConfig[
const makeCookieRequest = (
sessionToken: string,
cookieName = "t3_session",
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
({
cookies: {
[cookieName]: sessionToken,
// Derived, not hardcoded: the name is port-scoped so concurrent servers
// on one hostname don't share a cookie. Mode and devUrl mirror
// ServerConfig.layerTest, so this resolves to whatever the server reads.
[resolveSessionCookieName({ mode: "web", port: TEST_SERVER_PORT, devUrl: undefined })]:
sessionToken,
},
headers: {},
}) as unknown as Parameters<
@@ -102,39 +114,6 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
}).pipe(Effect.provide(makeEnvironmentAuthLayer())),
);
it.effect("uses the port-specific web cookie when sibling instance cookies are present", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const pairingCredential = yield* serverAuth.issuePairingCredential();
const exchanged = yield* serverAuth.createBrowserSession(
pairingCredential.credential,
requestMetadata,
);
const request = {
cookies: {
t3_session: "session-owned-by-the-canonical-instance",
t3_session_7446: exchanged.sessionToken,
},
headers: {},
} as unknown as Parameters<
EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]
>[0];
const verified = yield* serverAuth.authenticateHttpRequest(request);
expect(verified.sessionId.length).toBeGreaterThan(0);
expect(verified.subject).toBe("one-time-token");
}).pipe(
Effect.provide(
makeEnvironmentAuthLayer({
mode: "web",
port: 13773,
authCookiePort: 7446,
}),
),
),
);
it.effect("does not exchange ordinary pairing grants for administrative access tokens", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
+5
View File
@@ -438,6 +438,7 @@ export class EnvironmentAuth extends Context.Service<
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly subject?: string;
readonly proofKeyThumbprint?: string;
readonly purpose?: "startup";
}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
@@ -746,11 +747,13 @@ export const make = Effect.gen(function* () {
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly subject: string;
readonly label?: string;
readonly purpose?: "startup";
}) =>
createPairingLink({
scopes: input.scopes,
subject: input.subject,
...(input.label ? { label: input.label } : {}),
...(input.purpose ? { purpose: input.purpose } : {}),
}).pipe(
Effect.map(
(issued) =>
@@ -774,6 +777,7 @@ export const make = Effect.gen(function* () {
...(input?.ttl ? { ttl: input.ttl } : {}),
...(input?.label ? { label: input.label } : {}),
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
...(input?.purpose ? { purpose: input.purpose } : {}),
});
return {
id: issued.id,
@@ -872,6 +876,7 @@ export const make = Effect.gen(function* () {
issuePairingCredentialForSubject({
scopes: AuthAdministrativeScopes,
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
purpose: "startup",
}).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
@@ -34,6 +34,9 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
expect(descriptor.policy).toBe("desktop-managed-local");
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
// Packaged desktop has no devUrl, but still needs the port scope: it
// scans upward from 3773 for a free port and binds 127.0.0.1, so a second
// instance shares this one's hostname on a different port.
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
}).pipe(
Effect.provide(
@@ -45,6 +48,22 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
),
);
it.effect("keeps desktop cookies port-scoped on the port a second instance lands on", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.sessionCookieName).toBe("t3_session_3774");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "desktop",
port: 3774,
}),
),
),
);
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
@@ -70,47 +89,29 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
expect(descriptor.policy).toBe("loopback-browser");
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
expect(descriptor.sessionCookieName).toBe("t3_session");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "web",
host: "127.0.0.1",
port: 3773,
}),
),
),
);
it.effect("isolates browser session cookies for web servers on non-default ports", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.sessionCookieName).toBe("t3_session_7446");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "web",
host: "127.0.0.1",
port: 7446,
}),
),
),
);
it.effect("uses the browser-facing port when a reverse proxy changes the port", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.sessionCookieName).toBe("t3_session_7446");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "web",
host: "127.0.0.1",
port: 13773,
authCookiePort: 7446,
}),
),
),
);
it.effect("scopes web session cookies by port only in development", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "web",
port: 13773,
devUrl: new URL("http://127.0.0.1:5733"),
}),
),
),
@@ -40,7 +40,8 @@ export const make = Effect.gen(function* () {
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
sessionCookieName: resolveSessionCookieName({
mode: config.mode,
port: config.authCookiePort ?? config.port,
port: config.port,
devUrl: config.devUrl,
}),
};
+18 -1
View File
@@ -202,6 +202,11 @@ export class PairingGrantStore extends Context.Service<
readonly subject?: string;
readonly label?: string;
readonly proofKeyThumbprint?: string;
/**
* "startup" marks the credential the server mints for itself at boot,
* which gets the long dev TTL when a dev URL is configured.
*/
readonly purpose?: "startup";
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthPairingLink>,
@@ -243,6 +248,15 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
// window can still recover by re-bootstrapping rather than locking
// the user out of the backend.
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
// A dev server's startup token is read off a log by whoever (or whatever) is
// driving the session, often minutes later — after a `node --watch` restart, a
// detour into another task, or a hand-off to the person actually doing the
// testing. Five minutes turns that into a restart-the-server loop for no
// security benefit: the token only unlocks a local dev backend, and its holder
// could read the log anyway. Same reasoning (and duration) as the desktop
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
// pairing links and real servers keep the 5-minute default.
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const PAIRING_TOKEN_LENGTH = 12;
const PAIRING_TOKEN_REJECTION_LIMIT =
@@ -371,7 +385,10 @@ export const make = Effect.gen(function* () {
),
);
const credential = yield* generatePairingToken;
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
const ttl =
input?.ttl ??
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
const issued: IssuedBootstrapCredential = {
+2 -1
View File
@@ -469,7 +469,8 @@ export const make = Effect.gen(function* () {
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
port: serverConfig.authCookiePort ?? serverConfig.port,
port: serverConfig.port,
devUrl: serverConfig.devUrl,
});
const emitUpsert = (clientSession: AuthClientSession) =>
+1 -17
View File
@@ -1,22 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { deriveAuthClientMetadata, resolveSessionCookieName } from "./utils.ts";
describe("resolveSessionCookieName", () => {
it("preserves the legacy cookie name for the canonical web port", () => {
expect(resolveSessionCookieName({ mode: "web", port: 3773 })).toBe("t3_session");
});
it("isolates web sessions on non-default ports", () => {
expect(resolveSessionCookieName({ mode: "web", port: 7446 })).toBe("t3_session_7446");
expect(resolveSessionCookieName({ mode: "web", port: 7447 })).toBe("t3_session_7447");
});
it("keeps desktop sessions isolated by port", () => {
expect(resolveSessionCookieName({ mode: "desktop", port: 3773 })).toBe("t3_session_3773");
expect(resolveSessionCookieName({ mode: "desktop", port: 7446 })).toBe("t3_session_7446");
});
});
import { deriveAuthClientMetadata } from "./utils.ts";
describe("deriveAuthClientMetadata", () => {
it("labels Electron user agents as Electron instead of Chrome", () => {
+19 -7
View File
@@ -8,19 +8,31 @@ import * as NodeCrypto from "node:crypto";
import * as Encoding from "effect/Encoding";
import * as Result from "effect/Result";
import { DEFAULT_PORT } from "../config.ts";
const SESSION_COOKIE_NAME = "t3_session";
/**
* Cookies are scoped by host but *not* by port, so any two servers that can be
* live on one hostname at once need separate names — otherwise the second
* clobbers the first's session and both sides see "Invalid session token
* signature" until someone clears cookies by hand.
*
* Two populations qualify, for the same reason but from different causes:
*
* - **Dev servers** (`devUrl` set), which run several at a time across worktrees.
* - **Desktop**, which scans upward from 3773 for a free port and binds
* 127.0.0.1, so a second instance lands on a different port and the same host.
*
* Hosted deployments keep the stable production name: their public port can
* change between releases, and scoping it would log every user out.
*/
export function resolveSessionCookieName(input: {
readonly mode: "web" | "desktop";
readonly port: number;
readonly devUrl: URL | undefined;
}): string {
if (input.mode === "web" && input.port === DEFAULT_PORT) {
return SESSION_COOKIE_NAME;
}
return `${SESSION_COOKIE_NAME}_${input.port}`;
return input.devUrl === undefined && input.mode !== "desktop"
? SESSION_COOKIE_NAME
: `${SESSION_COOKIE_NAME}_${input.port}`;
}
export function base64UrlEncode(input: string | Uint8Array): string {
+1
View File
@@ -84,6 +84,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
...derivedPaths,
staticDir: undefined,
devUrl: undefined,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
@@ -83,6 +83,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -191,6 +193,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -274,6 +278,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -342,6 +348,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -395,6 +403,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
+4 -5
View File
@@ -48,6 +48,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
devAllowedOrigins: [],
} as const;
const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
@@ -92,10 +93,11 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
T3CODE_LOG_LEVEL: "Warn",
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_AUTH_COOKIE_PORT: "7446",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_DEV_ALLOWED_ORIGINS:
"https://host.example.ts.net, https://phone.example.ts.net ",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "true",
@@ -112,13 +114,13 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
...defaultObservabilityConfig,
mode: "desktop",
port: 4001,
authCookiePort: 7446,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "0.0.0.0",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
devAllowedOrigins: ["https://host.example.ts.net", "https://phone.example.ts.net"],
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
@@ -143,7 +145,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
{
mode: Option.some("web"),
port: Option.some(8788),
authCookiePort: Option.some(9443),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
@@ -165,7 +166,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
T3CODE_LOG_LEVEL: "Warn",
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_AUTH_COOKIE_PORT: "7446",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: join(NodeOS.tmpdir(), "ignored-base"),
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
@@ -185,7 +185,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
...defaultObservabilityConfig,
mode: "web",
port: 8788,
authCookiePort: 9443,
cwd: process.cwd(),
baseDir,
...derivedPaths,
+10 -25
View File
@@ -26,13 +26,6 @@ export const portFlag = Flag.integer("port").pipe(
Flag.withDescription("Port for the HTTP/WebSocket server."),
Flag.optional,
);
export const authCookiePortFlag = Flag.integer("auth-cookie-port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription(
"Browser-facing port used to namespace auth cookies when a reverse proxy exposes a different port.",
),
Flag.optional,
);
export const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
Flag.optional,
@@ -110,13 +103,18 @@ const EnvServerConfig = Config.all({
Config.map(Option.getOrUndefined),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
authCookiePort: Config.port("T3CODE_AUTH_COOKIE_PORT").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
devAllowedOrigins: Config.string("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
Config.withDefault(""),
Config.map((value) =>
value
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0),
),
),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
Config.option,
Config.map(Option.getOrUndefined),
@@ -146,7 +144,6 @@ const EnvServerConfig = Config.all({
export interface CliServerFlags {
readonly mode: Option.Option<ServerConfig.RuntimeMode>;
readonly port: Option.Option<number>;
readonly authCookiePort?: Option.Option<number>;
readonly host: Option.Option<string>;
readonly baseDir: Option.Option<string>;
readonly cwd: Option.Option<string>;
@@ -176,7 +173,6 @@ export const projectLocationFlags = {
export const sharedServerCommandFlags = {
mode: modeFlag,
port: portFlag,
authCookiePort: authCookiePortFlag,
host: hostFlag,
baseDir: baseDirFlag,
cwd: Argument.string("cwd").pipe(
@@ -227,7 +223,6 @@ export const resolveServerConfig = (
const normalizedFlags = {
mode: flags.mode ?? Option.none(),
port: flags.port ?? Option.none(),
authCookiePort: flags.authCookiePort ?? Option.none(),
host: flags.host ?? Option.none(),
baseDir: flags.baseDir ?? Option.none(),
cwd: flags.cwd ?? Option.none(),
@@ -271,12 +266,6 @@ export const resolveServerConfig = (
},
},
);
const explicitlyConfiguredAuthCookiePort = Option.getOrUndefined(
resolveOptionPrecedence(
normalizedFlags.authCookiePort,
Option.fromUndefinedOr(env.authCookiePort),
),
);
const devUrl = Option.getOrElse(
resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
() => undefined,
@@ -346,9 +335,6 @@ export const resolveServerConfig = (
),
() => 443,
);
const authCookiePort =
explicitlyConfiguredAuthCookiePort ??
(tailscaleServeEnabled ? tailscaleServePort : undefined);
const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
@@ -379,7 +365,6 @@ export const resolveServerConfig = (
otlpServiceName: env.otlpServiceName,
mode,
port,
...(authCookiePort !== undefined ? { authCookiePort } : {}),
cwd,
baseDir,
...derivedPaths,
@@ -387,6 +372,7 @@ export const resolveServerConfig = (
host,
staticDir,
devUrl,
devAllowedOrigins: env.devAllowedOrigins,
noBrowser,
startupPresentation,
desktopBootstrapToken,
@@ -407,7 +393,6 @@ export const resolveCliAuthConfig = (
{
mode: Option.none(),
port: Option.none(),
authCookiePort: Option.none(),
host: Option.none(),
baseDir: flags.baseDir,
cwd: Option.none(),
+2 -1
View File
@@ -67,12 +67,12 @@ export class ServerConfig extends Context.Service<
readonly otlpServiceName: string;
readonly mode: RuntimeMode;
readonly port: number;
readonly authCookiePort?: number;
readonly host: string | undefined;
readonly cwd: string;
readonly baseDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly devAllowedOrigins: ReadonlyArray<string>;
readonly noBrowser: boolean;
readonly startupPresentation: StartupPresentation;
readonly desktopBootstrapToken: string | undefined;
@@ -188,6 +188,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
desktopBootstrapToken: undefined,
staticDir: undefined,
devUrl,
devAllowedOrigins: [],
noBrowser: false,
startupPresentation: "browser",
});
@@ -43,6 +43,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
desktopBootstrapToken: undefined,
staticDir: undefined,
devUrl: undefined,
devAllowedOrigins: [],
noBrowser: false,
startupPresentation: "browser",
} satisfies ServerConfig.ServerConfig["Service"];
@@ -68,6 +69,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(first.environmentId).toBe(second.environmentId);
expect(second.capabilities.repositoryIdentity).toBe(true);
expect(second.capabilities.connectionProbe).toBe(true);
expect(second.capabilities.workspaceTaskTabs).toBe(true);
}),
);
@@ -142,6 +142,7 @@ export const make = Effect.gen(function* () {
connectionProbe: true,
threadSettlement: true,
threadSnooze: true,
workspaceTaskTabs: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
},
};
+14 -1
View File
@@ -4,6 +4,7 @@ import {
AuthOrchestrationReadScope,
EnvironmentHttpApi,
} from "@t3tools/contracts";
import { isDevProxiedPath } from "@t3tools/shared/devProxy";
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
@@ -48,9 +49,17 @@ export const browserApiCorsLayer = Layer.unwrap(
const devOrigin = config.devUrl?.origin;
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
//
// T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
// origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
// through Vite and is same-origin (no preflight at all), so this is a
// safety net for the desktop renderer and any direct-to-backend caller.
return HttpRouter.cors({
...(devOrigin
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
? {
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
credentials: true,
}
: {}),
allowedMethods: browserApiCorsAllowedMethods,
allowedHeaders: browserApiCorsAllowedHeaders,
@@ -216,6 +225,10 @@ export const staticAndDevRouteLayer = HttpRouter.add(
}
const config = yield* ServerConfig.ServerConfig;
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
status: 302,
+2
View File
@@ -198,6 +198,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("chat.newTab"), "mod+t");
assert.equal(defaultsByCommand.get("chat.reopenClosedTab"), "mod+shift+t");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
@@ -0,0 +1,227 @@
import type {
OrchestrationEvent,
OrchestrationThreadActivity,
OrchestrationThreadDetailSnapshot,
} from "@t3tools/contracts";
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function asTrimmedString(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function pushChangedFile(target: string[], seen: Set<string>, value: unknown): void {
const normalized = asTrimmedString(value);
if (!normalized || seen.has(normalized)) {
return;
}
seen.add(normalized);
target.push(normalized);
}
function collectChangedFiles(
value: unknown,
target: string[],
seen: Set<string>,
depth: number,
): void {
if (depth > 4 || target.length >= 12) {
return;
}
if (Array.isArray(value)) {
for (const entry of value) {
collectChangedFiles(entry, target, seen, depth + 1);
if (target.length >= 12) {
return;
}
}
return;
}
const record = asRecord(value);
if (!record) {
return;
}
pushChangedFile(target, seen, record.path);
pushChangedFile(target, seen, record.filePath);
pushChangedFile(target, seen, record.relativePath);
pushChangedFile(target, seen, record.filename);
pushChangedFile(target, seen, record.newPath);
pushChangedFile(target, seen, record.oldPath);
for (const nestedKey of [
"item",
"result",
"input",
"data",
"changes",
"files",
"edits",
"patch",
"patches",
"operations",
]) {
if (!(nestedKey in record)) {
continue;
}
collectChangedFiles(record[nestedKey], target, seen, depth + 1);
if (target.length >= 12) {
return;
}
}
}
function projectCommandData(data: Record<string, unknown>): Record<string, unknown> | undefined {
const item = asRecord(data.item);
if (!item) {
return undefined;
}
const projectedItem: Record<string, unknown> = {};
if ("command" in item) {
projectedItem.command = item.command;
}
const input = asRecord(item.input);
if (input && "command" in input) {
projectedItem.input = { command: input.command };
}
const result = asRecord(item.result);
if (result && "command" in result) {
projectedItem.result = { command: result.command };
}
return Object.keys(projectedItem).length > 0 ? projectedItem : undefined;
}
function summarizeToolTextOutput(value: string): string | null {
const lines: string[] = [];
for (const rawLine of value.split(/\r?\n/u)) {
const line = rawLine.replace(/\s+/g, " ").trim();
if (line.length > 0) {
lines.push(line);
}
}
const firstLine = lines.find((line) => line !== "```");
if (firstLine) {
return firstLine.length <= 84 ? firstLine : `${firstLine.slice(0, 83).trimEnd()}…`;
}
if (lines.length > 1) {
return `${lines.length.toLocaleString()} lines`;
}
return null;
}
function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
const rawOutput = asRecord(value);
if (!rawOutput) {
return undefined;
}
if (typeof rawOutput.totalFiles === "number" && Number.isFinite(rawOutput.totalFiles)) {
return {
totalFiles: rawOutput.totalFiles,
...(rawOutput.truncated === true ? { truncated: true } : {}),
};
}
const content = asTrimmedString(rawOutput.content);
if (content) {
const summary = summarizeToolTextOutput(content);
return summary ? { content: summary } : undefined;
}
const stdout = asTrimmedString(rawOutput.stdout);
if (stdout) {
const summary = summarizeToolTextOutput(stdout);
return summary ? { content: summary } : undefined;
}
return undefined;
}
/**
* Removes activity payload fields that no current client reads while retaining
* the full payload in persistence and the event store.
*/
export function projectActivityPayload(
activity: OrchestrationThreadActivity,
): OrchestrationThreadActivity {
const payload = asRecord(activity.payload);
const data = asRecord(payload?.data);
if (!payload || !data || payload.itemType === "mcp_tool_call") {
return activity;
}
const projectedData: Record<string, unknown> = {};
const item = projectCommandData(data);
if (item) {
projectedData.item = item;
}
if ("command" in data) {
projectedData.command = data.command;
}
const changedFiles: string[] = [];
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
if (changedFiles.length > 0) {
// Both clients discover file names by walking objects with path-like keys.
projectedData.files = changedFiles.map((path) => ({ path }));
}
if ("toolCallId" in data) {
projectedData.toolCallId = data.toolCallId;
}
if ("kind" in data) {
projectedData.kind = data.kind;
}
const rawOutput = projectRawOutput(data.rawOutput);
if (rawOutput) {
projectedData.rawOutput = rawOutput;
}
return {
...activity,
payload: {
...payload,
data: projectedData,
},
};
}
export function projectThreadDetailSnapshot(
snapshot: OrchestrationThreadDetailSnapshot,
): OrchestrationThreadDetailSnapshot {
return {
...snapshot,
thread: {
...snapshot.thread,
activities: snapshot.thread.activities.map(projectActivityPayload),
},
};
}
export function projectActivityEvent(event: OrchestrationEvent): OrchestrationEvent {
if (event.type !== "thread.activity-appended") {
return event;
}
return {
...event,
payload: {
...event.payload,
activity: projectActivityPayload(event.payload.activity),
},
};
}
@@ -192,6 +192,7 @@ describe("OrchestrationEngine", () => {
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getClosedTaskTabs: () => Effect.succeed([]),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
@@ -1652,117 +1652,6 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("replaces an assistant snapshot between legacy appended deltas", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-07-24T12:00:00.000Z";
const projectId = ProjectId.make("project-replacement");
const threadId = ThreadId.make("thread-replacement");
const messageId = MessageId.make("assistant-replacement");
yield* eventStore.append({
type: "project.created",
eventId: EventId.make("evt-replacement-1"),
aggregateKind: "project",
aggregateId: projectId,
occurredAt: now,
commandId: CommandId.make("cmd-replacement-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-replacement-1"),
metadata: {},
payload: {
projectId,
title: "Project Replacement",
workspaceRoot: "/tmp/project-replacement",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-replacement-2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-replacement-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-replacement-2"),
metadata: {},
payload: {
threadId,
projectId,
title: "Thread Replacement",
modelSelection: {
instanceId: ProviderInstanceId.make("hermes"),
model: "hermes",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
const appendMessage = (input: {
eventNumber: number;
text: string;
streaming: boolean;
textOperation?: "replace";
}) =>
eventStore.append({
type: "thread.message-sent",
eventId: EventId.make(`evt-replacement-${input.eventNumber}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make(`cmd-replacement-${input.eventNumber}`),
causationEventId: null,
correlationId: CorrelationId.make(`cmd-replacement-${input.eventNumber}`),
metadata: {},
payload: {
threadId,
messageId,
role: "assistant",
text: input.text,
turnId: null,
streaming: input.streaming,
...(input.textOperation !== undefined ? { textOperation: input.textOperation } : {}),
createdAt: now,
updatedAt: now,
},
});
yield* appendMessage({ eventNumber: 3, text: "Hello wor", streaming: true });
yield* appendMessage({
eventNumber: 4,
text: "Hello there",
streaming: true,
textOperation: "replace",
});
yield* appendMessage({ eventNumber: 5, text: "!", streaming: true });
yield* appendMessage({ eventNumber: 6, text: "", streaming: false });
yield* projectionPipeline.bootstrap;
const messageRows = yield* sql<{ readonly text: string; readonly isStreaming: unknown }>`
SELECT
text,
is_streaming AS "isStreaming"
FROM projection_thread_messages
WHERE message_id = ${messageId}
`;
assert.equal(messageRows.length, 1);
assert.equal(messageRows[0]?.text, "Hello there!");
assert.isFalse(Boolean(messageRows[0]?.isStreaming));
}),
);
it.effect(
"resolves turn-count conflicts when checkpoint completion rewrites provisional turns",
() =>
@@ -1,10 +1,10 @@
import {
ApprovalRequestId,
type ChatAttachment,
mergeAssistantMessageText,
type OrchestrationEvent,
type OrchestrationSessionStatus,
ThreadId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -598,6 +598,12 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
threadId: event.payload.threadId,
projectId: event.payload.projectId,
workspaceTaskId:
event.payload.workspaceTaskId ?? WorkspaceTaskId.make(String(event.payload.threadId)),
tabLabel: event.payload.tabLabel ?? null,
tabPosition: event.payload.tabPosition ?? 0,
tabClosedAt: event.payload.tabClosedAt ?? null,
forkProvenance: event.payload.forkProvenance ?? null,
title: event.payload.title,
modelSelection: event.payload.modelSelection,
runtimeMode: event.payload.runtimeMode,
@@ -731,6 +737,13 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.worktreePath !== undefined
? { worktreePath: event.payload.worktreePath }
: {}),
...(event.payload.tabLabel !== undefined ? { tabLabel: event.payload.tabLabel } : {}),
...(event.payload.tabPosition !== undefined
? { tabPosition: event.payload.tabPosition }
: {}),
...(event.payload.tabClosedAt !== undefined
? { tabClosedAt: event.payload.tabClosedAt }
: {}),
updatedAt: event.payload.updatedAt,
});
return;
@@ -887,14 +900,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const previousMessage = Option.getOrUndefined(existingMessage);
const nextText = Option.match(existingMessage, {
onNone: () => event.payload.text,
onSome: (message) =>
mergeAssistantMessageText(message.text, {
text: event.payload.text,
streaming: event.payload.streaming,
...(event.payload.textOperation !== undefined
? { textOperation: event.payload.textOperation }
: {}),
}),
onSome: (message) => {
if (event.payload.streaming) {
return `${message.text}${event.payload.text}`;
}
if (event.payload.text.length === 0) {
return message.text;
}
return event.payload.text;
},
});
const nextAttachments =
event.payload.attachments !== undefined
@@ -6,6 +6,7 @@ import {
ThreadId,
TurnId,
ProviderInstanceId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -284,6 +285,11 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
{
id: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
workspaceTaskId: WorkspaceTaskId.make("thread-1"),
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
@@ -398,6 +404,11 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
{
id: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
workspaceTaskId: WorkspaceTaskId.make("thread-1"),
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
@@ -447,6 +458,29 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
if (threadDetail._tag === "Some") {
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
}
yield* sql`
UPDATE projection_threads
SET tab_closed_at = '2026-02-24T00:00:09.000Z'
WHERE thread_id = 'thread-1'
`;
const closedShellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.deepEqual(closedShellSnapshot.threads, []);
const closedThreadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
assert.equal(closedThreadShell._tag, "None");
const closedTaskTabs = yield* snapshotQuery.getClosedTaskTabs();
assert.equal(closedTaskTabs.length, 1);
assert.equal(closedTaskTabs[0]?.id, ThreadId.make("thread-1"));
assert.equal(closedTaskTabs[0]?.tabClosedAt, "2026-02-24T00:00:09.000Z");
assert.isNull(closedTaskTabs[0]?.session);
assert.isNull(closedTaskTabs[0]?.latestTurn);
const closedThreadDetail = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-1"),
);
assert.equal(closedThreadDetail._tag, "Some");
if (closedThreadDetail._tag === "Some") {
assert.equal(closedThreadDetail.value.tabClosedAt, "2026-02-24T00:00:09.000Z");
}
}),
);
@@ -24,6 +24,7 @@ import {
ModelSelection,
ProjectId,
ThreadId,
ThreadForkProvenance,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Effect from "effect/Effect";
@@ -78,6 +79,7 @@ const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
forkProvenance: Schema.NullOr(Schema.fromJsonString(ThreadForkProvenance)),
}),
);
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
@@ -117,6 +119,10 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
const ThreadRowByIdLookupInput = Schema.Struct({
threadId: ThreadId,
includeClosed: Schema.Boolean,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
@@ -240,6 +246,39 @@ function mapProjectShellRow(
};
}
function mapThreadShellRow(
row: Schema.Schema.Type<typeof ProjectionThreadDbRowSchema>,
): OrchestrationThreadShell {
return {
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
session: null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
};
}
function mapProposedPlanRow(
row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,
): OrchestrationProposedPlan {
@@ -324,6 +363,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -356,6 +400,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -378,10 +427,51 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NULL
AND tab_closed_at IS NULL
ORDER BY project_id ASC, created_at ASC, thread_id ASC
`,
});
const listClosedTaskTabRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NULL
AND tab_closed_at IS NOT NULL
ORDER BY tab_closed_at DESC, thread_id ASC
`,
});
const listArchivedThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
@@ -390,6 +480,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -748,14 +843,19 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const getActiveThreadRowById = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
const getThreadRowById = SqlSchema.findOneOption({
Request: ThreadRowByIdLookupInput,
Result: ProjectionThreadDbRowSchema,
execute: ({ threadId }) =>
execute: ({ threadId, includeClosed }) =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -779,6 +879,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
WHERE thread_id = ${threadId}
AND deleted_at IS NULL
AND archived_at IS NULL
AND (${includeClosed ? 1 : 0} = 1 OR tab_closed_at IS NULL)
LIMIT 1
`,
});
@@ -1192,6 +1293,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
@@ -1394,6 +1500,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
threads.push({
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
@@ -1527,6 +1638,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
? Result.succeed({
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
@@ -1665,6 +1781,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
(row): OrchestrationThreadShell => ({
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
@@ -1708,6 +1829,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getClosedTaskTabs: ProjectionSnapshotQueryShape["getClosedTaskTabs"] = () =>
listClosedTaskTabRows(undefined).pipe(
Effect.map((rows) => rows.map(mapThreadShellRow)),
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getClosedTaskTabs:query",
"ProjectionSnapshotQuery.getClosedTaskTabs:decodeRows",
),
),
);
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
listProjectionStateRows(undefined).pipe(
Effect.mapError(
@@ -1876,7 +2008,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
getThreadRowById({ threadId, includeClosed: false }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
@@ -1909,6 +2041,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
return Option.some({
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
workspaceTaskId: threadRow.value.workspaceTaskId,
tabLabel: threadRow.value.tabLabel,
tabPosition: threadRow.value.tabPosition,
tabClosedAt: threadRow.value.tabClosedAt,
forkProvenance: threadRow.value.forkProvenance,
title: threadRow.value.title,
modelSelection: threadRow.value.modelSelection,
runtimeMode: threadRow.value.runtimeMode,
@@ -1942,7 +2079,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
latestTurnRow,
sessionRow,
] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
getThreadRowById({ threadId, includeClosed: true }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:getThread:query",
@@ -2007,6 +2144,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const thread = {
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
workspaceTaskId: threadRow.value.workspaceTaskId,
tabLabel: threadRow.value.tabLabel,
tabPosition: threadRow.value.tabPosition,
tabClosedAt: threadRow.value.tabClosedAt,
forkProvenance: threadRow.value.forkProvenance,
title: threadRow.value.title,
modelSelection: threadRow.value.modelSelection,
runtimeMode: threadRow.value.runtimeMode,
@@ -2108,6 +2250,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getSnapshot,
getShellSnapshot,
getArchivedShellSnapshot,
getClosedTaskTabs,
getSnapshotSequence,
getCounts,
getActiveProjectByWorkspaceRoot,
@@ -20,6 +20,7 @@ import {
ProjectId,
ThreadId,
TurnId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
@@ -477,47 +478,78 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect("adopts a recovered active provider turn while binding a pending start", () =>
Effect.gen(function* () {
const recoveredTurnId = asTurnId("turn-recovered-during-start");
const harness = yield* Effect.promise(() =>
createHarness({
startSessionEffect: (session) =>
Effect.succeed({
...session,
status: "running",
activeTurnId: recoveredTurnId,
}),
}),
);
const now = "2026-01-01T00:00:00.000Z";
effectIt.effect(
"injects a source transcript only into the first provider turn of a portable task fork",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-recovered-provider-turn"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-recovered-provider-turn"),
role: "user",
text: "steer the recovered turn",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-source-turn"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("source-user-message"),
role: "user",
text: "Source tab context",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
const readModel = yield* Effect.promise(() => harness.readModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-fork-thread-create"),
threadId: ThreadId.make("thread-fork"),
projectId: asProjectId("project-1"),
workspaceTaskId: WorkspaceTaskId.make("thread-1"),
tabPosition: 1,
forkProvenance: {
mode: "portable",
sourceThreadId: ThreadId.make("thread-1"),
createdAt: now,
},
title: "Fork",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
});
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-fork-turn"),
threadId: ThreadId.make("thread-fork"),
message: {
messageId: asMessageId("fork-user-message"),
role: "user",
text: "Try another approach",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
expect(thread?.session?.status).toBe("running");
expect(thread?.session?.activeTurnId).toBe(recoveredTurnId);
expect(thread?.latestTurn).toMatchObject({
turnId: recoveredTurnId,
state: "running",
});
}),
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 2));
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-fork"),
});
const forkInput = harness.sendTurn.mock.calls[1]?.[0] as { input?: string };
expect(forkInput.input).toContain("Source tab context");
expect(forkInput.input?.endsWith("Try another approach")).toBe(true);
const readModel = yield* Effect.promise(() => harness.readModel());
const fork = readModel.threads.find((thread) => thread.id === ThreadId.make("thread-fork"));
expect(fork?.messages.map((message) => message.text)).toEqual(["Try another approach"]);
}),
);
effectIt.effect("projects starting before a slow provider session finishes", () =>
@@ -1224,62 +1256,6 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("reuses a cwd-bookkept Hermes session for active follow-up guidance", async () => {
const harness = await createHarness({
threadModelSelection: {
instanceId: ProviderInstanceId.make("hermes"),
model: "hermes",
},
});
const now = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-hermes-guidance-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-hermes-guidance-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
provider: ProviderDriverKind.make("hermes"),
providerInstanceId: ProviderInstanceId.make("hermes"),
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-hermes-guidance-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-hermes-guidance-2"),
role: "user",
text: "follow up",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession).toHaveBeenCalledTimes(1);
expect(harness.stopSession).not.toHaveBeenCalled();
});
it("restarts an existing Codex thread on a compatible requested instance", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -41,6 +41,7 @@ import {
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
import { buildPortableForkProviderInput } from "../portableFork.ts";
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
const isProviderDriverKind = Schema.is(ProviderDriverKind);
@@ -527,7 +528,8 @@ const make = Effect.gen(function* () {
providerName: session.provider,
providerInstanceId: session.providerInstanceId,
runtimeMode: desiredRuntimeMode,
activeTurnId: session.activeTurnId ?? null,
// Provider turn ids are not orchestration turn ids.
activeTurnId: null,
lastError: session.lastError ?? null,
updatedAt: session.updatedAt,
},
@@ -628,7 +630,20 @@ const make = Effect.gen(function* () {
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
}
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const sourceThread =
thread.forkProvenance?.mode === "portable" &&
thread.forkProvenance.sourceThreadId !== null &&
thread.messages.filter((entry) => entry.role === "user").length === 1
? yield* resolveThread(thread.forkProvenance.sourceThreadId)
: undefined;
const providerInput =
sourceThread !== undefined
? buildPortableForkProviderInput({
source: sourceThread,
userInput: input.messageText,
})
: input.messageText;
const normalizedInput = toNonEmptyProviderInput(providerInput);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
.listSessions()
@@ -27,7 +27,6 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
@@ -36,9 +35,7 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import {
ProviderService,
type ProviderServiceShape,
@@ -195,10 +192,7 @@ async function waitForThread(
describe("ProviderRuntimeIngestion", () => {
let runtime: ManagedRuntime.ManagedRuntime<
| OrchestrationEngineService
| ProviderRuntimeIngestionService
| ProjectionSnapshotQuery
| ProjectionTurnRepository,
OrchestrationEngineService | ProviderRuntimeIngestionService | ProjectionSnapshotQuery,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
@@ -240,13 +234,9 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
const projectionTurnLayer = ProjectionTurnRepositoryLive.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(projectionTurnLayer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
@@ -257,7 +247,6 @@ describe("ProviderRuntimeIngestion", () => {
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
const turnRepository = await runtime.runPromise(Effect.service(ProjectionTurnRepository));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(ingestion.drain);
@@ -326,7 +315,6 @@ describe("ProviderRuntimeIngestion", () => {
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
emit: provider.emit,
setProviderSession: provider.setSession,
turnRepository,
drain,
};
}
@@ -958,209 +946,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("replaces streaming assistant text from authoritative snapshots without changing identity", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const now = "2026-01-01T00:00:00.000Z";
const itemId = asItemId("item-streaming-snapshot");
const turnId = asTurnId("turn-streaming-snapshot");
harness.emit({
type: "content.delta",
eventId: asEventId("evt-streaming-snapshot-delta"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "draft",
},
});
harness.emit({
type: "content.snapshot",
eventId: asEventId("evt-streaming-snapshot-replace"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
text: "authoritative",
},
});
harness.emit({
type: "content.delta",
eventId: asEventId("evt-streaming-snapshot-tail"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: " answer",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-streaming-snapshot-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` &&
message.text === "authoritative answer" &&
!message.streaming,
),
);
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
1,
);
});
it("applies repeated empty snapshots idempotently to a streaming assistant message", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const now = "2026-01-01T00:00:00.000Z";
const itemId = asItemId("item-empty-snapshot");
const turnId = asTurnId("turn-empty-snapshot");
harness.emit({
type: "content.delta",
eventId: asEventId("evt-empty-snapshot-delta"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "remove me",
},
});
for (const eventId of ["evt-empty-snapshot-one", "evt-empty-snapshot-two"]) {
harness.emit({
type: "content.snapshot",
eventId: asEventId(eventId),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
text: "",
},
});
}
harness.emit({
type: "item.completed",
eventId: asEventId("evt-empty-snapshot-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` && message.text === "" && !message.streaming,
),
);
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
1,
);
});
it("authoritatively replaces buffered assistant text before completion", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const itemId = asItemId("item-buffered-snapshot");
const turnId = asTurnId("turn-buffered-snapshot");
harness.emit({
type: "content.delta",
eventId: asEventId("evt-buffered-snapshot-delta"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "draft",
},
});
harness.emit({
type: "content.snapshot",
eventId: asEventId("evt-buffered-snapshot-replace"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
text: "final",
},
});
harness.emit({
type: "content.delta",
eventId: asEventId("evt-buffered-snapshot-tail"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: " answer",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-buffered-snapshot-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` &&
message.text === "final answer" &&
!message.streaming,
),
);
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
1,
);
});
it("uses assistant item completion detail when no assistant deltas were streamed", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -1788,85 +1573,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(threadAfterSteer.latestTurn?.state).toBe("running");
});
effectIt.effect(
"consumes a follow-up pending start when Hermes acknowledges the active turn",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const threadId = asThreadId("thread-1");
const activeTurnId = asTurnId("turn-hermes-active");
const followUpMessageId = asMessageId("msg-hermes-follow-up");
const createdAt = "2026-01-01T00:00:00.000Z";
harness.setProviderSession({
provider: ProviderDriverKind.make("hermes"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-hermes-active-turn-started"),
provider: ProviderDriverKind.make("hermes"),
createdAt,
threadId,
turnId: activeTurnId,
});
yield* Effect.promise(() =>
waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session.activeTurnId === activeTurnId,
2_000,
threadId,
),
);
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-hermes-follow-up"),
threadId,
message: {
messageId: followUpMessageId,
role: "user",
text: "steer the active Hermes turn",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
});
const pendingBeforeAck = yield* harness.turnRepository.getPendingTurnStartByThreadId({
threadId,
});
expect(Option.getOrUndefined(pendingBeforeAck)?.messageId).toBe(followUpMessageId);
harness.emit({
type: "turn.started",
eventId: asEventId("evt-hermes-follow-up-ack"),
provider: ProviderDriverKind.make("hermes"),
createdAt: "2026-01-01T00:00:02.000Z",
threadId,
turnId: activeTurnId,
});
yield* Effect.promise(() => harness.drain());
const pendingAfterAck = yield* harness.turnRepository.getPendingTurnStartByThreadId({
threadId,
});
const activeTurn = yield* harness.turnRepository.getByTurnId({
threadId,
turnId: activeTurnId,
});
expect(Option.isNone(pendingAfterAck)).toBe(true);
expect(Option.getOrUndefined(activeTurn)?.pendingMessageId).toBe(followUpMessageId);
}),
);
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
@@ -2167,97 +1873,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("treats turn.aborted as terminal and finalizes buffered assistant text", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const turnId = asTurnId("turn-aborted-buffered");
const itemId = asItemId("item-aborted-buffered");
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-before-abort"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
});
await waitForThread(
harness.readModel,
(thread) => thread.session?.status === "running" && thread.session.activeTurnId === turnId,
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-content-before-abort"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "partial response",
},
});
harness.emit({
type: "turn.aborted",
eventId: asEventId("evt-turn-aborted"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
payload: {
reason: "Interrupted by user.",
},
});
const thread = await waitForThread(
harness.readModel,
(entry) =>
entry.session?.status === "ready" &&
entry.session.activeTurnId === null &&
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` &&
message.text === "partial response" &&
!message.streaming,
),
);
expect(thread.session?.lastError).toBeNull();
const nextTurnId = asTurnId("turn-after-abort");
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-after-abort"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: nextTurnId,
});
await waitForThread(
harness.readModel,
(entry) => entry.session?.status === "running" && entry.session.activeTurnId === nextTurnId,
);
harness.emit({
type: "turn.aborted",
eventId: asEventId("evt-stale-turn-aborted"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
payload: {
reason: "Late abort for the previous turn.",
},
});
await harness.drain();
const afterStaleAbort = await harness.readModel();
const activeThread = afterStaleAbort.threads.find(
(entry) => entry.id === ThreadId.make("thread-1"),
);
expect(activeThread?.session?.status).toBe("running");
expect(activeThread?.session?.activeTurnId).toBe(nextTurnId);
});
it("flushes and completes buffered assistant text when an approval request opens", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2837,65 +2452,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("replaces a spilled buffered projection when an authoritative snapshot arrives", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
const itemId = asItemId("item-buffer-spill-snapshot");
const turnId = asTurnId("turn-buffer-spill-snapshot");
harness.emit({
type: "content.delta",
eventId: asEventId("evt-buffer-spill-before-snapshot"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
delta: "x".repeat(40_000),
},
});
harness.emit({
type: "content.snapshot",
eventId: asEventId("evt-buffer-spill-snapshot"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
streamKind: "assistant_text",
text: "authoritative after spill",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-buffer-spill-snapshot-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: now,
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "assistant_message",
status: "completed",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.messages.some(
(message: ProviderRuntimeTestMessage) =>
message.id === `assistant:${itemId}` &&
message.text === "authoritative after spill" &&
!message.streaming,
),
);
expect(thread.messages.filter((message) => message.id === `assistant:${itemId}`)).toHaveLength(
1,
);
});
it("does not duplicate assistant completion when item.completed is followed by turn.completed", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -3202,147 +2758,6 @@ describe("ProviderRuntimeIngestion", () => {
).toBe(true);
});
it("upserts status_text provider item lifecycle into one meaningful activity", async () => {
const harness = await createHarness();
const itemId = asItemId("item-generic-activity");
const turnId = asTurnId("turn-generic-activity");
harness.emit({
type: "item.started",
eventId: asEventId("evt-generic-activity-started"),
provider: ProviderDriverKind.make("hermes"),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "status_text",
status: "inProgress",
title: "Reading skill hermes-agent",
detail: "Opening the skill instructions.",
data: { unsafeRawPayload: "not projected" },
},
});
harness.emit({
type: "item.updated",
eventId: asEventId("evt-generic-activity-updated"),
provider: ProviderDriverKind.make("hermes"),
createdAt: "2026-01-01T00:00:01.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "status_text",
status: "inProgress",
title: "Reading skill hermes-agent",
detail: "Parsing the workflow.",
},
});
harness.emit({
type: "item.completed",
eventId: asEventId("evt-generic-activity-completed"),
provider: ProviderDriverKind.make("hermes"),
createdAt: "2026-01-01T00:00:02.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "status_text",
status: "completed",
title: "Read skill hermes-agent",
detail: "Skill instructions loaded.",
},
});
const activityId = `provider:hermes:item:${itemId}`;
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) =>
activity.id === activityId &&
activity.payload &&
typeof activity.payload === "object" &&
(activity.payload as Record<string, unknown>).status === "completed",
),
);
const activities = thread.activities.filter((activity) => activity.id === activityId);
const activity = activities[0];
const payload =
activity?.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: undefined;
expect(activities).toHaveLength(1);
expect(activity?.kind).toBe("provider.activity");
expect(activity?.tone).toBe("info");
expect(activity?.summary).toBe("Skill instructions loaded.");
expect(payload).toMatchObject({
itemType: "status_text",
status: "completed",
providerItemId: itemId,
title: "Read skill hermes-agent",
detail: "Skill instructions loaded.",
});
expect(payload?.data).toBeUndefined();
});
// Regression: `unknown` is the canonical "could not classify this item"
// sentinel and adapters rely on it being INERT. CodexAdapter deliberately
// emits it for item.updated; routing generic activity through it put rows
// summarized as the literal string "Provider activity" into Codex threads.
// Renderable status text has its own item type (`status_text`) instead.
it("does not create activities for the unknown item sentinel", async () => {
const harness = await createHarness();
const itemId = asItemId("item-codex-unknown");
const turnId = asTurnId("turn-codex-unknown");
harness.emit({
type: "item.updated",
eventId: asEventId("evt-codex-unknown-updated"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId,
payload: {
itemType: "unknown",
status: "inProgress",
},
});
// A tool item after it gives the poll something real to settle on, so the
// assertion is "the unknown item produced nothing" rather than a race.
harness.emit({
type: "item.started",
eventId: asEventId("evt-codex-unknown-tool"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:01.000Z",
threadId: asThreadId("thread-1"),
turnId,
itemId: asItemId("item-codex-tool"),
payload: {
itemType: "command_execution",
status: "inProgress",
title: "ls",
},
});
const thread = await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "tool.started",
),
);
expect(
thread.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === `provider:codex:item:${itemId}`,
),
).toBe(false);
expect(
thread.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "provider.activity",
),
).toBe(false);
});
it("consumes P1 runtime events into thread metadata, diff checkpoints, and activities", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2,7 +2,6 @@ import {
ApprovalRequestId,
type AssistantDeliveryMode,
CommandId,
EventId,
MessageId,
type OrchestrationEvent,
type OrchestrationMessage,
@@ -307,47 +306,6 @@ function requestKindFromCanonicalRequestType(
}
}
function genericProviderActivityId(event: ProviderRuntimeEvent): EventId {
return EventId.make(
event.itemId
? `provider:${event.provider}:item:${event.itemId}`
: `provider:${event.provider}:event:${event.eventId}`,
);
}
function genericProviderActivity(
event: Extract<
ProviderRuntimeEvent,
{ type: "item.started" | "item.updated" | "item.completed" }
>,
maybeSequence: { readonly sequence?: number },
): OrchestrationThreadActivity {
const title = event.payload.title ? truncateDetail(event.payload.title, 120) : undefined;
const detail = event.payload.detail ? truncateDetail(event.payload.detail) : undefined;
const status =
event.payload.status ?? (event.type === "item.completed" ? "completed" : "inProgress");
return {
id: genericProviderActivityId(event),
createdAt: event.createdAt,
tone: "info",
kind: "provider.activity",
// Status text is the interesting part here; the title is a generic label
// ("Hermes activity"). Prefer the detail so the row reads as the status the
// provider is actually reporting.
summary: detail ? truncateDetail(detail, 120) : (title ?? "Working…"),
payload: {
itemType: event.payload.itemType,
status,
...(event.itemId ? { providerItemId: event.itemId } : {}),
...(title ? { title } : {}),
...(detail ? { detail } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
};
}
export function runtimeEventToActivities(
event: ProviderRuntimeEvent,
taskTitle?: string,
@@ -656,9 +614,6 @@ export function runtimeEventToActivities(
}
case "item.updated": {
if (event.payload.itemType === "status_text") {
return [genericProviderActivity(event, maybeSequence)];
}
if (!isToolLifecycleItemType(event.payload.itemType)) {
return [];
}
@@ -682,9 +637,6 @@ export function runtimeEventToActivities(
}
case "item.completed": {
if (event.payload.itemType === "status_text") {
return [genericProviderActivity(event, maybeSequence)];
}
if (!isToolLifecycleItemType(event.payload.itemType)) {
return [];
}
@@ -707,9 +659,6 @@ export function runtimeEventToActivities(
}
case "item.started": {
if (event.payload.itemType === "status_text") {
return [genericProviderActivity(event, maybeSequence)];
}
if (!isToolLifecycleItemType(event.payload.itemType)) {
return [];
}
@@ -950,9 +899,6 @@ const make = Effect.gen(function* () {
),
);
const replaceBufferedAssistantText = (messageId: MessageId, text: string) =>
Cache.set(bufferedAssistantTextByMessageId, messageId, text);
const takeBufferedAssistantText = (messageId: MessageId) =>
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.flatMap((existingText) =>
@@ -1397,7 +1343,6 @@ const make = Effect.gen(function* () {
case "turn.started":
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
case "turn.completed":
case "turn.aborted":
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
}
@@ -1422,8 +1367,7 @@ const make = Effect.gen(function* () {
event.type === "session.exited" ||
event.type === "thread.started" ||
event.type === "turn.started" ||
event.type === "turn.completed" ||
event.type === "turn.aborted"
event.type === "turn.completed"
) {
const status = (() => {
switch (event.type) {
@@ -1439,8 +1383,6 @@ const make = Effect.gen(function* () {
return normalizeRuntimeTurnState(event.payload.state) === "failed"
? "error"
: "ready";
case "turn.aborted":
return "ready";
case "session.started":
case "thread.started":
// Provider thread/session start notifications can arrive during an
@@ -1451,9 +1393,7 @@ const make = Effect.gen(function* () {
const nextActiveTurnId =
event.type === "turn.started"
? (eventTurnId ?? null)
: event.type === "turn.completed" ||
event.type === "turn.aborted" ||
event.type === "session.exited"
: event.type === "turn.completed" || event.type === "session.exited"
? null
: event.type === "session.state.changed" &&
!sessionStatusAllowsActiveTurn(
@@ -1517,10 +1457,6 @@ const make = Effect.gen(function* () {
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
? event.payload.delta
: undefined;
const assistantSnapshot =
event.type === "content.snapshot" && event.payload.streamKind === "assistant_text"
? event.payload.text
: undefined;
const proposedPlanDelta =
event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
@@ -1565,53 +1501,6 @@ const make = Effect.gen(function* () {
}
}
if (assistantSnapshot !== undefined) {
const turnId = toTurnId(event.turnId);
const assistantMessageId = yield* getOrCreateAssistantMessageId({
threadId: thread.id,
event,
...(turnId ? { turnId } : {}),
});
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
);
if (assistantDeliveryMode === "buffered") {
const detailedThread = yield* getLoadedThreadDetail();
const hasProjectedMessage =
findMessageById(detailedThread?.messages ?? [], assistantMessageId) !== undefined;
if (hasProjectedMessage) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.replace",
commandId: yield* providerCommandId(event, "assistant-snapshot-buffer-spill"),
threadId: thread.id,
messageId: assistantMessageId,
text: assistantSnapshot,
...(turnId ? { turnId } : {}),
createdAt: now,
});
yield* clearBufferedAssistantText(assistantMessageId);
} else {
yield* replaceBufferedAssistantText(assistantMessageId, assistantSnapshot);
}
} else {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.replace",
commandId: yield* providerCommandId(event, "assistant-snapshot"),
threadId: thread.id,
messageId: assistantMessageId,
text: assistantSnapshot,
...(turnId ? { turnId } : {}),
createdAt: now,
});
yield* clearBufferedAssistantText(assistantMessageId);
}
}
const pauseForUserTurnId =
event.type === "request.opened" || event.type === "user-input.requested"
? toTurnId(event.turnId)
@@ -1745,7 +1634,7 @@ const make = Effect.gen(function* () {
});
}
if (event.type === "turn.completed" || event.type === "turn.aborted") {
if (event.type === "turn.completed") {
const detailedThread = yield* getLoadedThreadDetail();
const messages = detailedThread?.messages ?? [];
const proposedPlans = detailedThread?.proposedPlans ?? [];
@@ -94,6 +94,15 @@ export interface ProjectionSnapshotQueryShape {
ProjectionRepositoryError
>;
/**
* Read closed, non-archived task-tab shells so clients can offer restore
* without bootstrapping them into normal navigation state.
*/
readonly getClosedTaskTabs: () => Effect.Effect<
ReadonlyArray<OrchestrationThreadShell>,
ProjectionRepositoryError
>;
/**
* Read the latest projection snapshot sequence without hydrating read-model
* entities.
@@ -1,73 +0,0 @@
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import { expect, it } from "@effect/vitest";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
it.layer(NodeServices.layer)("assistant message replacement", (it) => {
it.effect("emits a streaming replacement message event", () =>
Effect.gen(function* () {
const now = "2026-07-24T12:00:00.000Z";
const threadId = ThreadId.make("thread-replacement");
const readModel = yield* projectEvent(createEmptyReadModel(now), {
sequence: 1,
eventId: EventId.make("event-thread-created"),
aggregateKind: "thread",
aggregateId: threadId,
type: "thread.created",
occurredAt: now,
commandId: CommandId.make("command-thread-created"),
causationEventId: null,
correlationId: CommandId.make("command-thread-created"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-replacement"),
title: "Replacement",
modelSelection: {
instanceId: ProviderInstanceId.make("hermes"),
model: "hermes",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
const decided = yield* decideOrchestrationCommand({
command: {
type: "thread.message.assistant.replace",
commandId: CommandId.make("command-message-replace"),
threadId,
messageId: MessageId.make("assistant:message-1"),
text: "Hello there",
turnId: TurnId.make("turn-1"),
createdAt: now,
},
readModel,
});
const event = Array.isArray(decided) ? decided[0] : decided;
if (event?.type !== "thread.message-sent") {
throw new Error("expected thread.message-sent");
}
expect(event.payload.text).toBe("Hello there");
expect(event.payload.streaming).toBe(true);
expect(event.payload.textOperation).toBe("replace");
}),
);
});
@@ -0,0 +1,216 @@
import {
CommandId,
EventId,
ProjectId,
ProviderInstanceId,
ThreadId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const now = "2026-07-24T00:00:00.000Z";
const projectId = ProjectId.make("project-1");
const taskId = WorkspaceTaskId.make("task-1");
const rootThreadId = ThreadId.make("thread-root");
const modelSelection = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5",
} as const;
const seededReadModel = Effect.gen(function* () {
const withProject = yield* projectEvent(createEmptyReadModel(now), {
sequence: 1,
eventId: EventId.make("event-project"),
aggregateKind: "project",
aggregateId: projectId,
type: "project.created",
occurredAt: now,
commandId: CommandId.make("command-project"),
causationEventId: null,
correlationId: CommandId.make("command-project"),
metadata: {},
payload: {
projectId,
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: modelSelection,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
return yield* projectEvent(withProject, {
sequence: 2,
eventId: EventId.make("event-root"),
aggregateKind: "thread",
aggregateId: rootThreadId,
type: "thread.created",
occurredAt: now,
commandId: CommandId.make("command-root"),
causationEventId: null,
correlationId: CommandId.make("command-root"),
metadata: {},
payload: {
threadId: rootThreadId,
projectId,
workspaceTaskId: taskId,
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Task",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/task",
worktreePath: "/tmp/project-task",
createdAt: now,
updatedAt: now,
},
});
});
const seededReadModelWithSibling = Effect.gen(function* () {
const readModel = yield* seededReadModel;
const decided = yield* decideOrchestrationCommand({
readModel,
command: {
type: "thread.create",
commandId: CommandId.make("command-seed-child"),
threadId: ThreadId.make("thread-child"),
projectId,
workspaceTaskId: taskId,
tabPosition: 1,
title: "Alternative",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/task",
worktreePath: "/tmp/project-task",
createdAt: now,
},
});
const event = Array.isArray(decided) ? decided[0]! : decided;
return yield* projectEvent(readModel, event);
});
it.layer(NodeServices.layer)("task tab invariants", (it) => {
it.effect("accepts a sibling tab on the same project and worktree", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
readModel: yield* seededReadModel,
command: {
type: "thread.create",
commandId: CommandId.make("command-child"),
threadId: ThreadId.make("thread-child"),
projectId,
workspaceTaskId: taskId,
tabPosition: 1,
forkProvenance: {
mode: "portable",
sourceThreadId: rootThreadId,
createdAt: now,
},
title: "Alternative",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/task",
worktreePath: "/tmp/project-task",
createdAt: now,
},
});
const firstEvent = Array.isArray(event) ? event[0] : event;
expect(firstEvent.type).toBe("thread.created");
expect(firstEvent.payload).toMatchObject({
workspaceTaskId: taskId,
tabPosition: 1,
});
}),
);
it.effect("rejects a sibling tab that points at another worktree", () =>
Effect.gen(function* () {
const failure = yield* Effect.flip(
decideOrchestrationCommand({
readModel: yield* seededReadModel,
command: {
type: "thread.create",
commandId: CommandId.make("command-wrong-tree"),
threadId: ThreadId.make("thread-wrong-tree"),
projectId,
workspaceTaskId: taskId,
title: "Wrong tree",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "other",
worktreePath: "/tmp/other-tree",
createdAt: now,
},
}),
);
expect(failure.message).toContain("must keep project and worktree identity");
}),
);
it.effect("rejects moving one tab to another worktree after task creation", () =>
Effect.gen(function* () {
const failure = yield* Effect.flip(
decideOrchestrationCommand({
readModel: yield* seededReadModelWithSibling,
command: {
type: "thread.meta.update",
commandId: CommandId.make("command-move-root"),
threadId: rootThreadId,
worktreePath: "/tmp/other-tree",
},
}),
);
expect(failure.message).toContain("must keep project and worktree identity");
}),
);
it.effect("rejects a deleted source for a portable fork", () =>
Effect.gen(function* () {
const readModel = yield* seededReadModel;
const withDeletedSource = {
...readModel,
threads: readModel.threads.map((thread) =>
thread.id === rootThreadId ? { ...thread, deletedAt: now } : thread,
),
};
const failure = yield* Effect.flip(
decideOrchestrationCommand({
readModel: withDeletedSource,
command: {
type: "thread.create",
commandId: CommandId.make("command-deleted-source"),
threadId: ThreadId.make("thread-from-deleted-source"),
projectId,
workspaceTaskId: taskId,
tabPosition: 1,
forkProvenance: {
mode: "portable",
sourceThreadId: rootThreadId,
createdAt: now,
},
title: "Deleted source",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/task",
worktreePath: "/tmp/project-task",
createdAt: now,
},
}),
);
expect(failure.message).toContain("portable fork source must be an existing tab");
}),
);
});
+72 -28
View File
@@ -3,6 +3,7 @@ import {
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
@@ -24,6 +25,10 @@ import { projectEvent } from "./projector.ts";
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
function workspaceTaskIdForThread(thread: OrchestrationReadModel["threads"][number]) {
return thread.workspaceTaskId ?? WorkspaceTaskId.make(String(thread.id));
}
// Session adoption takes seconds; a user message still unadopted after this
// window is a failed/stale start, not pending work. Mirrors the client's
// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.
@@ -355,6 +360,47 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
threadId: command.threadId,
});
const workspaceTaskId =
command.workspaceTaskId ?? WorkspaceTaskId.make(String(command.threadId));
const sibling = readModel.threads.find(
(thread) =>
thread.deletedAt === null && workspaceTaskIdForThread(thread) === workspaceTaskId,
);
if (
sibling &&
(sibling.projectId !== command.projectId || sibling.worktreePath !== command.worktreePath)
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `workspace task ${workspaceTaskId} must keep project and worktree identity from sibling thread ${sibling.id}`,
});
}
if (
command.forkProvenance?.mode === "fresh" &&
command.forkProvenance.sourceThreadId !== null
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "a fresh task tab cannot declare a source thread",
});
}
if (command.forkProvenance?.mode === "portable") {
const source = readModel.threads.find(
(thread) => thread.id === command.forkProvenance?.sourceThreadId,
);
if (
!source ||
source.deletedAt !== null ||
workspaceTaskIdForThread(source) !== workspaceTaskId ||
source.projectId !== command.projectId ||
source.worktreePath !== command.worktreePath
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `portable fork source must be an existing tab in workspace task ${workspaceTaskId}`,
});
}
}
return {
...(yield* withEventBase({
aggregateKind: "thread",
@@ -366,6 +412,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
projectId: command.projectId,
workspaceTaskId,
tabLabel: command.tabLabel ?? null,
tabPosition: command.tabPosition ?? 0,
tabClosedAt: command.tabClosedAt ?? null,
forkProvenance: command.forkProvenance ?? null,
title: command.title,
modelSelection: command.modelSelection,
runtimeMode: command.runtimeMode,
@@ -642,6 +693,24 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
thread.branch !== command.expectedBranch
? thread.branch
: command.branch;
if (command.worktreePath !== undefined) {
const workspaceTaskId = workspaceTaskIdForThread(thread);
const sibling = readModel.threads.find(
(candidate) =>
candidate.id !== thread.id &&
candidate.deletedAt === null &&
workspaceTaskIdForThread(candidate) === workspaceTaskId,
);
if (
sibling &&
(sibling.projectId !== thread.projectId || sibling.worktreePath !== command.worktreePath)
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `workspace task ${workspaceTaskId} must keep project and worktree identity from sibling thread ${sibling.id}`,
});
}
}
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -659,6 +728,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
: {}),
...(branch !== undefined ? { branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
...(command.tabLabel !== undefined ? { tabLabel: command.tabLabel } : {}),
...(command.tabPosition !== undefined ? { tabPosition: command.tabPosition } : {}),
...(command.tabClosedAt !== undefined ? { tabClosedAt: command.tabClosedAt } : {}),
updatedAt: occurredAt,
},
};
@@ -1018,34 +1090,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.message.assistant.replace": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.message-sent",
payload: {
threadId: command.threadId,
messageId: command.messageId,
role: "assistant",
text: command.text,
turnId: command.turnId ?? null,
streaming: true,
textOperation: "replace",
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
}
case "thread.message.assistant.complete": {
yield* requireThread({
readModel,
+2 -1
View File
@@ -7,6 +7,7 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { projectThreadDetailSnapshot } from "./ActivityPayloadProjection.ts";
import { normalizeDispatchCommand } from "./Normalizer.ts";
import {
annotateEnvironmentRequest,
@@ -69,7 +70,7 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
if (Option.isNone(snapshot)) {
return yield* failEnvironmentNotFound("thread_not_found");
}
return snapshot.value;
return projectThreadDetailSnapshot(snapshot.value);
}),
)
.handle(
@@ -0,0 +1,100 @@
import { describe, expect, it } from "@effect/vitest";
import {
MessageId,
ProviderInstanceId,
ProjectId,
ThreadId,
WorkspaceTaskId,
type OrchestrationThread,
} from "@t3tools/contracts";
import { buildPortableForkProviderInput } from "./portableFork.ts";
function makeSource(messages: OrchestrationThread["messages"]): OrchestrationThread {
return {
id: ThreadId.make("source-thread"),
projectId: ProjectId.make("project-1"),
workspaceTaskId: WorkspaceTaskId.make("task-1"),
tabLabel: "Main",
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Investigate task tabs",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/task-tabs",
worktreePath: "/tmp/task-tabs",
latestTurn: null,
createdAt: "2026-07-24T00:00:00.000Z",
updatedAt: "2026-07-24T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages,
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
};
}
describe("buildPortableForkProviderInput", () => {
it("places the source transcript before the child tab request", () => {
const result = buildPortableForkProviderInput({
source: makeSource([
{
id: MessageId.make("message-1"),
role: "user",
text: "Inspect the architecture.",
attachments: [],
turnId: null,
streaming: false,
createdAt: "2026-07-24T00:00:00.000Z",
updatedAt: "2026-07-24T00:00:00.000Z",
},
]),
userInput: "Try a different implementation.",
});
expect(result).toContain("same T3 Code task");
expect(result).toContain("Inspect the architecture.");
expect(result).toContain("Shared worktree: /tmp/task-tabs");
expect(result.endsWith("Try a different implementation.")).toBe(true);
});
it("bounds large transcripts while retaining recent messages", () => {
const result = buildPortableForkProviderInput({
source: makeSource([
{
id: MessageId.make("message-old"),
role: "user",
text: `old-${"x".repeat(48_000)}`,
attachments: [],
turnId: null,
streaming: false,
createdAt: "2026-07-24T00:00:00.000Z",
updatedAt: "2026-07-24T00:00:00.000Z",
},
{
id: MessageId.make("message-recent"),
role: "assistant",
text: "recent-context",
attachments: [],
turnId: null,
streaming: false,
createdAt: "2026-07-24T00:01:00.000Z",
updatedAt: "2026-07-24T00:01:00.000Z",
},
]),
userInput: "Continue.",
});
expect(result).not.toContain("old-");
expect(result).toContain("recent-context");
expect(result.length).toBeLessThan(50_000);
});
});
@@ -0,0 +1,55 @@
import type { OrchestrationMessage, OrchestrationThread } from "@t3tools/contracts";
const MAX_HANDOFF_CHARACTERS = 48_000;
function renderMessage(message: OrchestrationMessage): string {
const attachmentNote =
message.attachments && message.attachments.length > 0
? `\n[${message.attachments.length} attachment${message.attachments.length === 1 ? "" : "s"} omitted from the handoff]`
: "";
return `<message role="${message.role}">\n${message.text}${attachmentNote}\n</message>`;
}
/**
* Builds a provider-neutral first-turn handoff for a context-forked task tab.
* The source transcript remains owned by its original thread; the child only
* receives this bounded snapshot as provider input.
*/
export function buildPortableForkProviderInput(input: {
readonly source: OrchestrationThread;
readonly userInput: string;
}): string {
const header = [
"<t3-task-tab-context>",
"You are continuing in a sibling tab of the same T3 Code task.",
"The sibling tabs share one worktree. Treat the source transcript below as prior context,",
"but follow the new user request after the closing tag as the current instruction.",
`Source tab: ${input.source.title}`,
`Source thread id: ${input.source.id}`,
`Source branch: ${input.source.branch ?? "(current checkout)"}`,
`Shared worktree: ${input.source.worktreePath ?? "(project workspace)"}`,
"<source-transcript>",
].join("\n");
const footer = "\n</source-transcript>\n</t3-task-tab-context>";
const fixedSize = header.length + footer.length;
const budget = Math.max(0, MAX_HANDOFF_CHARACTERS - fixedSize);
const selected: string[] = [];
let used = 0;
// Preserve the most recent context when the source conversation is larger
// than the portable handoff budget.
for (let index = input.source.messages.length - 1; index >= 0; index -= 1) {
const message = input.source.messages[index];
if (!message) continue;
const rendered = renderMessage(message);
if (used + rendered.length > budget) {
continue;
}
selected.unshift(rendered);
used += rendered.length;
}
const transcript =
selected.length > 0 ? selected.join("\n") : "[No source transcript was available.]";
return `${header}\n${transcript}${footer}\n\n${input.userInput}`;
}
@@ -488,83 +488,6 @@ describe("orchestration projector", () => {
expect(message?.updatedAt).toBe(completeAt);
});
it("replaces an assistant snapshot between legacy appended deltas", async () => {
const createdAt = "2026-02-23T09:00:00.000Z";
const model = createEmptyReadModel(createdAt);
const afterCreate = await Effect.runPromise(
projectEvent(
model,
makeEvent({
sequence: 1,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: createdAt,
commandId: "cmd-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: ProviderDriverKind.make("hermes"),
model: "hermes",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
updatedAt: createdAt,
},
}),
),
);
const messageEvent = (input: {
sequence: number;
text: string;
streaming: boolean;
textOperation?: "replace";
}) =>
makeEvent({
sequence: input.sequence,
type: "thread.message-sent",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: createdAt,
commandId: `cmd-message-${input.sequence}`,
payload: {
threadId: "thread-1",
messageId: "assistant:msg-replace",
role: "assistant",
text: input.text,
turnId: "turn-1",
streaming: input.streaming,
...(input.textOperation !== undefined ? { textOperation: input.textOperation } : {}),
createdAt,
updatedAt: createdAt,
},
});
let projected = afterCreate;
for (const event of [
messageEvent({ sequence: 2, text: "Hello wor", streaming: true }),
messageEvent({
sequence: 3,
text: "Hello there",
streaming: true,
textOperation: "replace",
}),
messageEvent({ sequence: 4, text: "!", streaming: true }),
messageEvent({ sequence: 5, text: "", streaming: false }),
]) {
projected = await Effect.runPromise(projectEvent(projected, event));
}
const message = projected.threads[0]?.messages[0];
expect(message?.text).toBe("Hello there!");
expect(message?.streaming).toBe(false);
});
it("prunes reverted turn messages from in-memory thread snapshot", async () => {
const createdAt = "2026-02-23T10:00:00.000Z";
const model = createEmptyReadModel(createdAt);
+13 -8
View File
@@ -1,6 +1,5 @@
import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
import {
mergeAssistantMessageText,
OrchestrationCheckpointSummary,
OrchestrationMessage,
OrchestrationSession,
@@ -281,6 +280,11 @@ export function projectEvent(
{
id: payload.threadId,
projectId: payload.projectId,
workspaceTaskId: payload.workspaceTaskId,
tabLabel: payload.tabLabel,
tabPosition: payload.tabPosition,
tabClosedAt: payload.tabClosedAt,
forkProvenance: payload.forkProvenance,
title: payload.title,
modelSelection: payload.modelSelection,
runtimeMode: payload.runtimeMode,
@@ -405,6 +409,9 @@ export function projectEvent(
: {}),
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
...(payload.tabLabel !== undefined ? { tabLabel: payload.tabLabel } : {}),
...(payload.tabPosition !== undefined ? { tabPosition: payload.tabPosition } : {}),
...(payload.tabClosedAt !== undefined ? { tabClosedAt: payload.tabClosedAt } : {}),
updatedAt: payload.updatedAt,
}),
})),
@@ -472,13 +479,11 @@ export function projectEvent(
entry.id === message.id
? {
...entry,
text: mergeAssistantMessageText(entry.text, {
text: message.text,
streaming: message.streaming,
...(payload.textOperation !== undefined
? { textOperation: payload.textOperation }
: {}),
}),
text: message.streaming
? `${entry.text}${message.text}`
: message.text.length > 0
? message.text
: entry.text,
streaming: message.streaming,
updatedAt: message.updatedAt,
turnId: message.turnId,
@@ -1,4 +1,4 @@
import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import { ProjectId, ProviderInstanceId, ThreadId, WorkspaceTaskId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -78,6 +78,11 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
yield* threads.upsert({
threadId: ThreadId.make("thread-null-options"),
projectId: ProjectId.make("project-null-options"),
workspaceTaskId: WorkspaceTaskId.make("thread-null-options"),
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Null options thread",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
@@ -140,6 +145,11 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
yield* threads.upsert({
threadId: ThreadId.make("thread-settled"),
projectId: ProjectId.make("project-1"),
workspaceTaskId: WorkspaceTaskId.make("thread-settled"),
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Settled thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
@@ -14,11 +14,12 @@ import {
ProjectionThreadRepository,
type ProjectionThreadRepositoryShape,
} from "../Services/ProjectionThreads.ts";
import { ModelSelection } from "@t3tools/contracts";
import { ModelSelection, ThreadForkProvenance } from "@t3tools/contracts";
const ProjectionThreadDbRow = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
forkProvenance: Schema.NullOr(Schema.fromJsonString(ThreadForkProvenance)),
}),
);
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
@@ -33,6 +34,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
INSERT INTO projection_threads (
thread_id,
project_id,
workspace_task_id,
tab_label,
tab_position,
tab_closed_at,
fork_provenance_json,
title,
model_selection_json,
runtime_mode,
@@ -56,6 +62,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
VALUES (
${row.threadId},
${row.projectId},
${row.workspaceTaskId},
${row.tabLabel},
${row.tabPosition},
${row.tabClosedAt},
${row.forkProvenance === null ? null : JSON.stringify(row.forkProvenance)},
${row.title},
${JSON.stringify(row.modelSelection)},
${row.runtimeMode},
@@ -79,6 +90,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
ON CONFLICT (thread_id)
DO UPDATE SET
project_id = excluded.project_id,
workspace_task_id = excluded.workspace_task_id,
tab_label = excluded.tab_label,
tab_position = excluded.tab_position,
tab_closed_at = excluded.tab_closed_at,
fork_provenance_json = excluded.fork_provenance_json,
title = excluded.title,
model_selection_json = excluded.model_selection_json,
runtime_mode = excluded.runtime_mode,
@@ -109,6 +125,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -141,6 +162,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -47,6 +47,7 @@ import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionThreadTasks.ts";
/**
* Migration loader with all migrations defined inline.
@@ -93,6 +94,7 @@ export const migrationEntries = [
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "ProjectionThreadsSettled", Migration0033],
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionThreadTasks", Migration0035],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,97 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("035_ProjectionThreadTasks", (it) => {
it.effect("backfills legacy threads as one-tab tasks and creates the lookup index", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 34 });
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
settled_override,
settled_at,
snoozed_until,
snoozed_at,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
deleted_at
)
VALUES (
'thread-legacy',
'project-1',
'Legacy thread',
'{"instanceId":"codex","model":"gpt-5"}',
'full-access',
'default',
'main',
'/tmp/worktree',
NULL,
'2026-07-24T00:00:00.000Z',
'2026-07-24T00:00:00.000Z',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
NULL
)
`;
yield* runMigrations({ toMigrationInclusive: 35 });
const rows = yield* sql<{
readonly workspaceTaskId: string;
readonly tabPosition: number;
readonly tabClosedAt: string | null;
readonly forkProvenance: string | null;
}>`
SELECT
workspace_task_id AS "workspaceTaskId",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance"
FROM projection_threads
WHERE thread_id = 'thread-legacy'
`;
assert.deepStrictEqual(rows, [
{
workspaceTaskId: "thread-legacy",
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
},
]);
const indexes = yield* sql<{ readonly name: string }>`
PRAGMA index_list(projection_threads)
`;
assert.ok(indexes.some((index) => index.name === "idx_projection_threads_workspace_task"));
}),
);
});
@@ -0,0 +1,53 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "workspace_task_id")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN workspace_task_id TEXT
`;
}
if (!columns.some((column) => column.name === "tab_label")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN tab_label TEXT
`;
}
if (!columns.some((column) => column.name === "tab_position")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN tab_position INTEGER NOT NULL DEFAULT 0
`;
}
if (!columns.some((column) => column.name === "tab_closed_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN tab_closed_at TEXT
`;
}
if (!columns.some((column) => column.name === "fork_provenance_json")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN fork_provenance_json TEXT
`;
}
// Every pre-task thread becomes a one-tab task. This makes the migration
// lossless and lets mixed-version clients continue using thread routes.
yield* sql`
UPDATE projection_threads
SET workspace_task_id = thread_id
WHERE workspace_task_id IS NULL
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_workspace_task
ON projection_threads (workspace_task_id, tab_closed_at, tab_position, created_at, thread_id)
`;
});
@@ -14,7 +14,9 @@ import {
ProviderInteractionMode,
RuntimeMode,
ThreadId,
ThreadForkProvenance,
TurnId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -26,6 +28,11 @@ import type { ProjectionRepositoryError } from "../Errors.ts";
export const ProjectionThread = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
workspaceTaskId: WorkspaceTaskId,
tabLabel: Schema.NullOr(Schema.String),
tabPosition: NonNegativeInt,
tabClosedAt: Schema.NullOr(IsoDateTime),
forkProvenance: Schema.NullOr(ThreadForkProvenance),
title: Schema.String,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
@@ -30,6 +30,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
@@ -1,138 +0,0 @@
import {
DEFAULT_HERMES_MODEL,
HERMES_DRIVER_KIND,
HermesSettings,
TextGenerationError,
type ServerProvider,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { makeHermesAdapter } from "../Layers/HermesAdapter.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
type ProviderInstance,
} from "../ProviderDriver.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
import { HermesGatewayBroker } from "../Services/HermesGatewayBroker.ts";
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
export type HermesDriverEnv = Crypto.Crypto;
const unsupportedTextGeneration = (
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Hermes gateway instances do not support utility text generation.",
}),
);
const makeTextGeneration = (): TextGenerationShape => ({
generateCommitMessage: () => unsupportedTextGeneration("generateCommitMessage"),
generatePrContent: () => unsupportedTextGeneration("generatePrContent"),
generateBranchName: () => unsupportedTextGeneration("generateBranchName"),
generateThreadTitle: () => unsupportedTextGeneration("generateThreadTitle"),
});
export const HermesDriver: ProviderDriver<HermesSettings, HermesDriverEnv> = {
driverKind: HERMES_DRIVER_KIND,
metadata: {
displayName: "Hermes",
supportsMultipleInstances: true,
},
configSchema: HermesSettings,
defaultConfig: () => decodeHermesSettings({}),
create: ({ instanceId, displayName, accentColor, enabled }) =>
Effect.gen(function* () {
const broker = yield* HermesGatewayBroker;
const adapter = yield* makeHermesAdapter({ instanceId });
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: HERMES_DRIVER_KIND,
instanceId,
});
const maintenanceCapabilities = makeManualOnlyProviderMaintenanceCapabilities({
provider: HERMES_DRIVER_KIND,
packageName: null,
});
const getSnapshot = Effect.gen(function* () {
const connected = yield* broker.isConnected(instanceId);
const status = yield* broker
.getInstanceStatus(instanceId)
.pipe(Effect.catchTag("HermesGatewayManagementError", () => Effect.succeed(undefined)));
return {
instanceId,
driver: HERMES_DRIVER_KIND,
...(displayName ? { displayName } : {}),
...(accentColor ? { accentColor } : {}),
continuation: { groupKey: continuationIdentity.continuationKey },
showInteractionModeToggle: false,
requiresNewThreadForModelChange: true,
enabled,
installed: true,
version: status?.hermesVersion ?? null,
status: !enabled ? "disabled" : connected ? "ready" : "warning",
auth: {
status: connected ? "authenticated" : "unauthenticated",
type: "gateway",
label: status?.nickname ?? displayName ?? "Hermes",
},
checkedAt: DateTime.formatIso(DateTime.nowUnsafe()),
...(!connected && enabled
? { message: "Hermes is offline. Reconnect its T3 Code gateway plugin." }
: {}),
availability: "available",
// The slug stays `DEFAULT_HERMES_MODEL` no matter what the plugin
// reports: threads bind to it, and letting it follow Hermes' current
// config would orphan every thread whose model changed on the Hermes
// side. The reported model is used only as the human-facing name, so
// the picker says "gpt-5.6-terra" instead of a generic placeholder.
// Falls back to "Hermes" when no plugin has connected yet or the
// plugin predates the `model` field on `connection.hello`.
models: [
{
slug: DEFAULT_HERMES_MODEL,
name: status?.model ?? "Hermes",
isCustom: false,
isDefault: true,
capabilities: null,
},
],
slashCommands: [],
skills: [],
} satisfies ServerProvider;
});
const snapshot = {
maintenanceCapabilities,
getSnapshot,
refresh: getSnapshot,
streamChanges: broker.streamStatuses.pipe(
Stream.filter((status) => status.instanceId === instanceId),
Stream.mapEffect(() => getSnapshot),
),
};
return {
instanceId,
driverKind: HERMES_DRIVER_KIND,
continuationIdentity,
displayName,
accentColor,
enabled,
snapshot,
adapter,
textGeneration: makeTextGeneration(),
} satisfies ProviderInstance;
}),
};
@@ -530,6 +530,29 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("preserves xhigh effort for Claude Opus 5", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-5",
[{ id: "effort", value: "xhigh" }],
),
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "xhigh");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -51,6 +51,7 @@ const CLAUDE_PRESENTATION = {
displayName: "Claude",
showInteractionModeToggle: true,
} as const;
const MINIMUM_CLAUDE_OPUS_5_VERSION = "2.1.219";
const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
@@ -87,6 +88,42 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
],
}),
},
{
slug: "claude-opus-5",
name: "Claude Opus 5",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultracode", label: "Ultracode" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Claude Code selects the 1M variant explicitly (`claude-opus-5[1m]`).
options: [
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
}),
},
{
slug: "claude-opus-4-8",
name: "Claude Opus 4.8",
@@ -272,6 +309,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
function supportsClaudeOpus5(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
}
function supportsClaudeFable5(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
}
@@ -288,6 +329,9 @@ function getBuiltInClaudeModelsForVersion(
version: string | null | undefined,
): ReadonlyArray<ServerProviderModel> {
return BUILT_IN_MODELS.filter((model) => {
if (model.slug === "claude-opus-5") {
return supportsClaudeOpus5(version);
}
if (model.slug === "claude-fable-5") {
return supportsClaudeFable5(version);
}
@@ -301,6 +345,11 @@ function getBuiltInClaudeModelsForVersion(
});
}
function formatClaudeOpus5UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Opus 5. Upgrade to v${MINIMUM_CLAUDE_OPUS_5_VERSION} or newer to access it.`;
}
function formatClaudeFable5UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
@@ -360,6 +409,7 @@ export function normalizeClaudeCliEffort(
if (
effort === "xhigh" &&
model !== "claude-fable-5" &&
model !== "claude-opus-5" &&
model !== "claude-opus-4-8" &&
model !== "claude-sonnet-5"
) {
@@ -837,13 +887,15 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)
? undefined
: supportsClaudeOpus48(parsedVersion)
? formatClaudeFable5UpgradeMessage(parsedVersion)
: supportsClaudeOpus47(parsedVersion)
? formatClaudeOpus48UpgradeMessage(parsedVersion)
: formatClaudeOpus47UpgradeMessage(parsedVersion);
: supportsClaudeFable5(parsedVersion)
? formatClaudeOpus5UpgradeMessage(parsedVersion)
: supportsClaudeOpus48(parsedVersion)
? formatClaudeFable5UpgradeMessage(parsedVersion)
: supportsClaudeOpus47(parsedVersion)
? formatClaudeOpus48UpgradeMessage(parsedVersion)
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const capabilities = resolveCapabilities
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
File diff suppressed because it is too large. Load diff
@@ -1,911 +0,0 @@
import {
EventId,
HERMES_GATEWAY_PROTOCOL_VERSION,
HermesGatewayRequestId,
HermesGatewayResumeCursor,
HermesGatewaySessionId,
ProviderDriverKind,
RuntimeItemId,
RuntimeRequestId,
ThreadId,
TurnId,
type CanonicalRequestType,
type HermesGatewayPluginToT3Message,
type ProviderInstanceId,
type ProviderRuntimeEvent,
type ProviderSession,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import {
ProviderAdapterRequestError,
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
} from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
import { HermesGatewayBroker } from "../Services/HermesGatewayBroker.ts";
const PROVIDER = ProviderDriverKind.make("hermes");
const isResumeCursor = Schema.is(HermesGatewayResumeCursor);
/**
* Hermes never queues. When the gateway socket is down there is nothing on the
* far side to accept work, and a queued turn would silently start minutes later
* against a thread the user has moved on from. Every send path fails
* immediately with this text so the failure names the fix rather than showing
* up as a generic protocol error or a 30s request timeout.
*/
const offlineDetail = (instanceId: ProviderInstanceId) =>
`Hermes is offline — the '${instanceId}' gateway plugin is not connected. Start the gateway on the Hermes host (\`hermes gateway restart\`), then retry.`;
/**
* `turns` exists only to answer `readThread`, which no Hermes call site reaches
* today. Retaining every completed item for the life of the process is an
* unbounded leak in service of that dead path, so the accumulator keeps a
* hard-capped tail of the most recent turns/items and `readThread` reports what
* it still holds. Raising these bounds is a deliberate decision, not something
* that should drift with thread length.
*/
const MAX_RETAINED_TURNS = 8;
const MAX_RETAINED_ITEMS_PER_TURN = 32;
type HermesAdapterShape = ProviderAdapterShape<
ProviderAdapterRequestError | ProviderAdapterSessionNotFoundError | ProviderAdapterValidationError
>;
interface PendingInteraction {
readonly requestId: string;
readonly turnId: TurnId;
readonly requestType: CanonicalRequestType;
}
interface SessionContext {
hermesSessionId: HermesGatewaySessionId;
readonly turns: Array<{ readonly id: TurnId; readonly items: Array<unknown> }>;
/**
* Approval and user-input requests T3 has shown but Hermes has not resolved.
* The plugin holds its side in plain dicts, so a plugin restart forgets them
* and any decision sent afterwards comes back `request-not-found`, parking
* the turn forever. Tracking them here lets a reconnect close them out.
*/
readonly pendingApprovals: Map<string, PendingInteraction>;
readonly pendingUserInputs: Map<string, PendingInteraction>;
session: ProviderSession;
}
type PluginMessage = Exclude<HermesGatewayPluginToT3Message, { readonly type: "connection.hello" }>;
const nowIso = () => DateTime.formatIso(DateTime.nowUnsafe());
const MAX_PERSISTED_GATEWAY_FIELD_CHARS = 4_096;
const boundedString = (value: unknown) =>
typeof value === "string" && value.length <= MAX_PERSISTED_GATEWAY_FIELD_CHARS
? value
: undefined;
const asRecord = (value: unknown) =>
typeof value === "object" && value !== null
? (value as Readonly<Record<string, unknown>>)
: undefined;
export const sanitizeHermesItemData = (
itemType: Extract<PluginMessage, { readonly type: "item.started" }>["itemType"],
value: unknown,
) => {
const record = asRecord(value);
if (!record) return undefined;
const fields =
itemType === "command_execution"
? ["command", "cwd"]
: itemType === "file_change"
? ["path"]
: itemType === "web_search"
? ["query"]
: itemType === "image_view"
? ["path"]
: itemType === "mcp_tool_call"
? ["server", "operation"]
: [];
const sanitized = Object.fromEntries(
fields.flatMap((field) => {
const value = boundedString(record[field]);
return value === undefined ? [] : [[field, value]];
}),
);
return Object.keys(sanitized).length > 0 ? sanitized : undefined;
};
export const sanitizeHermesRequestArgs = (
requestType: Extract<PluginMessage, { readonly type: "request.opened" }>["requestType"],
value: unknown,
) => {
const record = asRecord(value);
if (!record) return undefined;
const fields =
requestType === "command_execution_approval" || requestType === "exec_command_approval"
? ["command", "cwd"]
: requestType === "file_read_approval" ||
requestType === "file_change_approval" ||
requestType === "apply_patch_approval"
? ["path"]
: [];
const sanitized = Object.fromEntries(
fields.flatMap((field) => {
const value = boundedString(record[field]);
return value === undefined ? [] : [[field, value]];
}),
);
return Object.keys(sanitized).length > 0 ? sanitized : undefined;
};
export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input: {
readonly instanceId: ProviderInstanceId;
}) {
const crypto = yield* Crypto.Crypto;
const broker = yield* HermesGatewayBroker;
const events = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, SessionContext>();
const randomId = crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "crypto/randomUUIDv4",
detail: "Failed to generate a Hermes runtime identifier.",
cause,
}),
),
);
const requestId = randomId.pipe(
Effect.map((value) => HermesGatewayRequestId.make(`t3-${value}`)),
);
const eventBase = (message: {
readonly threadId: ThreadId;
readonly turnId?: string | undefined;
readonly itemId?: string | undefined;
readonly requestId?: string | undefined;
}) =>
randomId.pipe(
Effect.map((value) => ({
eventId: EventId.make(value),
provider: PROVIDER,
providerInstanceId: input.instanceId,
threadId: message.threadId,
createdAt: nowIso(),
...(message.turnId ? { turnId: TurnId.make(message.turnId) } : {}),
...(message.itemId ? { itemId: RuntimeItemId.make(message.itemId) } : {}),
...(message.requestId ? { requestId: RuntimeRequestId.make(message.requestId) } : {}),
})),
);
const emit = (event: ProviderRuntimeEvent) => PubSub.publish(events, event).pipe(Effect.asVoid);
const findContext = (threadId: ThreadId) =>
Effect.gen(function* (): Effect.fn.Return<SessionContext, ProviderAdapterSessionNotFoundError> {
const context = sessions.get(threadId);
if (!context) {
return yield* new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
threadId,
});
}
return context;
});
const requireConnected = (method: string) =>
Effect.gen(function* (): Effect.fn.Return<void, ProviderAdapterRequestError> {
const connected = yield* broker.isConnected(input.instanceId);
if (!connected) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method,
detail: offlineDetail(input.instanceId),
});
}
});
const updateSession = (context: SessionContext, patch: Partial<ProviderSession>) => {
context.session = {
...context.session,
...patch,
updatedAt: nowIso(),
};
};
const clearActiveTurn = (
context: SessionContext,
patch: Omit<Partial<ProviderSession>, "activeTurnId">,
) => {
const { activeTurnId: _activeTurnId, ...session } = context.session;
context.session = { ...session, ...patch, updatedAt: nowIso() };
};
const trackTurn = (context: SessionContext, turnId: TurnId) => {
if (context.turns.some((turn) => turn.id === turnId)) return;
context.turns.push({ id: turnId, items: [] });
while (context.turns.length > MAX_RETAINED_TURNS) context.turns.shift();
};
const recordCompletedItem = (context: SessionContext, turnId: string, payload: unknown) => {
const turn = context.turns.find((entry) => entry.id === turnId);
if (!turn) return;
turn.items.push(payload);
while (turn.items.length > MAX_RETAINED_ITEMS_PER_TURN) turn.items.shift();
};
/**
* Every session-scoped plugin frame names the session it belongs to. If we do
* not hold that session — because the thread was stopped, or the plugin is
* still emitting for a session we already tore down — the frame has no thread
* context on this side, and forwarding it would inject deltas and item rows
* into a thread T3 no longer tracks. `session.exited` always guarded this;
* the guard belongs on every session-scoped frame.
*/
const contextMatchesSession = (
context: SessionContext | undefined,
message: { readonly sessionId: HermesGatewaySessionId },
): context is SessionContext => context?.hermesSessionId === message.sessionId;
const toRuntimeEvent = (message: PluginMessage) =>
Effect.gen(function* (): Effect.fn.Return<
ProviderRuntimeEvent | undefined,
ProviderAdapterRequestError
> {
if (!("threadId" in message)) return undefined;
const context = sessions.get(message.threadId);
switch (message.type) {
case "session.ready":
return undefined;
case "turn.started": {
if (!contextMatchesSession(context, message)) return undefined;
updateSession(context, {
status: "running",
activeTurnId: TurnId.make(message.turnId),
});
trackTurn(context, TurnId.make(message.turnId));
return {
...(yield* eventBase(message)),
type: "turn.started",
payload: {},
};
}
case "content.delta": {
if (!contextMatchesSession(context, message)) return undefined;
return {
...(yield* eventBase(message)),
type: "content.delta",
payload: {
streamKind: message.streamKind,
delta: message.delta,
...(message.contentIndex !== undefined ? { contentIndex: message.contentIndex } : {}),
},
};
}
case "content.snapshot": {
if (!contextMatchesSession(context, message)) return undefined;
return {
...(yield* eventBase(message)),
type: "content.snapshot",
payload: {
streamKind: message.streamKind,
text: message.text,
...(message.contentIndex !== undefined ? { contentIndex: message.contentIndex } : {}),
},
};
}
case "item.started":
case "item.updated":
case "item.completed": {
if (!contextMatchesSession(context, message)) return undefined;
const data = sanitizeHermesItemData(message.itemType, message.data);
const payload = {
itemType: message.itemType,
...(message.status ? { status: message.status } : {}),
...(message.title ? { title: message.title } : {}),
...(message.detail ? { detail: message.detail } : {}),
...(data ? { data } : {}),
};
if (message.type === "item.completed") {
recordCompletedItem(context, message.turnId, payload);
}
return { ...(yield* eventBase(message)), type: message.type, payload };
}
case "request.opened": {
if (!contextMatchesSession(context, message)) return undefined;
context.pendingApprovals.set(message.requestId, {
requestId: message.requestId,
turnId: TurnId.make(message.turnId),
requestType: message.requestType,
});
const args = sanitizeHermesRequestArgs(message.requestType, message.args);
return {
...(yield* eventBase(message)),
type: "request.opened",
payload: {
requestType: message.requestType,
...(message.detail ? { detail: message.detail } : {}),
...(args ? { args } : {}),
},
};
}
case "request.resolved": {
if (!contextMatchesSession(context, message)) return undefined;
context.pendingApprovals.delete(message.requestId);
return {
...(yield* eventBase(message)),
type: "request.resolved",
payload: {
requestType: message.requestType,
...(message.decision ? { decision: message.decision } : {}),
},
};
}
case "user-input.requested": {
if (!contextMatchesSession(context, message)) return undefined;
context.pendingUserInputs.set(message.requestId, {
requestId: message.requestId,
turnId: TurnId.make(message.turnId),
requestType: "tool_user_input",
});
return {
...(yield* eventBase(message)),
type: "user-input.requested",
payload: { questions: message.questions },
};
}
case "user-input.resolved": {
if (!contextMatchesSession(context, message)) return undefined;
context.pendingUserInputs.delete(message.requestId);
return {
...(yield* eventBase(message)),
type: "user-input.resolved",
payload: { answers: message.answers },
};
}
case "turn.completed": {
if (!contextMatchesSession(context, message)) return undefined;
if (context.session.activeTurnId === message.turnId) {
clearActiveTurn(context, { status: message.state === "failed" ? "error" : "ready" });
}
return {
...(yield* eventBase(message)),
type: "turn.completed",
payload: {
state: message.state,
...(message.stopReason !== undefined ? { stopReason: message.stopReason } : {}),
...(message.errorMessage ? { errorMessage: message.errorMessage } : {}),
},
};
}
case "turn.aborted": {
if (!contextMatchesSession(context, message)) return undefined;
if (context.session.activeTurnId === message.turnId) {
clearActiveTurn(context, { status: "ready" });
}
return {
...(yield* eventBase(message)),
type: "turn.aborted",
payload: { reason: message.reason },
};
}
case "session.exited": {
if (!contextMatchesSession(context, message)) return undefined;
clearActiveTurn(context, { status: message.recoverable ? "error" : "closed" });
const base = yield* eventBase(message);
// A session Hermes has exited is gone on both sides. Dropping it here
// is what keeps the sessions map from growing without bound across a
// long-lived process's reconnect cycles.
sessions.delete(message.threadId);
return {
...base,
type: "session.exited",
payload: {
...(message.reason ? { reason: message.reason } : {}),
recoverable: message.recoverable,
exitKind: message.recoverable ? "error" : "graceful",
},
};
}
default:
return undefined;
}
});
yield* broker.stream.pipe(
Stream.filter((envelope) => envelope.instanceId === input.instanceId),
Stream.runForEach((envelope) =>
toRuntimeEvent(envelope.message).pipe(
Effect.flatMap((event) => (event ? emit(event) : Effect.void)),
),
),
Effect.forkScoped,
);
/**
* Close out every interaction the user could still be looking at.
*
* The plugin keeps `_approval_requests` / `_user_input_requests` in plain
* dicts, so a plugin restart forgets them: any decision the user makes
* afterwards is answered `request-not-found` and the turn waits on a reply
* that can never arrive. We deliberately do not decide on the user's behalf —
* each request is marked resolved with no decision, which clears the pending
* badge, and a warning row explains why it disappeared.
*/
const cancelPendingInteractions = (context: SessionContext, reason: string) =>
Effect.gen(function* () {
const approvals = Array.from(context.pendingApprovals.values());
const userInputs = Array.from(context.pendingUserInputs.values());
context.pendingApprovals.clear();
context.pendingUserInputs.clear();
if (approvals.length === 0 && userInputs.length === 0) return;
for (const pending of approvals) {
yield* emit({
...(yield* eventBase({
threadId: context.session.threadId,
turnId: pending.turnId,
requestId: pending.requestId,
})),
type: "request.resolved",
payload: { requestType: pending.requestType },
});
}
for (const pending of userInputs) {
yield* emit({
...(yield* eventBase({
threadId: context.session.threadId,
turnId: pending.turnId,
requestId: pending.requestId,
})),
type: "user-input.resolved",
payload: { answers: {} },
});
}
yield* emit({
...(yield* eventBase({ threadId: context.session.threadId })),
type: "runtime.warning",
payload: {
message: `${approvals.length + userInputs.length} pending Hermes request(s) were cancelled without a decision: ${reason} Nothing was approved or denied on your behalf — ask again to re-run the step.`,
},
});
});
/**
* Settle a thread whose turn did not survive the reconnect.
*
* Without this the turn stays "running" forever: Hermes never sends a
* terminal frame for a turn its restarted plugin no longer knows about, and
* orchestration's conflict gate rejects any later frame naming it. A failed
* `turn.completed` is the terminal event orchestration already folds into
* thread state.
*/
const settleDeadTurn = (context: SessionContext, turnId: TurnId, message: string) =>
Effect.gen(function* () {
clearActiveTurn(context, { status: "error", lastError: message });
yield* emit({
...(yield* eventBase({ threadId: context.session.threadId, turnId })),
type: "turn.completed",
payload: { state: "failed", errorMessage: message },
});
});
const resumeSessionAfterReconnect = (context: SessionContext) =>
Effect.gen(function* () {
const threadId = context.session.threadId;
const previousTurnId = context.session.activeTurnId;
yield* cancelPendingInteractions(
context,
"the Hermes gateway reconnected and the plugin no longer holds them.",
);
const outcome = yield* broker
.request(input.instanceId, {
type: "session.ensure",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: yield* requestId,
threadId,
resumeSessionId: context.hermesSessionId,
})
.pipe(Effect.result);
// Anything other than a clean session.ready leaves us unable to tell
// whether Hermes is still generating, with no channel to ask. Leaving the
// thread "running" would hang it, so it settles with the reason spelled
// out instead.
const failure =
outcome._tag === "Failure"
? `Hermes could not resume this thread after reconnecting: ${outcome.failure.detail}`
: outcome.success.type === "protocol.error"
? `Hermes rejected the resume for this thread: ${outcome.success.message}`
: outcome.success.type !== "session.ready" || outcome.success.threadId !== threadId
? `Hermes returned '${outcome.success.type}' instead of session.ready while resuming this thread.`
: undefined;
if (failure !== undefined) {
if (previousTurnId) return yield* settleDeadTurn(context, previousTurnId, failure);
updateSession(context, { status: "error", lastError: failure });
return;
}
if (outcome._tag !== "Success" || outcome.success.type !== "session.ready") return;
const ready = outcome.success;
// The session may have been stopped or exited while the request was in
// flight; do not resurrect it.
if (sessions.get(threadId) !== context) return;
// Hermes owns the session id and a restarted plugin mints a new one.
// Adopting it is what keeps the inbound context guard matching.
context.hermesSessionId = ready.sessionId;
updateSession(context, {
resumeCursor: {
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
sessionId: ready.sessionId,
} satisfies HermesGatewayResumeCursor,
});
const activeTurnId = ready.activeTurnId;
if (activeTurnId !== undefined) {
// The turn outlived the socket. Keep streaming into it and emit nothing
// disruptive — what follows belongs to the turn the UI already renders.
updateSession(context, { status: "running", activeTurnId });
trackTurn(context, activeTurnId);
return;
}
if (previousTurnId) {
yield* settleDeadTurn(
context,
previousTurnId,
"The Hermes gateway reconnected without this turn — it did not survive the disconnect.",
);
return;
}
updateSession(context, { status: "ready" });
});
/**
* The reconnect trigger. Protocol v2 already carries `activeTurnId` on
* `session.ready` for exactly this case, but nothing re-issued
* `session.ensure` after a drop — so a surviving turn's eventual
* `turn.completed` arrived for a turn orchestration had written off, was
* rejected by its conflict gate, and the thread never settled.
*/
// Track the connection identity, not merely whether we are connected. A
// plugin restart usually REPLACES the socket: the old one dies as the new
// one is accepted, so exactly one `connected` status is published and a
// connectedness edge never fires. The plugin's session map is per-process,
// so skipping the re-ensure there leaves T3 holding a session the new
// process has never heard of, and its next turn.start is rejected with
// "Call session.ensure before starting a turn" — a dead thread.
//
// Starts null rather than reading the current generation: sessions are only
// created after this point, so the first status we observe has nothing to
// resume, and treating it as new is harmless.
let seenGeneration: number | null = null;
yield* broker.streamStatuses.pipe(
Stream.filter((status) => status.instanceId === input.instanceId),
Stream.runForEach((status) =>
Effect.gen(function* () {
const generation = status.connectionGeneration;
const reconnected =
status.status === "connected" && generation !== null && generation !== seenGeneration;
// Only advance on a live connection: holding the last generation
// through an offline gap means the reconnect still registers as new.
if (generation !== null) seenGeneration = generation;
if (!reconnected) return;
// Forked, NOT awaited. `Stream.runForEach` processes status events
// serially, and the resume issues `session.ensure` — a correlated
// request whose reply is delivered by the broker's message stream.
// Awaiting it here holds up this handler, and the deadlock is only
// broken by the 30s request timeout, after which the thread is left
// with no session and every turn fails "Call session.ensure before
// starting a turn". Resuming off the handler lets the reply land.
yield* Effect.forEach(
Array.from(sessions.values()),
(context) =>
resumeSessionAfterReconnect(context).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider.hermes.resume-after-reconnect-failed", {
instanceId: input.instanceId,
threadId: context.session.threadId,
cause,
}),
),
),
{ discard: true },
).pipe(Effect.forkScoped);
}),
),
Effect.forkScoped,
);
const startSession: HermesAdapterShape["startSession"] = Effect.fn("startSession")(
function* (sessionInput) {
yield* requireConnected("session.ensure");
if (sessionInput.providerInstanceId && sessionInput.providerInstanceId !== input.instanceId) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Session targets instance '${sessionInput.providerInstanceId}', expected '${input.instanceId}'.`,
});
}
const resume =
sessionInput.resumeCursor === undefined
? undefined
: isResumeCursor(sessionInput.resumeCursor)
? sessionInput.resumeCursor
: undefined;
if (sessionInput.resumeCursor !== undefined && !resume) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: "The Hermes resume cursor is invalid or from an unsupported protocol version.",
});
}
const response = yield* broker.request(input.instanceId, {
type: "session.ensure",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: yield* requestId,
threadId: sessionInput.threadId,
...(resume ? { resumeSessionId: resume.sessionId } : {}),
});
if (response.type !== "session.ready" || response.threadId !== sessionInput.threadId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session.ensure",
detail:
response.type === "protocol.error"
? response.message
: `Expected session.ready, received '${response.type}'.`,
});
}
const createdAt = nowIso();
const activeTurnId = response.activeTurnId;
const session = {
provider: PROVIDER,
providerInstanceId: input.instanceId,
status: activeTurnId === undefined ? "ready" : "running",
runtimeMode: sessionInput.runtimeMode,
...(sessionInput.cwd !== undefined ? { cwd: sessionInput.cwd } : {}),
...(sessionInput.modelSelection?.model ? { model: sessionInput.modelSelection.model } : {}),
...(activeTurnId !== undefined ? { activeTurnId } : {}),
threadId: sessionInput.threadId,
resumeCursor: {
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
sessionId: response.sessionId,
} satisfies HermesGatewayResumeCursor,
createdAt,
updatedAt: createdAt,
} satisfies ProviderSession;
sessions.set(sessionInput.threadId, {
session,
hermesSessionId: response.sessionId,
turns: activeTurnId === undefined ? [] : [{ id: activeTurnId, items: [] }],
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
});
yield* emit({
...(yield* eventBase({ threadId: sessionInput.threadId })),
type: "session.started",
payload: {
message: response.resumed ? "Hermes session resumed" : "Hermes session started",
resume: session.resumeCursor,
},
});
yield* emit({
...(yield* eventBase({ threadId: sessionInput.threadId })),
type: "thread.started",
payload: { providerThreadId: response.sessionId },
});
return session;
},
);
const sendTurn: HermesAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (turnInput) {
const context = yield* findContext(turnInput.threadId);
if (turnInput.attachments && turnInput.attachments.length > 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Hermes gateway attachments are not supported yet.",
});
}
const text = turnInput.input;
if (!text || text.trim().length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Hermes turns require text input.",
});
}
const activeTurnId = context.session.activeTurnId;
const method = activeTurnId ? "turn.steer" : "turn.start";
// Checked before the request so an offline gateway fails immediately with
// an actionable message instead of parking on the broker's request timeout.
yield* requireConnected(method);
const turnId = activeTurnId ?? TurnId.make(`hermes-turn-${yield* randomId}`);
const outboundRequestId = yield* requestId;
const response = yield* broker.request(input.instanceId, {
type: activeTurnId ? "turn.steer" : "turn.start",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: outboundRequestId,
threadId: turnInput.threadId,
sessionId: context.hermesSessionId,
turnId,
text,
});
if (response.type !== "turn.started") {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method,
detail:
response.type === "protocol.error"
? response.message
: `Expected turn.started, received '${response.type}'.`,
});
}
updateSession(context, { status: "running", activeTurnId: turnId });
trackTurn(context, turnId);
return {
threadId: turnInput.threadId,
turnId,
resumeCursor: context.session.resumeCursor,
};
});
const adapter: HermesAdapterShape = {
provider: PROVIDER,
capabilities: { sessionModelSwitch: "unsupported" },
startSession,
sendTurn,
interruptTurn: (threadId, selectedTurnId) =>
Effect.gen(function* () {
const context = yield* findContext(threadId);
const turnId = selectedTurnId ?? context.session.activeTurnId;
if (!turnId) return;
yield* requireConnected("turn.interrupt");
yield* broker.send(input.instanceId, {
type: "turn.interrupt",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: yield* requestId,
threadId,
sessionId: context.hermesSessionId,
turnId,
});
}),
respondToRequest: (threadId, selectedRequestId, decision) =>
Effect.gen(function* () {
const context = yield* findContext(threadId);
if (!context.session.activeTurnId) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "respondToRequest",
issue: "The Hermes session has no active turn.",
});
}
yield* requireConnected("approval.respond");
yield* broker.send(input.instanceId, {
type: "approval.respond",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: HermesGatewayRequestId.make(selectedRequestId),
threadId,
sessionId: context.hermesSessionId,
turnId: context.session.activeTurnId,
decision,
});
context.pendingApprovals.delete(selectedRequestId);
}),
respondToUserInput: (threadId, selectedRequestId, answers) =>
Effect.gen(function* () {
const context = yield* findContext(threadId);
if (!context.session.activeTurnId) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "respondToUserInput",
issue: "The Hermes session has no active turn.",
});
}
yield* requireConnected("user-input.respond");
yield* broker.send(input.instanceId, {
type: "user-input.respond",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: HermesGatewayRequestId.make(selectedRequestId),
threadId,
sessionId: context.hermesSessionId,
turnId: context.session.activeTurnId,
answers,
});
context.pendingUserInputs.delete(selectedRequestId);
}),
stopSession: (threadId) =>
Effect.gen(function* () {
const context = yield* findContext(threadId);
if (!(yield* broker.isConnected(input.instanceId))) {
// The stop was never delivered: Hermes still owns this thread and
// keeps generating. Deleting our state here would orphan it — frames
// arriving after a reconnect would have no session to match, and the
// user would have no way to stop it. Keep the session so the reconnect
// path can resume it and a later stop can actually land.
updateSession(context, { status: "error", lastError: offlineDetail(input.instanceId) });
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session.stop",
detail: offlineDetail(input.instanceId),
});
}
yield* broker.send(input.instanceId, {
type: "session.stop",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: yield* requestId,
threadId,
sessionId: context.hermesSessionId,
});
updateSession(context, { status: "closed" });
sessions.delete(threadId);
}),
listSessions: () => Effect.sync(() => Array.from(sessions.values(), ({ session }) => session)),
hasSession: (threadId) => Effect.sync(() => sessions.has(threadId)),
readThread: (threadId) =>
findContext(threadId).pipe(
Effect.map((context) => ({
threadId,
// Bounded to the most recent turns/items — older history lives in the
// orchestration projections, not in adapter memory.
turns: context.turns,
})),
),
rollbackThread: (threadId) =>
findContext(threadId).pipe(
Effect.flatMap(() =>
Effect.fail(
new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "rollbackThread",
issue: "Hermes gateway thread rollback is not supported.",
}),
),
),
),
stopAll: () =>
Effect.forEach(
Array.from(sessions.keys()),
(threadId) =>
// A stop that could not be delivered (typically: the gateway is
// offline) must not abort the sweep or fail shutdown. The session is
// deliberately left in place rather than orphaned.
adapter.stopSession(threadId).pipe(
Effect.catchTag("ProviderAdapterRequestError", (error) =>
Effect.logWarning("provider.hermes.stop-session-undeliverable", {
instanceId: input.instanceId,
threadId,
detail: error.detail,
}),
),
),
{ discard: true },
),
streamEvents: Stream.fromPubSub(events),
};
// Deliberately NOT `stopAll()`. Hermes sessions live in a separate process
// that outlives this one, and `session.stop` makes the plugin drop the
// thread from its active set — so tearing down on shutdown meant every
// thread open when T3 restarted came back unusable: the next turn.start was
// rejected with "Call session.ensure before starting a turn", with no way to
// recover from the UI. Threads created after the restart worked, which is
// what made it look like a resume bug rather than a shutdown bug.
//
// Dropping local state without telling the plugin is the correct shutdown:
// the resume cursor is persisted, and the next turn re-issues session.ensure
// against the session Hermes still holds. Explicit user-initiated stops
// still go through `stopSession` and do end the remote session.
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
sessions.clear();
}),
);
return adapter;
});
@@ -1,213 +0,0 @@
/**
* Live {@link HermesConnectionRegistry}. See the service module for why this
* state is memory-only and how generation fencing works.
*
* @module Layers/HermesConnectionRegistry
*/
import type { ProviderInstanceId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import type {
HermesActiveConnection,
HermesConnectionRegistry,
HermesInstanceLiveness,
HermesLivenessStatusFields,
HermesObservedConnection,
} from "../Services/HermesConnectionRegistry.ts";
/** Strip the transport/scope/generation from a connection to keep as `lastSeen`. */
const toObserved = (connection: HermesActiveConnection): HermesObservedConnection => ({
pluginVersion: connection.pluginVersion,
hermesVersion: connection.hermesVersion,
capabilities: connection.capabilities,
model: connection.model,
connectedAt: connection.connectedAt,
activeSessionCount: connection.activeSessionCount,
});
/**
* Project liveness into the status fields it owns. Prefers the live connection,
* falls back to `lastSeen`, and finally to whatever the incompatible plugin
* advertised.
*/
export const livenessStatusFields = (
liveness: HermesInstanceLiveness | undefined,
): HermesLivenessStatusFields => {
const observed = liveness?.connection ?? liveness?.lastSeen;
return {
lastConnectedAt: observed?.connectedAt ?? null,
pluginVersion: observed?.pluginVersion ?? liveness?.upgradeRequired?.pluginVersion ?? null,
hermesVersion: observed?.hermesVersion ?? liveness?.upgradeRequired?.hermesVersion ?? null,
model: observed?.model ?? liveness?.upgradeRequired?.model ?? null,
activeSessionCount: liveness?.connection?.activeSessionCount ?? 0,
protocolVersion:
observed?.capabilities.protocolVersion ?? liveness?.upgradeRequired?.protocolVersion ?? null,
capabilities: observed?.capabilities ?? null,
// Exposed so consumers can tell a replacement (old socket dies as a new
// one is accepted, publishing a single `connected` status) from a
// continuous connection. Watching connectedness alone cannot.
connectionGeneration: liveness?.connection?.generation ?? null,
connected: liveness?.connection !== undefined,
upgradeRequired: liveness?.upgradeRequired !== undefined,
};
};
export const makeHermesConnectionRegistry = Effect.gen(function* () {
const states = yield* Ref.make(new Map<ProviderInstanceId, HermesInstanceLiveness>());
const generation = yield* Ref.make(0);
/** Write liveness for one instance, dropping the entry when it goes empty. */
const setLiveness = (
current: ReadonlyMap<ProviderInstanceId, HermesInstanceLiveness>,
instanceId: ProviderInstanceId,
liveness: HermesInstanceLiveness,
) => {
const next = new Map(current);
if (
liveness.connection === undefined &&
liveness.lastSeen === undefined &&
liveness.upgradeRequired === undefined
) {
next.delete(instanceId);
} else {
next.set(instanceId, liveness);
}
return next;
};
const liveness = (instanceId: ProviderInstanceId) =>
Ref.get(states).pipe(Effect.map((current) => current.get(instanceId)));
const accept: HermesConnectionRegistry["accept"] = (input) =>
Effect.gen(function* () {
const nextGeneration = yield* Ref.getAndUpdate(generation, (value) => value + 1);
// The connection scope is a child of nothing in particular: it is closed
// explicitly on disconnect/replace so per-connection fibers (ping) die
// exactly with the connection they belong to.
const scope = yield* Scope.make();
const connection: HermesActiveConnection = {
...input.observed,
generation: nextGeneration,
transport: input.transport,
scope,
};
const displaced = yield* Ref.modify(states, (current) => {
const found = current.get(input.instanceId);
return [
found?.connection,
setLiveness(current, input.instanceId, {
connection,
lastSeen: toObserved(connection),
// Accepting a compatible connection clears any stale
// upgrade-required observation for this instance.
upgradeRequired: undefined,
}),
] as const;
});
return { generation: nextGeneration, displaced };
});
const markUpgradeRequired: HermesConnectionRegistry["markUpgradeRequired"] = (input) =>
Ref.modify(states, (current) => {
const found = current.get(input.instanceId);
return [
found?.connection,
setLiveness(current, input.instanceId, {
connection: undefined,
lastSeen: found?.lastSeen,
upgradeRequired: input.upgradeRequired,
}),
] as const;
});
const recordSessionCount: HermesConnectionRegistry["recordSessionCount"] = (
registration,
activeSessionCount,
) =>
Ref.modify(states, (current) => {
const found = current.get(registration.instanceId);
// Fence inside the update so a replacement that lands between a read and
// this write cannot be clobbered.
if (found?.connection?.generation !== registration.generation) {
return [false, current] as const;
}
const connection: HermesActiveConnection = { ...found.connection, activeSessionCount };
return [
true,
setLiveness(current, registration.instanceId, {
...found,
connection,
lastSeen: toObserved(connection),
}),
] as const;
});
const disconnect: HermesConnectionRegistry["disconnect"] = (registration) =>
Effect.gen(function* () {
const retired = yield* Ref.modify(states, (current) => {
const found = current.get(registration.instanceId);
if (found?.connection?.generation !== registration.generation) {
return [undefined, current] as const;
}
return [
found.connection,
setLiveness(current, registration.instanceId, {
connection: undefined,
lastSeen: toObserved(found.connection),
upgradeRequired: found.upgradeRequired,
}),
] as const;
});
if (retired) yield* Scope.close(retired.scope, Exit.void).pipe(Effect.ignore);
return retired;
});
const clearConnection: HermesConnectionRegistry["clearConnection"] = (instanceId) =>
Effect.gen(function* () {
const cleared = yield* Ref.modify(states, (current) => {
const found = current.get(instanceId);
if (!found?.connection) return [undefined, current] as const;
return [
found.connection,
setLiveness(current, instanceId, {
connection: undefined,
lastSeen: toObserved(found.connection),
upgradeRequired: found.upgradeRequired,
}),
] as const;
});
if (cleared) yield* Scope.close(cleared.scope, Exit.void).pipe(Effect.ignore);
return cleared;
});
const forget = (instanceId: ProviderInstanceId) =>
Effect.gen(function* () {
const dropped = yield* Ref.modify(states, (current) => {
const found = current.get(instanceId);
if (!found) return [undefined, current] as const;
const next = new Map(current);
next.delete(instanceId);
return [found.connection, next] as const;
});
if (dropped) yield* Scope.close(dropped.scope, Exit.void).pipe(Effect.ignore);
});
return {
liveness,
accept,
markUpgradeRequired,
recordSessionCount,
disconnect,
clearConnection,
forget,
isConnected: (instanceId) =>
liveness(instanceId).pipe(Effect.map((found) => found?.connection !== undefined)),
transport: (instanceId) =>
liveness(instanceId).pipe(Effect.map((found) => found?.connection?.transport)),
} satisfies HermesConnectionRegistry;
});
@@ -1,106 +0,0 @@
/**
* Live {@link HermesEnrollmentStore}. See the service module for the token
* rules this upholds.
*
* @module Layers/HermesEnrollmentStore
*/
import { HermesGatewayEnrollmentToken, type ProviderInstanceId } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Ref from "effect/Ref";
import type {
HermesEnrollmentStore,
PendingEnrollment,
} from "../Services/HermesEnrollmentStore.ts";
const ENROLLMENT_TOKEN_BYTES = 32;
export interface MakeHermesEnrollmentStoreOptions {
readonly ttl: Duration.Duration;
}
export const makeHermesEnrollmentStore = (
options: MakeHermesEnrollmentStoreOptions,
): Effect.Effect<HermesEnrollmentStore, never, Crypto.Crypto> =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const enrollments = yield* Ref.make(new Map<string, PendingEnrollment>());
const mint: HermesEnrollmentStore["mint"] = (input) =>
Effect.gen(function* () {
const bytes = yield* crypto.randomBytes(ENROLLMENT_TOKEN_BYTES).pipe(Effect.orDie);
const token = HermesGatewayEnrollmentToken.make(Encoding.encodeBase64Url(bytes));
const expiresAtMillis = (yield* Clock.currentTimeMillis) + Duration.toMillis(options.ttl);
yield* Ref.update(enrollments, (current) => {
const next = new Map(current);
// Minting supersedes this instance's previous tokens so only the
// newest unconsumed token is redeemable.
for (const [pendingToken, pending] of current) {
if (pending.input.instanceId === input.instanceId) next.delete(pendingToken);
}
return next.set(token, { input, expiresAtMillis });
});
return { token, expiresAtMillis };
});
const peek: HermesEnrollmentStore["peek"] = (token) =>
Effect.gen(function* () {
const found = (yield* Ref.get(enrollments)).get(token);
if (!found) return undefined;
return found.expiresAtMillis < (yield* Clock.currentTimeMillis) ? undefined : found;
});
const consume: HermesEnrollmentStore["consume"] = (token, expected) =>
Effect.gen(function* () {
// Compare-and-swap: delete only if the entry is still the exact object
// the caller authenticated against, so a concurrent redemption or a
// re-mint in between cannot be consumed by this caller.
const claimed = yield* Ref.modify(enrollments, (current) => {
const found = current.get(token);
if (found !== expected) return [undefined, current] as const;
const next = new Map(current);
next.delete(token);
return [found, next] as const;
});
if (claimed === undefined) return undefined;
// Re-check expiry after winning the swap: the entry may have aged out
// between authentication and consumption.
return claimed.expiresAtMillis < (yield* Clock.currentTimeMillis) ? undefined : claimed;
});
const forget = (instanceId: ProviderInstanceId) =>
Ref.update(enrollments, (current) => {
const next = new Map(current);
for (const [token, pending] of current) {
if (pending.input.instanceId === instanceId) next.delete(token);
}
return next;
});
const sweep = Clock.currentTimeMillis.pipe(
Effect.flatMap((now) =>
Ref.update(enrollments, (current) => {
const next = new Map(current);
for (const [token, pending] of current) {
if (pending.expiresAtMillis < now) next.delete(token);
}
return next.size === current.size ? current : next;
}),
),
);
return {
mint,
peek,
consume,
forget,
sweep,
size: Ref.get(enrollments).pipe(Effect.map((current) => current.size)),
} satisfies HermesEnrollmentStore;
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,37 +0,0 @@
import { assert, it } from "@effect/vitest";
import {
DEFAULT_SERVER_SETTINGS,
HERMES_DRIVER_KIND,
ProviderInstanceId,
} from "@t3tools/contracts";
import { deriveProviderInstanceConfigMap } from "./ProviderInstanceRegistryHydration.ts";
it("does not synthesize a legacy default Hermes instance", () => {
const instances = deriveProviderInstanceConfigMap(DEFAULT_SERVER_SETTINGS);
assert.isUndefined(instances[ProviderInstanceId.make("hermes")]);
assert.equal(instances[ProviderInstanceId.make("codex")]?.driver, "codex");
});
it("preserves an explicit Hermes instance whose id matches the driver default", () => {
const instanceId = ProviderInstanceId.make("hermes");
const instances = deriveProviderInstanceConfigMap({
...DEFAULT_SERVER_SETTINGS,
providerInstances: {
[instanceId]: {
driver: HERMES_DRIVER_KIND,
displayName: "Research Hermes",
enabled: true,
config: {},
},
},
});
assert.deepEqual(instances[instanceId], {
driver: HERMES_DRIVER_KIND,
displayName: "Research Hermes",
enabled: true,
config: {},
});
});
@@ -18,8 +18,7 @@
* `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a
* routing slug), we synthesize an envelope from the legacy field. The
* registry decodes both flavours through the same `configSchema` and ends
* up with one uniform `ProviderInstance` per entry. Drivers such as Hermes
* that require an explicitly paired remote instance opt out of synthesis.
* up with one uniform `ProviderInstance` per entry.
*
* Explicit `providerInstances` entries always win — users can already
* override the legacy `providers.<kind>` blob by authoring a
@@ -44,7 +43,6 @@
*/
import {
defaultInstanceIdForDriver,
HERMES_DRIVER_KIND,
type ProviderInstanceConfig,
type ProviderInstanceConfigMap,
ServerSettings,
@@ -64,10 +62,9 @@ import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistry
*
* Strategy:
* 1. Copy all explicit `settings.providerInstances` entries verbatim.
* 2. For each legacy-compatible built-in driver whose
* `defaultInstanceIdForDriver(id)` key is *not* already in the explicit
* map, synthesize an entry from the matching legacy
* `settings.providers.<kind>` blob.
* 2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key
* is *not* already in the explicit map, synthesize an entry from the
* matching legacy `settings.providers.<kind>` blob.
*
* The returned map is the input the registry consumes; pure & exported
* separately so the hydration logic can be exercised by unit tests
@@ -85,12 +82,6 @@ export const deriveProviderInstanceConfigMap = (
// config always wins over the legacy mirror.
continue;
}
if (driver.driverKind === HERMES_DRIVER_KIND) {
// Hermes is configured only through explicit gateway instances. A
// synthesized legacy default would resurrect a revoked-and-removed
// instance in settings and provider pickers.
continue;
}
// Only built-in drivers have a legacy mirror; the registry's
// `providers` struct is keyed on the same literal slug as
@@ -280,24 +280,20 @@ function makeMutableServerSettingsService(
return Effect.gen(function* () {
const settingsRef = yield* Ref.make(initial);
const changes = yield* PubSub.unbounded<ContractServerSettings>();
const updateSettingsWith = (
update: (current: ContractServerSettings) => Parameters<typeof applyServerSettingsPatch>[1],
) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = applyServerSettingsPatch(current, update(current));
encodeServerSettings(next);
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
});
return {
start: Effect.void,
ready: Effect.void,
getSettings: Ref.get(settingsRef),
updateSettings: (patch) => updateSettingsWith(() => patch),
updateSettingsWith,
updateSettings: (patch) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = applyServerSettingsPatch(current, patch);
encodeServerSettings(next);
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
}),
get streamChanges() {
return Stream.fromPubSub(changes);
},
@@ -1846,6 +1842,62 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
),
);
it.effect("includes Claude Opus 5 on supported Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
claudeCapabilities(),
);
const opus5 = status.models.find((model) => model.slug === "claude-opus-5");
assert.strictEqual(opus5?.name, "Claude Opus 5");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.219\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides Claude Opus 5 on older Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
claudeCapabilities(),
);
assert.strictEqual(
status.models.some((model) => model.slug === "claude-opus-5"),
false,
);
assert.strictEqual(
status.message,
"Claude Code v2.1.218 is too old for Claude Opus 5. Upgrade to v2.1.219 or newer to access it.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.218\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
@@ -1280,170 +1280,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
}
}
yield* advanceTestClock(50);
routing.codex.emit({
type: "turn.completed",
eventId: asEventId("evt-runtime-status-stale-completion"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:01.000Z",
threadId: session.threadId,
turnId: asTurnId("turn-from-an-older-request"),
payload: {
state: "completed",
},
});
yield* advanceTestClock(50);
const afterStaleCompletion = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterStaleCompletion), true);
if (Option.isSome(afterStaleCompletion)) {
assert.equal(afterStaleCompletion.value.status, "running");
const payload = afterStaleCompletion.value.runtimePayload;
assert.equal(payload !== null && typeof payload === "object", true);
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal(
"activeTurnId" in payload ? payload.activeTurnId : undefined,
`turn-${String(session.threadId)}`,
);
assert.equal(
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
"turn.completed",
);
}
}
routing.codex.emit({
type: "turn.completed",
eventId: asEventId("evt-runtime-status-active-completion"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:02.000Z",
threadId: session.threadId,
turnId: asTurnId(`turn-${String(session.threadId)}`),
payload: {
state: "completed",
},
});
yield* advanceTestClock(50);
const afterActiveCompletion = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterActiveCompletion), true);
if (Option.isSome(afterActiveCompletion)) {
assert.equal(afterActiveCompletion.value.status, "running");
const payload = afterActiveCompletion.value.runtimePayload;
assert.equal(payload !== null && typeof payload === "object", true);
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
assert.equal("cwd" in payload ? payload.cwd : undefined, session.cwd);
assert.equal(
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
"turn.completed",
);
}
}
// A *failed* completion of the active turn must persist "error". This
// shared a ternary branch with turn.started and wrote "running" for every
// settled turn, failed ones included.
yield* provider.sendTurn({
threadId: session.threadId,
input: "hello again",
attachments: [],
});
yield* advanceTestClock(50);
routing.codex.emit({
type: "turn.completed",
eventId: asEventId("evt-runtime-status-failed-completion"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:02.500Z",
threadId: session.threadId,
turnId: asTurnId(`turn-${String(session.threadId)}`),
payload: {
state: "failed",
errorMessage: "Hermes could not resume this thread after reconnecting.",
},
});
yield* advanceTestClock(50);
const afterFailedCompletion = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterFailedCompletion), true);
if (Option.isSome(afterFailedCompletion)) {
assert.equal(afterFailedCompletion.value.status, "error");
const payload = afterFailedCompletion.value.runtimePayload;
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
}
}
// A matching turn.aborted settles the same way, minus the error.
yield* provider.sendTurn({
threadId: session.threadId,
input: "hello once more",
attachments: [],
});
yield* advanceTestClock(50);
routing.codex.emit({
type: "turn.aborted",
eventId: asEventId("evt-runtime-status-active-abort"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:02.750Z",
threadId: session.threadId,
turnId: asTurnId(`turn-${String(session.threadId)}`),
payload: { reason: "interrupted" },
});
yield* advanceTestClock(50);
const afterAbort = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterAbort), true);
if (Option.isSome(afterAbort)) {
assert.equal(afterAbort.value.status, "running");
const payload = afterAbort.value.runtimePayload;
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
assert.equal(
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
"turn.aborted",
);
}
}
routing.codex.emit({
type: "session.exited",
eventId: asEventId("evt-runtime-status-session-exit"),
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:03.000Z",
threadId: session.threadId,
payload: {
exitKind: "error",
recoverable: true,
},
});
yield* advanceTestClock(50);
const afterSessionExit = yield* runtimeRepository.getByThreadId({
threadId: session.threadId,
});
assert.equal(Option.isSome(afterSessionExit), true);
if (Option.isSome(afterSessionExit)) {
assert.equal(afterSessionExit.value.status, "error");
const payload = afterSessionExit.value.runtimePayload;
assert.equal(payload !== null && typeof payload === "object", true);
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
assert.equal("activeTurnId" in payload ? payload.activeTurnId : undefined, null);
assert.equal(
"lastRuntimeEvent" in payload ? payload.lastRuntimeEvent : undefined,
"session.exited",
);
}
}
}),
);
@@ -162,19 +162,6 @@ function readPersistedCwd(
return trimmed.length > 0 ? trimmed : undefined;
}
function readPersistedActiveTurnId(
runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
): string | null | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const rawActiveTurnId =
"activeTurnId" in runtimePayload ? runtimePayload.activeTurnId : undefined;
return typeof rawActiveTurnId === "string" || rawActiveTurnId === null
? rawActiveTurnId
: undefined;
}
const dieOnMissingBindingInstanceId = (
operation: string,
payload: {
@@ -294,84 +281,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
});
});
const persistRuntimeLifecycle = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
if (
event.type !== "turn.started" &&
event.type !== "turn.completed" &&
event.type !== "turn.aborted" &&
event.type !== "session.exited"
) {
return;
}
const binding = Option.getOrUndefined(yield* directory.getBinding(event.threadId));
if (!binding || event.providerInstanceId === undefined) {
return;
}
if (
binding.provider !== event.provider ||
binding.providerInstanceId !== event.providerInstanceId
) {
yield* Effect.logWarning("provider.session.runtime.lifecycle-binding-mismatch", {
threadId: event.threadId,
eventProvider: event.provider,
eventProviderInstanceId: event.providerInstanceId,
bindingProvider: binding.provider,
bindingProviderInstanceId: binding.providerInstanceId,
eventType: event.type,
});
return;
}
const persistedActiveTurnId = readPersistedActiveTurnId(binding.runtimePayload);
const terminalMatchesActiveTurn =
(event.type === "turn.completed" || event.type === "turn.aborted") &&
event.turnId !== undefined &&
persistedActiveTurnId === event.turnId;
const isSessionExit = event.type === "session.exited";
// `turn.started` and a terminal event that closes the active turn are
// opposite transitions and must not share a branch. Folded together they
// persisted "running" for every settled turn — including a *failed* one,
// which is the lie this split removes.
//
// A non-failed terminal still writes "running": this status describes the
// session, not the turn (`toRuntimeStatus` maps both ready and running to
// it), and the settled turn is expressed by `activeTurnId: null` below.
// "stopped" is reserved for sessions that are actually gone — the reaper
// skips those, so using it for an idle session would strand it.
const status =
event.type === "turn.started"
? "running"
: terminalMatchesActiveTurn
? event.type === "turn.completed" && event.payload.state === "failed"
? "error"
: "running"
: isSessionExit
? event.payload.recoverable === true || event.payload.exitKind === "error"
? "error"
: "stopped"
: undefined;
const activeTurnId =
event.type === "turn.started"
? (event.turnId ?? persistedActiveTurnId)
: terminalMatchesActiveTurn || isSessionExit
? null
: persistedActiveTurnId;
yield* directory.upsert({
threadId: event.threadId,
provider: event.provider,
providerInstanceId: event.providerInstanceId,
...(status !== undefined ? { status } : {}),
runtimePayload: {
...(activeTurnId !== undefined ? { activeTurnId } : {}),
lastRuntimeEvent: event.type,
lastRuntimeEventAt: event.createdAt,
},
});
});
const processRuntimeEvent = (
source: {
readonly instanceId: ProviderInstanceId;
@@ -384,22 +293,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
increment(providerRuntimeEventsTotal, {
provider: canonicalEvent.provider,
eventType: canonicalEvent.type,
}).pipe(
Effect.andThen(
persistRuntimeLifecycle(canonicalEvent).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.runtime.lifecycle-persist-failed", {
threadId: canonicalEvent.threadId,
provider: canonicalEvent.provider,
providerInstanceId: canonicalEvent.providerInstanceId,
eventType: canonicalEvent.type,
errorTag: causeErrorTag(cause),
}),
),
),
),
Effect.andThen(publishRuntimeEvent(canonicalEvent)),
),
}).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),
),
);
@@ -196,6 +196,7 @@ describe("ProviderSessionReaper", () => {
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
getCounts: () => Effect.die("unused"),
@@ -1,160 +0,0 @@
/**
* Live {@link RequestCorrelator} implementation.
*
* Generic over the owner key (the route a request travels over) and the
* response payload, so this is reusable by any provider with correlated
* request/response framing — see the module docs on the service for why the
* interrupt-safety and sweeping guarantees live here rather than at call sites.
*
* @module Layers/RequestCorrelator
*/
import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Ref from "effect/Ref";
import { ProviderAdapterRequestError } from "../Errors.ts";
import type { RequestCorrelator, RequestCorrelatorSend } from "../Services/RequestCorrelator.ts";
interface PendingRequest<Owner, Response> {
readonly owner: Owner;
readonly method: string;
readonly registeredAtMillis: number;
readonly deferred: Deferred.Deferred<Response, ProviderAdapterRequestError>;
}
export interface MakeRequestCorrelatorOptions {
/** Provider name stamped onto `ProviderAdapterRequestError`. */
readonly provider: string;
/** Default response timeout when a request does not override it. */
readonly timeout: Duration.Duration;
/**
* Entries older than this are reaped by `sweep`. Comfortably larger than
* `timeout` so the sweeper only ever catches entries whose own timeout
* pipeline failed to run — a normal slow request is never stolen from
* underneath its awaiting fiber.
*/
readonly maxAge: Duration.Duration;
}
export const makeRequestCorrelator = <Owner, Response>(
options: MakeRequestCorrelatorOptions,
): Effect.Effect<RequestCorrelator<Owner, Response>> =>
Effect.gen(function* () {
const pending = yield* Ref.make(new Map<string, PendingRequest<Owner, Response>>());
const requestError = (method: string, detail: string) =>
new ProviderAdapterRequestError({ provider: options.provider, method, detail });
/** Remove one entry by id. Safe to call when it is already gone. */
const release = (requestId: string) =>
Ref.update(pending, (current) => {
if (!current.has(requestId)) return current;
const next = new Map(current);
next.delete(requestId);
return next;
});
const request = (input: RequestCorrelatorSend<Owner>) =>
Effect.gen(function* () {
const deferred = yield* Deferred.make<Response, ProviderAdapterRequestError>();
const registeredAtMillis = yield* Clock.currentTimeMillis;
// Registration and the send must not be interruptible independently of
// the cleanup that removes the entry. `uninterruptibleMask` closes the
// window: the registration is applied, `restore` re-enables interrupts
// only inside the awaiting pipeline, and `ensuring` guarantees release
// regardless of how that pipeline exits.
return yield* Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
yield* Ref.update(pending, (current) =>
new Map(current).set(input.requestId, {
owner: input.owner,
method: input.method,
registeredAtMillis,
deferred,
}),
);
yield* input.send.pipe(Effect.tapError(() => release(input.requestId)));
return yield* restore(Deferred.await(deferred)).pipe(
Effect.timeout(input.timeout ?? options.timeout),
Effect.mapError((error) =>
error._tag === "TimeoutError"
? requestError(input.method, `${options.provider} request timed out.`)
: error,
),
Effect.ensuring(release(input.requestId)),
);
}),
);
});
const complete = (requestId: string, response: Response) =>
Ref.modify(pending, (current) => {
const found = current.get(requestId);
if (!found) return [undefined, current] as const;
const next = new Map(current);
next.delete(requestId);
return [found, next] as const;
}).pipe(
Effect.flatMap((found) =>
found === undefined
? Effect.succeed(false)
: Deferred.succeed(found.deferred, response).pipe(Effect.as(true)),
),
);
/**
* Extract every entry matching `select`, then fail their deferreds. The
* extraction is a single `Ref.modify` so two concurrent failures cannot
* both claim the same entry.
*/
const failMatching = (
select: (entry: PendingRequest<Owner, Response>) => boolean,
detail: (entry: PendingRequest<Owner, Response>) => string,
) =>
Ref.modify(pending, (current) => {
const claimed: Array<PendingRequest<Owner, Response>> = [];
const next = new Map(current);
for (const [requestId, entry] of current) {
if (!select(entry)) continue;
claimed.push(entry);
next.delete(requestId);
}
return [claimed, next] as const;
}).pipe(
Effect.flatMap((claimed) =>
Effect.forEach(
claimed,
(entry) => Deferred.fail(entry.deferred, requestError(entry.method, detail(entry))),
{ discard: true },
),
),
);
const failOwner = (owner: Owner, detail: string) =>
failMatching(
(entry) => entry.owner === owner,
() => detail,
);
const sweep = Clock.currentTimeMillis.pipe(
Effect.flatMap((now) =>
failMatching(
(entry) => now - entry.registeredAtMillis >= Duration.toMillis(options.maxAge),
() => `${options.provider} request was abandoned before it completed.`,
),
),
);
return {
request,
complete,
failOwner,
sweep,
pendingCount: Ref.get(pending).pipe(Effect.map((current) => current.size)),
} satisfies RequestCorrelator<Owner, Response>;
});
@@ -1,167 +0,0 @@
/**
* HermesConnectionRegistry — owner of **volatile** Hermes gateway liveness.
*
* Everything in here is deliberately memory-only and is never persisted:
* the live connection, its transport, `lastSeen`, `activeSessionCount`, the
* reported model, and the `upgrade-required` observation.
*
* Why liveness must not be persisted
* ----------------------------------
* `ProviderInstanceRegistryLive.reconcile` structurally compares each
* `ProviderInstanceConfig` envelope and closes the instance scope on **any**
* change. Closing that scope runs `HermesAdapter`'s finalizer, which calls
* `stopAll()` and sends `session.stop` to Hermes for every live thread. So
* writing something like `connectedAt` into the instance config on every
* connect would tear down every Hermes session on every reconnect.
*
* The broker (and therefore this registry) is a top-level layer that survives
* reconcile, which makes it the correct owner of liveness. The accepted
* consequence is that after a T3 server restart the UI reports "never
* connected" until the plugin dials back in. That is intended.
*
* Generation fencing
* ------------------
* Every accepted connection gets a monotonically increasing generation. All
* post-acceptance mutations are fenced on it, and the comparison happens
* *inside* the `Ref` update rather than as a separate read, so a replacement
* landing concurrently cannot be clobbered by a stale writer (TOCTOU).
*
* @module HermesConnectionRegistry
*/
import type {
HermesGatewayCapabilities,
HermesGatewayInstanceStatus,
ProviderInstanceId,
} from "@t3tools/contracts";
import type * as Effect from "effect/Effect";
import type * as Scope from "effect/Scope";
import type {
HermesGatewayConnectionRegistration,
HermesGatewayTransport,
} from "./HermesGatewayBroker.ts";
/** Observed facts about a plugin connection, independent of its transport. */
export interface HermesObservedConnection {
readonly pluginVersion: string;
readonly hermesVersion: string;
readonly capabilities: HermesGatewayCapabilities;
/** Model reported at handshake. Null when the plugin predates the field. */
readonly model: string | null;
readonly connectedAt: string;
readonly activeSessionCount: number;
}
export interface HermesActiveConnection extends HermesObservedConnection {
readonly generation: number;
readonly transport: HermesGatewayTransport;
/**
* Scope tied to this connection's lifetime. Per-connection fibers (the ping
* loop) are forked into it, so they die exactly when the connection does.
*/
readonly scope: Scope.Closeable;
}
export interface HermesUpgradeRequired {
readonly pluginVersion: string;
readonly hermesVersion: string;
readonly protocolVersion: number;
readonly model: string | null;
}
/** Volatile per-instance liveness. Absent entry means "nothing observed yet". */
export interface HermesInstanceLiveness {
readonly connection?: HermesActiveConnection | undefined;
readonly lastSeen?: HermesObservedConnection | undefined;
readonly upgradeRequired?: HermesUpgradeRequired | undefined;
}
export interface HermesAcceptedConnection {
readonly generation: number;
/**
* The connection this one displaced, if any. The caller is responsible for
* closing it — the registry never touches a transport itself, so callers can
* order the close against failing pending requests.
*/
readonly displaced: HermesActiveConnection | undefined;
}
export interface HermesConnectionRegistry {
/** Current liveness for one instance, or `undefined` if nothing observed. */
readonly liveness: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesInstanceLiveness | undefined>;
/** Accept a connection, assigning it the next generation. */
readonly accept: (input: {
readonly instanceId: ProviderInstanceId;
readonly transport: HermesGatewayTransport;
readonly observed: HermesObservedConnection;
}) => Effect.Effect<HermesAcceptedConnection>;
/**
* Record an incompatible plugin. Clears any live connection for the instance
* and returns it so the caller can close it.
*/
readonly markUpgradeRequired: (input: {
readonly instanceId: ProviderInstanceId;
readonly upgradeRequired: HermesUpgradeRequired;
}) => Effect.Effect<HermesActiveConnection | undefined>;
/**
* Update the active session count. Generation-fenced; returns `false` when
* the registration is stale, in which case nothing was written.
*/
readonly recordSessionCount: (
registration: HermesGatewayConnectionRegistration,
activeSessionCount: number,
) => Effect.Effect<boolean>;
/**
* Retire a connection, demoting it to `lastSeen`. Generation-fenced;
* returns the retired connection, or `undefined` when the registration is
* stale (already replaced) and nothing was changed.
*/
readonly disconnect: (
registration: HermesGatewayConnectionRegistration,
) => Effect.Effect<HermesActiveConnection | undefined>;
/**
* Clear the live connection for an instance regardless of generation, e.g.
* on revoke. Returns it so the caller can close the transport.
*/
readonly clearConnection: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesActiveConnection | undefined>;
/** Drop all liveness for an instance (on remove). */
readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect<void>;
/** Whether a live connection exists. */
readonly isConnected: (instanceId: ProviderInstanceId) => Effect.Effect<boolean>;
/** Live transport for an instance, if connected. */
readonly transport: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesGatewayTransport | undefined>;
}
/**
* Project the status fields owned by liveness. The durable half (nickname,
* connectorUrl, revoked) is layered on by the broker, which reads it from
* settings.
*/
export type HermesLivenessStatusFields = Pick<
HermesGatewayInstanceStatus,
| "lastConnectedAt"
| "pluginVersion"
| "hermesVersion"
| "model"
| "activeSessionCount"
| "protocolVersion"
| "capabilities"
| "connectionGeneration"
> & {
readonly connected: boolean;
readonly upgradeRequired: boolean;
};
@@ -1,68 +0,0 @@
/**
* HermesEnrollmentStore — the mint/consume/expire lifecycle of one-time
* enrollment tokens.
*
* Separated from the broker so the token rules live in one place:
*
* - A token is redeemable exactly once. Consumption is compare-and-swap:
* the entry is deleted only if it is still byte-identical to the one the
* caller authenticated against, and expiry is re-checked afterwards, so
* two concurrent redemptions cannot both win.
* - Minting a token for an instance invalidates that instance's previous
* tokens, so only the newest unconsumed token is ever redeemable.
* - Tokens expire from memory on a sweep, not only lazily at redemption.
* Redemption-time expiry alone let any operator-scoped client grow the
* map without bound by calling createEnrollment in a loop.
*
* @module HermesEnrollmentStore
*/
import type {
HermesGatewayCreateEnrollmentInput,
HermesGatewayEnrollmentToken,
ProviderInstanceId,
} from "@t3tools/contracts";
import type * as Effect from "effect/Effect";
export interface PendingEnrollment {
readonly input: HermesGatewayCreateEnrollmentInput;
readonly expiresAtMillis: number;
}
export interface HermesEnrollmentStore {
/**
* Mint a token for `input`, invalidating any prior unconsumed token for the
* same instance. Returns the token and its absolute expiry.
*/
readonly mint: (
input: HermesGatewayCreateEnrollmentInput,
) => Effect.Effect<
{ readonly token: HermesGatewayEnrollmentToken; readonly expiresAtMillis: number },
never
>;
/**
* Look up a token without consuming it. Returns `undefined` when the token
* is unknown or already expired — the caller authenticates against this
* value and later passes it back to `consume`.
*/
readonly peek: (token: string) => Effect.Effect<PendingEnrollment | undefined>;
/**
* Compare-and-swap consumption. Deletes the entry only if it is still
* identical to `expected`, then re-checks expiry. Returns the consumed
* enrollment, or `undefined` if it was raced away or expired in between.
*/
readonly consume: (
token: string,
expected: PendingEnrollment,
) => Effect.Effect<PendingEnrollment | undefined>;
/** Drop every unconsumed token belonging to `instanceId`. */
readonly forget: (instanceId: ProviderInstanceId) => Effect.Effect<void>;
/** Drop every expired token. Run periodically; bounds memory. */
readonly sweep: Effect.Effect<void>;
/** Number of unconsumed tokens. Exposed for tests and diagnostics. */
readonly size: Effect.Effect<number>;
}
@@ -1,112 +0,0 @@
import type {
HermesGatewayConnectionHello,
HermesGatewayCreateEnrollmentInput,
HermesGatewayEnrollmentResult,
HermesGatewayInstanceStatus,
HermesGatewayPluginToT3Message,
HermesGatewayRemoveInstanceResult,
HermesGatewayRenameInstanceInput,
HermesGatewayRenameInstanceResult,
HermesGatewayRevokeInstanceResult,
HermesGatewayT3ToPluginMessage,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import type { HermesGatewayManagementError } from "@t3tools/contracts";
import type { ProviderAdapterRequestError } from "../Errors.ts";
export interface HermesGatewayTransport {
readonly send: (
message: HermesGatewayT3ToPluginMessage,
) => Effect.Effect<void, ProviderAdapterRequestError>;
readonly close: (code: number, reason: string) => Effect.Effect<void>;
}
export interface HermesGatewayConnectionRegistration {
readonly instanceId: ProviderInstanceId;
readonly generation: number;
readonly accepted: Extract<
HermesGatewayT3ToPluginMessage,
{ readonly type: "connection.accepted" }
>;
}
export interface HermesGatewayEnvelope {
readonly instanceId: ProviderInstanceId;
readonly message: Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>;
}
export interface HermesGatewayBrokerShape {
readonly createEnrollment: (
input: HermesGatewayCreateEnrollmentInput,
) => Effect.Effect<HermesGatewayEnrollmentResult, HermesGatewayManagementError>;
readonly getInstanceStatus: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesGatewayInstanceStatus, HermesGatewayManagementError>;
readonly listInstances: Effect.Effect<
ReadonlyArray<HermesGatewayInstanceStatus>,
HermesGatewayManagementError
>;
readonly renameInstance: (
input: HermesGatewayRenameInstanceInput,
) => Effect.Effect<HermesGatewayRenameInstanceResult, HermesGatewayManagementError>;
readonly revokeInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesGatewayRevokeInstanceResult, HermesGatewayManagementError>;
readonly removeInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<HermesGatewayRemoveInstanceResult, HermesGatewayManagementError>;
readonly registerConnection: (
hello: HermesGatewayConnectionHello,
transport: HermesGatewayTransport,
) => Effect.Effect<
HermesGatewayConnectionRegistration,
Extract<HermesGatewayT3ToPluginMessage, { readonly type: "connection.rejected" }>
>;
readonly receive: (
registration: HermesGatewayConnectionRegistration,
message: Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>,
) => Effect.Effect<void>;
readonly disconnect: (registration: HermesGatewayConnectionRegistration) => Effect.Effect<void>;
readonly request: (
instanceId: ProviderInstanceId,
message: HermesGatewayT3ToPluginMessage,
) => Effect.Effect<
Exclude<HermesGatewayPluginToT3Message, HermesGatewayConnectionHello>,
ProviderAdapterRequestError
>;
readonly send: (
instanceId: ProviderInstanceId,
message: HermesGatewayT3ToPluginMessage,
) => Effect.Effect<void, ProviderAdapterRequestError>;
readonly isConnected: (instanceId: ProviderInstanceId) => Effect.Effect<boolean>;
readonly stream: Stream.Stream<HermesGatewayEnvelope>;
readonly streamStatuses: Stream.Stream<HermesGatewayInstanceStatus>;
}
const unavailable = () => Effect.die(new Error("HermesGatewayBroker live layer is not installed"));
export const HermesGatewayBroker = Context.Reference<HermesGatewayBrokerShape>(
"t3/provider/Services/HermesGatewayBroker",
{
defaultValue: () => ({
createEnrollment: unavailable,
getInstanceStatus: unavailable,
listInstances: unavailable(),
renameInstance: unavailable,
revokeInstance: unavailable,
removeInstance: unavailable,
registerConnection: unavailable,
receive: unavailable,
disconnect: unavailable,
request: unavailable,
send: unavailable,
isConnected: () => Effect.succeed(false),
stream: Stream.empty,
streamStatuses: Stream.empty,
}),
},
);
@@ -1,69 +0,0 @@
/**
* RequestCorrelator — generic request/response correlation over a one-way
* message transport.
*
* Nothing in here is Hermes-specific. Any provider that speaks a protocol
* where a request carries an id and the reply echoes it can use this: register
* a pending entry, write the request, await the correlated reply, and have the
* entry torn down on success, failure, timeout, or interrupt.
*
* The correlator owns three guarantees the call sites used to hand-roll:
*
* 1. **No interrupt window.** Registration happens uninterruptibly and the
* await pipeline is wrapped in `ensuring`, so there is no point at which
* an interrupt can leave an entry in the map with nobody to clean it up.
* 2. **Age-based sweeping.** An entry whose awaiting fiber died abnormally
* is reaped by `sweep` instead of leaking for the process lifetime.
* 3. **Owner-scoped failure.** When a connection drops, every request routed
* over it fails immediately rather than waiting out its timeout.
*
* @module RequestCorrelator
*/
import type * as Duration from "effect/Duration";
import type * as Effect from "effect/Effect";
import type { ProviderAdapterRequestError } from "../Errors.ts";
export interface RequestCorrelatorSend<Owner> {
/**
* The logical route the request travels over. Used to fail an entire group
* of in-flight requests at once when that route dies (see `failOwner`).
*/
readonly owner: Owner;
/** Correlation key. Must match the id echoed on the response. */
readonly requestId: string;
/** Protocol method name, surfaced on errors for diagnostics. */
readonly method: string;
/** Writes the request. Registration is already in place when this runs. */
readonly send: Effect.Effect<void, ProviderAdapterRequestError>;
/** Overrides the correlator's default response timeout. */
readonly timeout?: Duration.Duration | undefined;
}
export interface RequestCorrelator<Owner, Response> {
/**
* Register, send, and await the correlated response. Cleans up the pending
* entry on every exit path, including interrupt.
*/
readonly request: (
input: RequestCorrelatorSend<Owner>,
) => Effect.Effect<Response, ProviderAdapterRequestError>;
/**
* Resolve a pending request. Returns `false` when no entry was waiting,
* which lets callers distinguish a correlated reply from an unsolicited one.
*/
readonly complete: (requestId: string, response: Response) => Effect.Effect<boolean>;
/** Fail every pending request registered against `owner`. */
readonly failOwner: (owner: Owner, detail: string) => Effect.Effect<void>;
/**
* Fail pending entries older than the configured max age. Safety net for
* entries whose awaiting fiber died without running its own cleanup.
*/
readonly sweep: Effect.Effect<void>;
/** Number of in-flight requests. Exposed for tests and diagnostics. */
readonly pendingCount: Effect.Effect<number>;
}
@@ -24,7 +24,6 @@ import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";
import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";
import { GrokDriver, type GrokDriverEnv } from "./Drivers/GrokDriver.ts";
import { HermesDriver, type HermesDriverEnv } from "./Drivers/HermesDriver.ts";
import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";
import type { AnyProviderDriver } from "./ProviderDriver.ts";
@@ -38,7 +37,6 @@ export type BuiltInDriversEnv =
| CodexDriverEnv
| CursorDriverEnv
| GrokDriverEnv
| HermesDriverEnv
| OpenCodeDriverEnv;
/**
@@ -52,5 +50,4 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
CursorDriver,
GrokDriver,
OpenCodeDriver,
HermesDriver,
];
@@ -1,116 +0,0 @@
import {
HermesGatewayConnectionHello,
HermesGatewayPluginToT3Message,
HermesGatewayT3ToPluginMessage,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import * as Socket from "effect/unstable/socket/Socket";
import {
HermesGatewayBroker,
type HermesGatewayConnectionRegistration,
} from "./Services/HermesGatewayBroker.ts";
import { ProviderAdapterRequestError } from "./Errors.ts";
export const HERMES_GATEWAY_WEBSOCKET_PATH = "/api/hermes-gateway/ws";
const decodePluginFrame = Schema.decodeUnknownEffect(
Schema.fromJsonString(HermesGatewayPluginToT3Message),
);
const encodeServerFrame = Schema.encodeSync(Schema.fromJsonString(HermesGatewayT3ToPluginMessage));
const isConnectionHello = Schema.is(HermesGatewayConnectionHello);
export const hermesGatewayWebSocketRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const broker = yield* HermesGatewayBroker;
return HttpRouter.add(
"GET",
HERMES_GATEWAY_WEBSOCKET_PATH,
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const socket = yield* Effect.orDie(request.upgrade);
const write = yield* socket.writer;
const registration = yield* Ref.make<Option.Option<HermesGatewayConnectionRegistration>>(
Option.none(),
);
const transport = {
send: (message: HermesGatewayT3ToPluginMessage) =>
write(encodeServerFrame(message)).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: "hermes",
method: message.type,
detail: "Failed to write a Hermes gateway WebSocket frame.",
cause,
}),
),
),
close: (code: number, reason: string) =>
write(new Socket.CloseEvent(code, reason)).pipe(Effect.ignore),
};
yield* socket
.runString((frame) =>
Effect.gen(function* () {
const message = yield* decodePluginFrame(frame);
const current = yield* Ref.get(registration);
if (Option.isNone(current)) {
if (!isConnectionHello(message)) {
yield* transport.close(4002, "First message must be connection.hello");
return;
}
const registered = yield* broker
.registerConnection(message, transport)
.pipe(
Effect.tapError((rejected) =>
transport
.send(rejected)
.pipe(Effect.andThen(transport.close(4003, rejected.message))),
),
);
yield* Ref.set(registration, Option.some(registered));
yield* transport.send(registered.accepted);
return;
}
if (isConnectionHello(message)) {
yield* transport.close(4002, "connection.hello may only be sent once");
return;
}
yield* broker.receive(current.value, message);
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("Rejected Hermes gateway WebSocket frame", { cause }).pipe(
Effect.andThen(transport.close(4002, "Invalid Hermes gateway message")),
),
),
),
)
.pipe(
Effect.catch((cause) =>
Effect.logDebug("Hermes gateway WebSocket disconnected", { cause }),
),
Effect.ensuring(
Ref.get(registration).pipe(
Effect.flatMap(
Option.match({
onNone: () => Effect.void,
onSome: broker.disconnect,
}),
),
),
),
);
return HttpServerResponse.empty();
}),
);
}),
);
+41 -1
View File
@@ -380,6 +380,7 @@ const buildAppUnderTest = (options?: {
...derivedPaths,
staticDir: undefined,
devUrl,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: defaultDesktopBootstrapToken,
@@ -563,7 +564,6 @@ const buildAppUnderTest = (options?: {
ready: Effect.void,
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
updateSettingsWith: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
streamChanges: Stream.empty,
...options?.layers?.serverSettings,
}),
@@ -1329,6 +1329,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
"bearer-access-token",
"dpop-access-token",
]);
// Desktop, so port-scoped: instances scan for a free port and share
// 127.0.0.1, and cookies are not scoped by port.
assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -3247,6 +3249,34 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("allows configured development origins through ServerConfig", () =>
Effect.gen(function* () {
const tailnetOrigin = "https://host.example.ts.net";
yield* buildAppUnderTest({
config: {
devUrl: new URL(crossOriginClientOrigin),
devAllowedOrigins: [tailnetOrigin],
},
});
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const response = yield* fetchEffect(sessionUrl, {
method: "OPTIONS",
headers: {
origin: tailnetOrigin,
"access-control-request-method": "GET",
"access-control-request-headers": "content-type",
},
});
assert.equal(response.status, 204);
assertBrowserApiCorsPreflightHeaders(response.headers, {
origin: tailnetOrigin,
credentials: true,
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
Effect.gen(function* () {
@@ -5523,11 +5553,16 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
],
};
const closedTaskTab = makeDefaultOrchestrationThreadShell({
id: ThreadId.make("thread-closed"),
tabClosedAt: now,
});
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getSnapshot: () => Effect.succeed(snapshot),
getClosedTaskTabs: () => Effect.succeed([closedTaskTab]),
},
orchestrationEngine: {
dispatch: () => Effect.succeed({ sequence: 7 }),
@@ -5594,6 +5629,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
assert.deepEqual(replayResult, []);
const closedTaskTabs = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getClosedTaskTabs]({})),
);
assert.deepEqual(closedTaskTabs, [closedTaskTab]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+1 -8
View File
@@ -21,8 +21,6 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.ts";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
import { HermesGatewayBrokerLive } from "./provider/Layers/HermesGatewayBroker.ts";
import { hermesGatewayWebSocketRouteLayer } from "./provider/hermesGatewayHttp.ts";
import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
@@ -289,10 +287,6 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
Layer.provideMerge(OrchestrationLayerLive),
);
const HermesProviderRuntimeLive = ProviderInstanceRegistryHydrationLive.pipe(
Layer.provideMerge(HermesGatewayBrokerLive),
);
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
// Core Services
Layer.provideMerge(CheckpointingLayerLive),
@@ -309,7 +303,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
// through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
// `providerInstances` hydration merges `settings.providers.<kind>`
// with explicit `providerInstances` entries on boot.
Layer.provideMerge(HermesProviderRuntimeLive),
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
// Shared native/canonical NDJSON writers used by both the per-instance
// drivers (native stream, written from inside each `<X>Adapter`) and
// `ProviderService` (canonical stream, written after event normalization).
@@ -368,7 +362,6 @@ export const makeRoutesLayer = Layer.mergeAll(
assetRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
hermesGatewayWebSocketRouteLayer,
),
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
).pipe(
@@ -81,6 +81,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () =>
Deferred.await(releaseCounts).pipe(
@@ -138,6 +139,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () =>
@@ -194,6 +196,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -244,6 +247,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
-49
View File
@@ -90,55 +90,6 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(settingsLayer));
});
it.effect("does not report post-commit materialization failure as an update failure", () => {
const platformCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFile",
pathOrDescriptor: "provider environment secret",
description: "Secret backend unavailable after settings commit.",
});
const cause = new ServerSecretStore.SecretStoreReadError({
resource: "provider environment secret",
cause: platformCause,
});
const configLayer = Layer.fresh(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-server-settings-post-commit-failure-test-",
}),
);
const settingsLayer = ServerSettingsModule.layer.pipe(
Layer.provide(makeFailingSecretStoreLayer(cause)),
Layer.provideMerge(configLayer),
);
return Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
const hermesId = ProviderInstanceId.make("hermes_remote");
yield* fileSystem.writeFileString(
serverConfig.settingsPath,
'{"providerInstances":{"hermes_remote":{"driver":"hermes","displayName":"Remote Hermes","config":{}},"codex_personal":{"driver":"codex","environment":[{"name":"OPENROUTER_API_KEY","value":"","sensitive":true,"valueRedacted":true}],"config":{}}}}',
);
const next = yield* serverSettings.updateSettingsWith((current) => {
const providerInstances = { ...current.providerInstances };
delete providerInstances[hermesId];
return { providerInstances };
});
assert.isUndefined(next.providerInstances[hermesId]);
assert.equal(
next.providerInstances[ProviderInstanceId.make("codex_personal")]?.environment?.[0]?.value,
"",
);
const persisted = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.notInclude(persisted, "hermes_remote");
assert.include(persisted, "codex_personal");
}).pipe(Effect.provide(settingsLayer));
});
it.effect("decodes nested settings patches", () =>
Effect.gen(function* () {
assert.deepEqual(
+22 -53
View File
@@ -125,15 +125,6 @@ export class ServerSettingsService extends Context.Service<
patch: ServerSettingsPatch,
) => Effect.Effect<ServerSettings, ServerSettingsError>;
/**
* Compute and persist a patch while holding the settings write lock.
* Use this for read-modify-write operations on whole-map fields such as
* `providerInstances`, so concurrent settings edits are preserved.
*/
readonly updateSettingsWith: (
update: (current: ServerSettings) => ServerSettingsPatch,
) => Effect.Effect<ServerSettings, ServerSettingsError>;
/** Stream of settings change events. */
readonly streamChanges: Stream.Stream<ServerSettings>;
}
@@ -153,24 +144,17 @@ const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
: {}),
});
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
const writeSemaphore = yield* Semaphore.make(1);
const updateSettingsWith = (update: (current: ServerSettings) => ServerSettingsPatch) =>
writeSemaphore.withPermits(1)(
Ref.get(currentSettingsRef).pipe(
Effect.map((currentSettings) =>
applyServerSettingsPatch(currentSettings, update(currentSettings)),
),
Effect.flatMap(normalizeServerSettings),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
),
);
return {
start: Effect.void,
ready: Effect.void,
getSettings: Ref.get(currentSettingsRef),
updateSettings: (patch) => updateSettingsWith(() => patch),
updateSettingsWith,
updateSettings: (patch) =>
Ref.get(currentSettingsRef).pipe(
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
Effect.flatMap(normalizeServerSettings),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
),
streamChanges: Stream.empty,
} satisfies ServerSettingsService["Service"];
});
@@ -572,35 +556,6 @@ const make = Effect.gen(function* () {
yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
});
const updateSettingsWith = (update: (current: ServerSettings) => ServerSettingsPatch) =>
writeSemaphore.withPermits(1)(
Effect.gen(function* () {
const current = yield* getSettingsFromCache;
const nextPersisted = yield* persistProviderEnvironmentSecrets(
current,
applyServerSettingsPatch(current, update(current)),
);
const next = yield* normalizeServerSettings(nextPersisted);
yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
const materialized = yield* materializeProviderEnvironmentSecrets(next).pipe(
Effect.catch((error: ServerSettingsError) =>
Effect.logWarning(
"settings update committed but provider environment secrets could not be materialized",
{
operation: error.operation,
providerInstanceId: error.providerInstanceId,
environmentVariable: error.environmentVariable,
cause: error.cause,
},
).pipe(Effect.as(next)),
),
);
return resolveTextGenerationProvider(materialized);
}),
);
return {
start,
ready: Deferred.await(startedDeferred),
@@ -608,8 +563,22 @@ const make = Effect.gen(function* () {
Effect.flatMap(materializeProviderEnvironmentSecrets),
Effect.map(resolveTextGenerationProvider),
),
updateSettings: (patch) => updateSettingsWith(() => patch),
updateSettingsWith,
updateSettings: (patch) =>
writeSemaphore.withPermits(1)(
Effect.gen(function* () {
const current = yield* getSettingsFromCache;
const nextPersisted = yield* persistProviderEnvironmentSecrets(
current,
applyServerSettingsPatch(current, patch),
);
const next = yield* normalizeServerSettings(nextPersisted);
yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
const materialized = yield* materializeProviderEnvironmentSecrets(next);
return resolveTextGenerationProvider(materialized);
}),
),
get streamChanges() {
return Stream.fromPubSub(changesPubSub).pipe(
Stream.mapEffect((settings) =>
+44 -47
View File
@@ -68,6 +68,10 @@ import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as ServerConfig from "./config.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import {
projectActivityEvent,
projectThreadDetailSnapshot,
} from "./orchestration/ActivityPayloadProjection.ts";
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -78,7 +82,6 @@ import {
} from "./observability/RpcInstrumentation.ts";
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
import { HermesGatewayBroker } from "./provider/Services/HermesGatewayBroker.ts";
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
@@ -293,6 +296,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getClosedTaskTabs, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.subscribeThread, AuthOrchestrationReadScope],
[WS_METHODS.serverProbe, AuthOrchestrationReadScope],
[WS_METHODS.serverGetConfig, AuthOrchestrationReadScope],
@@ -308,12 +312,6 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope],
[WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope],
[WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope],
[WS_METHODS.hermesGatewayCreateEnrollment, AuthOrchestrationOperateScope],
[WS_METHODS.hermesGatewayGetInstanceStatus, AuthOrchestrationReadScope],
[WS_METHODS.hermesGatewayListInstances, AuthOrchestrationReadScope],
[WS_METHODS.hermesGatewayRenameInstance, AuthOrchestrationOperateScope],
[WS_METHODS.hermesGatewayRevokeInstance, AuthOrchestrationOperateScope],
[WS_METHODS.hermesGatewayRemoveInstance, AuthOrchestrationOperateScope],
[WS_METHODS.cloudGetRelayClientStatus, AuthRelayWriteScope],
[WS_METHODS.cloudInstallRelayClient, AuthRelayWriteScope],
[WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope],
@@ -427,7 +425,6 @@ const makeWsRpcLayer = (
const portDiscovery = yield* PortScanner.PortDiscovery;
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
const hermesGatewayBroker = yield* HermesGatewayBroker;
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const config = yield* ServerConfig.ServerConfig;
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
@@ -992,6 +989,21 @@ const makeWsRpcLayer = (
commandId: yield* serverCommandId("bootstrap-thread-create"),
threadId: command.threadId,
projectId: bootstrap.createThread.projectId,
...(bootstrap.createThread.workspaceTaskId !== undefined
? { workspaceTaskId: bootstrap.createThread.workspaceTaskId }
: {}),
...(bootstrap.createThread.tabLabel !== undefined
? { tabLabel: bootstrap.createThread.tabLabel }
: {}),
...(bootstrap.createThread.tabPosition !== undefined
? { tabPosition: bootstrap.createThread.tabPosition }
: {}),
...(bootstrap.createThread.tabClosedAt !== undefined
? { tabClosedAt: bootstrap.createThread.tabClosedAt }
: {}),
...(bootstrap.createThread.forkProvenance !== undefined
? { forkProvenance: bootstrap.createThread.forkProvenance }
: {}),
title: bootstrap.createThread.title,
modelSelection: bootstrap.createThread.modelSelection,
runtimeMode: bootstrap.createThread.runtimeMode,
@@ -1221,6 +1233,7 @@ const makeWsRpcLayer = (
).pipe(
Effect.map((events) => Array.from(events)),
Effect.flatMap(enrichOrchestrationEvents),
Effect.map((events) => events.map(projectActivityEvent)),
Effect.mapError(
(cause) =>
new OrchestrationReplayEventsError({
@@ -1355,6 +1368,23 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getClosedTaskTabs]: (_input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getClosedTaskTabs,
projectionSnapshotQuery.getClosedTaskTabs().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration closed task tabs load failed", { cause }),
),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load closed task tabs",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
observeRpcStreamEffect(
ORCHESTRATION_WS_METHODS.subscribeThread,
@@ -1368,7 +1398,7 @@ const makeWsRpcLayer = (
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({
kind: "event" as const,
event,
event: projectActivityEvent(event),
})),
);
@@ -1403,7 +1433,10 @@ const makeWsRpcLayer = (
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({ kind: "event" as const, event })),
Stream.map((event) => ({
kind: "event" as const,
event: projectActivityEvent(event),
})),
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
@@ -1455,7 +1488,7 @@ const makeWsRpcLayer = (
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
snapshot: snapshot.value,
snapshot: projectThreadDetailSnapshot(snapshot.value),
}),
afterSnapshot,
);
@@ -1529,42 +1562,6 @@ const makeWsRpcLayer = (
"rpc.aggregate": "server",
},
),
[WS_METHODS.hermesGatewayCreateEnrollment]: (input) =>
observeRpcEffect(
WS_METHODS.hermesGatewayCreateEnrollment,
hermesGatewayBroker.createEnrollment(input),
{ "rpc.aggregate": "hermes-gateway" },
),
[WS_METHODS.hermesGatewayGetInstanceStatus]: ({ instanceId }) =>
observeRpcEffect(
WS_METHODS.hermesGatewayGetInstanceStatus,
hermesGatewayBroker.getInstanceStatus(instanceId),
{ "rpc.aggregate": "hermes-gateway" },
),
[WS_METHODS.hermesGatewayListInstances]: (_input) =>
observeRpcEffect(
WS_METHODS.hermesGatewayListInstances,
hermesGatewayBroker.listInstances,
{ "rpc.aggregate": "hermes-gateway" },
),
[WS_METHODS.hermesGatewayRenameInstance]: (input) =>
observeRpcEffect(
WS_METHODS.hermesGatewayRenameInstance,
hermesGatewayBroker.renameInstance(input),
{ "rpc.aggregate": "hermes-gateway" },
),
[WS_METHODS.hermesGatewayRevokeInstance]: ({ instanceId }) =>
observeRpcEffect(
WS_METHODS.hermesGatewayRevokeInstance,
hermesGatewayBroker.revokeInstance(instanceId),
{ "rpc.aggregate": "hermes-gateway" },
),
[WS_METHODS.hermesGatewayRemoveInstance]: ({ instanceId }) =>
observeRpcEffect(
WS_METHODS.hermesGatewayRemoveInstance,
hermesGatewayBroker.removeInstance(instanceId),
{ "rpc.aggregate": "hermes-gateway" },
),
[WS_METHODS.serverDiscoverSourceControl]: (_input) =>
observeRpcEffect(
WS_METHODS.serverDiscoverSourceControl,
@@ -0,0 +1,230 @@
import {
EventId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationEvent,
type OrchestrationThread,
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { buildThreadFeed } from "../../mobile/src/lib/threadActivity.ts";
import { deriveWorkLogEntries } from "../../web/src/session-logic.ts";
import {
projectActivityEvent,
projectActivityPayload,
projectThreadDetailSnapshot,
} from "../src/orchestration/ActivityPayloadProjection.ts";
function makeActivity(
id: string,
itemType: string,
data: Record<string, unknown>,
): OrchestrationThreadActivity {
return {
id: EventId.make(id),
tone: "tool",
kind: "tool.completed",
summary: `Completed ${itemType}`,
payload: {
itemType,
title: itemType,
detail: `${itemType} detail`,
status: "completed",
requestKind: "command",
data,
},
turnId: TurnId.make(`turn-${id}`),
createdAt: "2026-07-27T00:00:00.000Z",
};
}
function makeThread(activities: ReadonlyArray<OrchestrationThreadActivity>): OrchestrationThread {
return {
id: ThreadId.make("thread-projection"),
projectId: ProjectId.make("project-projection"),
title: "Activity projection",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-07-27T00:00:00.000Z",
updatedAt: "2026-07-27T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities,
checkpoints: [],
session: null,
};
}
function buildMaterializedThreadFeed(activities: ReadonlyArray<OrchestrationThreadActivity>) {
return buildThreadFeed(makeThread(activities)).map((entry) => {
if (entry.type !== "activity-group") {
return entry;
}
return {
...entry,
activities: entry.activities.map(({ getFullDetail, getCopyText, ...activity }) => ({
...activity,
fullDetail: getFullDetail(),
copyText: getCopyText(),
})),
};
});
}
const fixtures = [
makeActivity("command", "command_execution", {
item: {
command: ["bash", "-lc", "pnpm test"],
input: { command: "fallback input", ignored: "input bulk" },
result: { command: "fallback result", aggregatedOutput: "x".repeat(10_000) },
commandActions: [{ type: "unknown", output: "y".repeat(5_000) }],
},
command: "fallback data",
kind: "execute",
toolCallId: "tool-command",
rawOutput: {
content: "\n```\nfirst useful line\nsecond line",
stdout: "unused stdout",
ignored: "raw bulk",
},
ignored: "top-level bulk",
}),
makeActivity("file-change", "file_change", {
item: {
changes: [
{ oldPath: "src/old.ts", newPath: "src/new.ts", patch: "large patch".repeat(1_000) },
{ filePath: "src/second.ts" },
],
},
ignored: "top-level bulk",
}),
makeActivity("dynamic", "dynamic_tool_call", {
toolCallId: "tool-dynamic",
rawOutput: {
stdout: "dynamic summary\nlong output".repeat(1_000),
},
ignored: "top-level bulk",
}),
makeActivity("collab", "collab_agent_tool_call", {
kind: "delegate",
rawOutput: {
content: "``` \n```",
stdout: "must not be used when content is present",
},
ignored: "top-level bulk",
}),
makeActivity("mcp", "mcp_tool_call", {
item: {
server: "repository",
tool: "search",
arguments: { query: "activity projection" },
aggregatedOutput: "mcp payload remains available",
},
ignored: "MCP data is rendered verbatim",
}),
makeActivity("search", "web_search", {
rawOutput: {
totalFiles: 42,
truncated: true,
content: "ignored because totalFiles wins",
},
ignored: "top-level bulk",
}),
makeActivity("image", "image_view", {
ignored: "top-level bulk",
}),
] satisfies ReadonlyArray<OrchestrationThreadActivity>;
describe("projectActivityPayload", () => {
it("drops unread bulk while retaining command, file, tool, and summary inputs", () => {
const projected = projectActivityPayload(fixtures[0]!);
expect(projected.payload).toEqual({
itemType: "command_execution",
title: "command_execution",
detail: "command_execution detail",
status: "completed",
requestKind: "command",
data: {
item: {
command: ["bash", "-lc", "pnpm test"],
input: { command: "fallback input" },
result: { command: "fallback result" },
},
command: "fallback data",
toolCallId: "tool-command",
kind: "execute",
rawOutput: { content: "first useful line" },
},
});
expect(projectActivityPayload(fixtures[1]!).payload).toMatchObject({
data: {
files: [{ path: "src/new.ts" }, { path: "src/old.ts" }, { path: "src/second.ts" }],
},
});
});
it("passes MCP tool data through unchanged", () => {
expect(projectActivityPayload(fixtures[4]!)).toBe(fixtures[4]);
});
it("keeps current web and mobile derived output identical for every tool item type", () => {
for (const activity of fixtures) {
const projected = projectActivityPayload(activity);
expect(deriveWorkLogEntries([projected])).toEqual(deriveWorkLogEntries([activity]));
expect(buildMaterializedThreadFeed([projected])).toEqual(
buildMaterializedThreadFeed([activity]),
);
}
});
it("projects snapshot and event transports without mutating their sources", () => {
const activity = fixtures[0]!;
const thread = makeThread([activity]);
const snapshot = { snapshotSequence: 7, thread };
const projectedSnapshot = projectThreadDetailSnapshot(snapshot);
expect(projectedSnapshot.thread.activities[0]).not.toBe(activity);
expect(snapshot.thread.activities[0]).toBe(activity);
const event = {
sequence: 8,
eventId: EventId.make("event-activity"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: "2026-07-27T00:00:01.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.activity-appended",
payload: {
threadId: thread.id,
activity,
},
} satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
const projectedEvent = projectActivityEvent(event);
expect(projectedEvent).not.toBe(event);
expect(
projectedEvent.type === "thread.activity-appended"
? projectedEvent.payload.activity
: undefined,
).toEqual(projectActivityPayload(activity));
expect(event.payload.activity).toBe(activity);
});
});
+14
View File
@@ -115,6 +115,7 @@ import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { WorkspaceTaskTabs } from "./WorkspaceTaskTabs";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
import {
@@ -4725,6 +4726,18 @@ function ChatViewContent(props: ChatViewProps) {
? {
createThread: {
projectId: activeProject.id,
...(draftThread?.workspaceTaskId
? { workspaceTaskId: draftThread.workspaceTaskId }
: {}),
...(draftThread?.tabLabel !== undefined
? { tabLabel: draftThread.tabLabel }
: {}),
...(draftThread?.tabPosition !== undefined
? { tabPosition: draftThread.tabPosition }
: {}),
...(draftThread?.forkProvenance !== undefined
? { forkProvenance: draftThread.forkProvenance }
: {}),
title,
modelSelection: threadCreateModelSelection,
runtimeMode,
@@ -5655,6 +5668,7 @@ function ChatViewContent(props: ChatViewProps) {
/>
</header>
<WorkspaceTaskTabs />
<ThreadErrorBanner
error={threadError}
onDismiss={() => setThreadError(activeThread.id, null)}
+43 -1
View File
@@ -11,6 +11,8 @@ import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
ChevronsDownUpIcon,
ChevronsUpDownIcon,
Columns2Icon,
PilcrowIcon,
Rows3Icon,
@@ -32,6 +34,7 @@ import {
resolveDiffThemeName,
resolveFileDiffPath,
} from "../lib/diffRendering";
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useProject, useThread } from "../state/entities";
import { resolveThreadRouteRef } from "../threadRoutes";
@@ -39,6 +42,7 @@ import { useClientSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
import { Button } from "./ui/button";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
import { Switch } from "./ui/switch";
import {
@@ -446,6 +450,8 @@ export default function DiffPanel({
}),
[collapsedDiffFileKeys, renderableFiles],
);
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
useEffect(() => {
if (!selectedFilePath) return;
@@ -496,6 +502,18 @@ export default function DiffPanel({
[collapseScopeKey],
);
const toggleDiffFileCollapse = useCallback(() => {
setCollapsedDiffFiles((current) => {
const currentKeys =
current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
return {
scopeKey: collapseScopeKey,
fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
};
});
}, [collapseScopeKey, diffFileKeys]);
const selectTurn = (turnId: TurnId) => {
if (!routeThreadRef) return;
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
@@ -695,6 +713,30 @@ export default function DiffPanel({
)}
</div>
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
{codeViewFiles.length > 0 && (
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
onClick={toggleDiffFileCollapse}
/>
}
>
{allDiffFilesCollapsed ? (
<ChevronsUpDownIcon className="size-3" />
) : (
<ChevronsDownUpIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
</TooltipPopup>
</Tooltip>
)}
<ToggleGroup
className="shrink-0"
variant="outline"
@@ -824,7 +866,7 @@ export default function DiffPanel({
<AnnotatableCodeView
viewerRef={codeViewRef}
key={collapseScopeKey ?? reviewSectionId}
className="diff-render-surface h-full min-h-0 overflow-auto"
className="diff-render-surface h-full min-h-0 overflow-auto [&>div>div:last-child]:top-0! [&>div>div:last-child]:bottom-auto!"
files={codeViewFiles}
sectionId={reviewSectionId}
sectionTitle={reviewSectionTitle}
-18
View File
@@ -1,18 +0,0 @@
import type { Icon } from "./Icons";
/**
* Compact local mark for Hermes provider surfaces. The paired wings suggest
* Hermes' caduceus without depending on a remote image asset.
*/
export const HermesIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="none">
<path
d="M12 3v18M8.5 6.5c-2.8-2.2-5-1.1-5.5-.7.8 2.8 2.6 4.2 5.5 4.2h7c2.9 0 4.7-1.4 5.5-4.2-.5-.4-2.7-1.5-5.5.7M8 14h8M9.5 18h5"
stroke="currentColor"
strokeWidth="1.7"
strokeLinecap="round"
strokeLinejoin="round"
/>
<circle cx="12" cy="3" r="1.4" fill="currentColor" />
</svg>
);
+221 -83
View File
@@ -18,7 +18,6 @@ import {
AlarmClockOffIcon,
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
CircleAlertIcon,
CircleCheckIcon,
CircleDashedIcon,
@@ -33,6 +32,7 @@ import {
SearchIcon,
ServerIcon,
SquarePenIcon,
SquareStackIcon,
Trash2Icon,
Undo2Icon,
} from "lucide-react";
@@ -101,6 +101,11 @@ import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoute
import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat";
import type { SidebarThreadSummary } from "../types";
import { cn } from "~/lib/utils";
import {
groupThreadsByWorkspaceTask,
taskPresentationThread,
workspaceTaskKey,
} from "../lib/workspaceTasks";
import {
formatWorkingDurationLabel,
firstValidTimestampMs,
@@ -117,7 +122,11 @@ import {
sortThreadsForSidebarV2,
} from "./Sidebar.logic";
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
import {
prStatusIndicator,
resolveThreadPr,
settledPrHoverColorClass,
} from "./ThreadStatusIndicators";
import {
resolveSnoozePresets,
snoozeWakeDescription,
@@ -209,6 +218,23 @@ function WorkingDuration(props: { startedAt: string | null }) {
return <span className="tabular-nums">{formatWorkingDurationLabel(Date.now() - startedMs)}</span>;
}
/**
* A task row stands for every tab of that task, so the count is a quiet glyph
* badge rather than a bare number — the icon carries the meaning without color,
* and the row tooltip explains what the tabs do and don't share.
*/
function TaskTabCountBadge(props: { count: number }) {
return (
<span
className="inline-flex shrink-0 items-center gap-0.5 rounded bg-sidebar-accent px-1 font-mono text-[10px] text-sidebar-muted-foreground"
aria-label={`${props.count} task tabs`}
>
<SquareStackIcon aria-hidden className="size-2.5" />
{props.count}
</span>
);
}
function SidebarV2ThreadTooltip({
thread,
projectTitle,
@@ -218,11 +244,13 @@ function SidebarV2ThreadTooltip({
modelInstanceId,
modelLabel,
branchMismatch,
tabCount,
}: {
thread: SidebarThreadSummary;
projectTitle: string | null;
projectCwd: string | null;
environmentLabel: string | null;
tabCount: number;
driverKind: ProviderInstanceEntry["driverKind"] | null;
modelInstanceId: string;
modelLabel: string;
@@ -236,7 +264,11 @@ function SidebarV2ThreadTooltip({
side="right"
align="start"
sideOffset={8}
className="dropdown-glass max-w-80 border-0! bg-[color-mix(in_srgb,var(--background)_var(--glass-opacity),transparent)] text-left whitespace-normal shadow-lg/10 before:hidden dark:shadow-none"
className="dropdown-glass max-w-80 border-0! text-left whitespace-normal shadow-lg/10 before:hidden dark:shadow-none"
style={{
background:
"color-mix(in srgb, var(--popover) 18%, color-mix(in srgb, var(--popover) var(--glass-opacity), transparent))",
}}
>
<div className="flex max-w-80 flex-col gap-2 p-2">
<div className="whitespace-nowrap text-sm font-medium text-foreground">{thread.title}</div>
@@ -281,6 +313,14 @@ function SidebarV2ThreadTooltip({
<div className="min-w-0 wrap-break-word text-foreground/90">{modelLabel}</div>
</div>
) : null}
{tabCount > 1 ? (
<div className="flex min-w-0 items-start gap-2">
<SquareStackIcon aria-hidden className="mt-0.5 size-4 shrink-0 stroke-current" />
<div className="min-w-0 flex-1 wrap-break-word leading-5">
{tabCount} tabs · Shared files, separate chats.
</div>
</div>
) : null}
{thread.session?.lastError ? (
<div className="flex min-w-0 items-center gap-2 text-red-600 dark:text-red-400">
<CircleAlertIcon className="size-4 shrink-0 stroke-current" />
@@ -361,6 +401,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
// When a snooze ended (timer or early wake); drives the Woke pill until
// the user visits the thread.
wokeAt: string | null;
tabCount: number;
isActive: boolean;
jumpLabel: string | null;
currentEnvironmentId: string | null;
@@ -498,6 +539,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
hasDedicatedWorktree: thread.worktreePath !== null,
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined;
// Report the PR state up: the parent partitions rows with effectiveSettled,
// and a merged/closed PR auto-settles a thread — data only rows have.
const prState = pr?.state ?? null;
@@ -528,6 +570,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
modelInstanceId={modelInstanceId}
modelLabel={modelLabel}
branchMismatch={branchMismatch}
tabCount={props.tabCount}
/>
);
@@ -647,7 +690,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
// content; surface is reserved for interaction (hover, multi-select, route).
const rowSurfaceClassName = cn(
"group/v2-row relative w-full cursor-pointer overflow-hidden rounded-md text-left outline-none select-none",
variant === "card" && "backdrop-blur-[16px]",
props.isActive
? "bg-sidebar-row-active text-sidebar-foreground"
: isSelected
@@ -714,7 +756,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
variant === "slim" && variantAction === "unsettle"
? props.isActive
? "text-muted-foreground/70"
: "text-muted-foreground/35 transition-colors group-hover/v2-row:text-muted-foreground/65"
: cn("text-muted-foreground/35 transition-colors", settledPrHoverClass)
: prStatus.colorClass,
)}
aria-label={prStatus.tooltip}
@@ -761,6 +803,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
/>
</span>
{title}
{props.tabCount > 1 ? <TaskTabCountBadge count={props.tabCount} /> : null}
{/* The PR badge stays outside the hover-fading slot: it must
remain visible AND clickable while the row is hovered. Only
the time/jump label yields to the settle affordance. */}
@@ -936,7 +979,10 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
) : null}
</span>
</div>
<div className="mt-1 flex min-w-0">{title}</div>
<div className="mt-1 flex min-w-0 items-center gap-1.5">
{title}
{props.tabCount > 1 ? <TaskTabCountBadge count={props.tabCount} /> : null}
</div>
<div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground/75">
{thread.branch ? (
<span className="min-w-0 flex-1 truncate whitespace-nowrap">{thread.branch}</span>
@@ -1051,6 +1097,34 @@ export default function SidebarV2() {
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
const routeTaskKey = useMemo(() => {
if (routeThreadKey === null) return null;
const routeThread = threads.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
);
return routeThread ? workspaceTaskKey(routeThread) : null;
}, [routeThreadKey, threads]);
const taskTabCountByKey = useMemo(
() =>
new Map(
groupThreadsByWorkspaceTask(threads.filter((thread) => thread.tabClosedAt == null)).map(
(task) => [task.key, task.tabs.length] as const,
),
),
[threads],
);
const taskTabsByThreadKey = useMemo(() => {
const mapping = new Map<string, ReadonlyArray<EnvironmentThreadShell>>();
for (const task of groupThreadsByWorkspaceTask(
threads.filter((thread) => thread.tabClosedAt == null),
)) {
for (const tab of task.tabs) {
mapping.set(scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id)), task.tabs);
}
}
return mapping;
}, [threads]);
const routeTargetRef = useRef(routeTarget);
routeTargetRef.current = routeTarget;
// Post-settle navigation validates against the CURRENT route, not the one
@@ -1363,13 +1437,15 @@ export default function SidebarV2() {
const visible = threads.filter(
(thread) =>
thread.archivedAt === null &&
thread.tabClosedAt == null &&
(scopedProjectKeys === null ||
scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
);
const active: EnvironmentThreadShell[] = [];
const snoozed: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
for (const thread of visible) {
for (const task of groupThreadsByWorkspaceTask(visible)) {
const thread = taskPresentationThread(task, routeThreadKey);
// Threads on servers without the settlement capability (old server,
// or descriptor not loaded yet) never classify as settled: the user
// could neither un-settle nor pin them, so auto-settling them would
@@ -1378,17 +1454,22 @@ export default function SidebarV2() {
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true;
const supportsSnooze =
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
const tabStates = task.tabs.map((tab) => {
const threadKey = scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id));
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
return {
snoozed: supportsSnooze && effectiveSnoozed(tab, { now: preciseNow }),
settled:
supportsSettlement &&
effectiveSettled(tab, { now, autoSettleAfterDays, changeRequestState }),
};
});
// Snooze outranks settled classification: an explicitly snoozed thread
// belongs to the shelf even if it would also auto-settle (the shelf's
// wake time is a stronger statement about when it matters again).
if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) {
if (tabStates.every((state) => state.snoozed)) {
snoozed.push(thread);
} else if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
) {
} else if (tabStates.every((state) => state.settled)) {
settled.push(thread);
} else {
active.push(thread);
@@ -1413,6 +1494,7 @@ export default function SidebarV2() {
serverConfigs,
snoozeWakeTick,
threads,
routeThreadKey,
]);
// Arm a timeout for the earliest upcoming wake so the shelf empties the
@@ -1450,17 +1532,14 @@ export default function SidebarV2() {
// The open thread must never hide under "Show more": navigating into a
// deep settled thread (search, deep link) pulls its row into the visible
// tail so the highlight and the un-settle affordance stay reachable.
if (routeThreadKey !== null) {
if (routeTaskKey !== null) {
const routeThread = settledThreads
.slice(settledVisibleCount)
.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
);
.find((thread) => workspaceTaskKey(thread) === routeTaskKey);
if (routeThread !== undefined) visible.push(routeThread);
}
return visible;
}, [routeThreadKey, settledThreads, settledVisibleCount]);
}, [routeTaskKey, settledThreads, settledVisibleCount]);
const hiddenSettledCount = settledThreads.length - visibleSettledThreads.length;
const showMoreSettled = useCallback(
() => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT),
@@ -1470,13 +1549,12 @@ export default function SidebarV2() {
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
const renderedSettledThreads = useMemo(() => {
if (settledShelfExpanded) return visibleSettledThreads;
if (routeThreadKey === null) return [];
if (routeTaskKey === null) return [];
const routeThread = visibleSettledThreads.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
(thread) => workspaceTaskKey(thread) === routeTaskKey,
);
return routeThread === undefined ? [] : [routeThread];
}, [routeThreadKey, settledShelfExpanded, visibleSettledThreads]);
}, [routeTaskKey, settledShelfExpanded, visibleSettledThreads]);
// The snoozed shelf is collapsed by default: out of the way, never gone.
// Collapsed threads don't render (and so don't participate in jump
@@ -1489,13 +1567,10 @@ export default function SidebarV2() {
// snoozed thread reached by route (deep link, open before snoozing
// elsewhere) keeps its row — with highlight and wake affordance — same
// exception the settled tail's "Show more" makes.
if (routeThreadKey === null) return [];
const routeThread = snoozedThreads.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
);
if (routeTaskKey === null) return [];
const routeThread = snoozedThreads.find((thread) => workspaceTaskKey(thread) === routeTaskKey);
return routeThread === undefined ? [] : [routeThread];
}, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]);
}, [routeTaskKey, snoozedShelfExpanded, snoozedThreads]);
const orderedThreads = useMemo(
() => [...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads],
@@ -1807,6 +1882,52 @@ export default function SidebarV2() {
},
[attemptUnsnooze, planForwardNavigation, snoozeThread],
);
const taskTabsForRef = useCallback(
(threadRef: ScopedThreadRef) => taskTabsByThreadKey.get(scopedThreadKey(threadRef)) ?? [],
[taskTabsByThreadKey],
);
const attemptSettleTask = useCallback(
(threadRef: ScopedThreadRef) => {
const tabs = taskTabsForRef(threadRef);
const coSettlingKeys = new Set(
tabs.map((tab) => scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id))),
);
for (const tab of tabs) {
attemptSettle(scopeThreadRef(tab.environmentId, tab.id), { coSettlingKeys });
}
},
[attemptSettle, taskTabsForRef],
);
const attemptUnsettleTask = useCallback(
(threadRef: ScopedThreadRef) => {
for (const tab of taskTabsForRef(threadRef)) {
attemptUnsettle(scopeThreadRef(tab.environmentId, tab.id));
}
},
[attemptUnsettle, taskTabsForRef],
);
const attemptSnoozeTask = useCallback(
(threadRef: ScopedThreadRef, preset: SnoozePreset) => {
const tabs = taskTabsForRef(threadRef);
const coSnoozingKeys = new Set(
tabs.map((tab) => scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id))),
);
for (const tab of tabs) {
attemptSnooze(scopeThreadRef(tab.environmentId, tab.id), preset, {
coSnoozingKeys,
});
}
},
[attemptSnooze, taskTabsForRef],
);
const attemptUnsnoozeTask = useCallback(
(threadRef: ScopedThreadRef) => {
for (const tab of taskTabsForRef(threadRef)) {
attemptUnsnooze(scopeThreadRef(tab.environmentId, tab.id));
}
},
[attemptUnsnooze, taskTabsForRef],
);
const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
const handleMultiSelectContextMenu = useCallback(
@@ -1822,13 +1943,20 @@ export default function SidebarV2() {
);
if (threadKeys.length === 0) return;
const count = threadKeys.length;
const selectedTabsByKey = new Map<string, EnvironmentThreadShell>();
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
if (!thread) continue;
const tabs = taskTabsByThreadKey.get(threadKey) ?? [thread];
for (const tab of tabs) {
selectedTabsByKey.set(scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id)), tab);
}
}
const selectedTabEntries = [...selectedTabsByKey.entries()];
// Snooze (N) is offered when every selected thread can actually take
// it — a mixed selection with blocked-on-you work would half-apply.
const selectionNow = new Date().toISOString();
const snoozableThreads = threadKeys.flatMap((threadKey) => {
const thread = threadByKeyRef.current.get(threadKey);
return thread ? [thread] : [];
});
const snoozableThreads = selectedTabEntries.map(([, thread]) => thread);
const canSnoozeSelection = snoozableThreads.every(
(thread) =>
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true &&
@@ -1865,7 +1993,7 @@ export default function SidebarV2() {
if (preset) {
// Post-snooze navigation must skip threads snoozing in this same
// batch — they are all leaving the card block together.
const coSnoozingKeys = new Set(threadKeys);
const coSnoozingKeys = new Set(selectedTabsByKey.keys());
for (const thread of snoozableThreads) {
attemptSnooze(scopeThreadRef(thread.environmentId, thread.id), preset, {
coSnoozingKeys,
@@ -1880,18 +2008,16 @@ export default function SidebarV2() {
// batch — they are all leaving the card block together. Rows that
// are already explicitly settled are skipped: nothing to do on a
// valid mixed selection.
const coSettlingKeys = new Set(threadKeys);
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
if (!thread || thread.settledOverride === "settled") continue;
const coSettlingKeys = new Set(selectedTabsByKey.keys());
for (const [, thread] of selectedTabEntries) {
if (thread.settledOverride === "settled") continue;
attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys });
}
clearSelection();
return;
}
if (clicked.value === "mark-unread") {
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
for (const [threadKey, thread] of selectedTabEntries) {
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
}
clearSelection();
@@ -1902,8 +2028,8 @@ export default function SidebarV2() {
const confirmed = await settlePromise(() =>
api.dialogs.confirm(
[
`Delete ${count} thread${count === 1 ? "" : "s"}?`,
"This permanently clears conversation history for these threads.",
`Delete ${count} task${count === 1 ? "" : "s"}?`,
"This permanently clears conversation history for every tab in these tasks.",
].join("\n"),
),
);
@@ -1914,9 +2040,7 @@ export default function SidebarV2() {
// really gone, or the first delete would treat still-alive batch mates
// as deleted and remove a worktree they still point at.
const deletedThreadKeys = new Set<string>();
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
if (!thread) continue;
for (const [threadKey, thread] of selectedTabEntries) {
const result = await deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
deletedThreadKeys,
});
@@ -1946,6 +2070,7 @@ export default function SidebarV2() {
markThreadUnread,
removeFromSelection,
serverConfigs,
taskTabsByThreadKey,
],
);
@@ -1962,6 +2087,7 @@ export default function SidebarV2() {
}
const thread = threadByKeyRef.current.get(threadKey);
if (!thread) return;
const taskTabs = taskTabsForRef(threadRef);
// Un-settle works on every settled row: for explicit settles it
// clears the override, for auto-settled rows it pins the thread
// active until real activity clears the pin. Environments without
@@ -1989,8 +2115,8 @@ export default function SidebarV2() {
...(supportsSettlement
? [
isSettled
? { id: "unsettle", label: "Un-settle thread" }
: { id: "settle", label: "Settle thread" },
? { id: "unsettle", label: "Un-settle task" }
: { id: "settle", label: "Settle task" },
]
: []),
...(supportsSnooze
@@ -2008,9 +2134,9 @@ export default function SidebarV2() {
},
]
: []),
{ id: "rename", label: "Rename thread" },
{ id: "rename", label: "Rename task" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
{ id: "delete", label: "Delete task", destructive: true, icon: "trash" },
],
position,
),
@@ -2020,7 +2146,7 @@ export default function SidebarV2() {
const preset = snoozePresets.find(
(candidate) => `snooze:${candidate.id}` === clicked.value,
);
if (preset) attemptSnooze(threadRef, preset);
if (preset) attemptSnoozeTask(threadRef, preset);
return;
}
switch (clicked.value) {
@@ -2048,43 +2174,53 @@ export default function SidebarV2() {
return;
}
case "settle":
attemptSettle(threadRef);
attemptSettleTask(threadRef);
return;
case "unsettle":
attemptUnsettle(threadRef);
attemptUnsettleTask(threadRef);
return;
case "unsnooze":
attemptUnsnooze(threadRef);
attemptUnsnoozeTask(threadRef);
return;
case "rename":
startThreadRename(threadRef, thread.title);
return;
case "mark-unread":
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
for (const tab of taskTabs) {
markThreadUnread(
scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id)),
tab.latestTurn?.completedAt,
);
}
return;
case "delete": {
if (confirmThreadDelete) {
const confirmed = await settlePromise(() =>
api.dialogs.confirm(
[
`Delete thread "${thread.title}"?`,
"This permanently clears conversation history for this thread.",
`Delete task "${thread.title}" and its ${taskTabs.length} tab${taskTabs.length === 1 ? "" : "s"}?`,
"This permanently clears conversation history for every tab in the task.",
].join("\n"),
),
);
if (confirmed._tag === "Failure" || !confirmed.value) return;
}
const result = await deleteThread(threadRef);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
return;
const deletedThreadKeys = new Set<string>();
for (const tab of taskTabs) {
const tabRef = scopeThreadRef(tab.environmentId, tab.id);
const result = await deleteThread(tabRef, { deletedThreadKeys });
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete task",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
return;
}
deletedThreadKeys.add(scopedThreadKey(tabRef));
}
return;
}
@@ -2094,16 +2230,17 @@ export default function SidebarV2() {
})();
},
[
attemptSettle,
attemptSnooze,
attemptUnsettle,
attemptUnsnooze,
attemptSettleTask,
attemptSnoozeTask,
attemptUnsettleTask,
attemptUnsnoozeTask,
confirmThreadDelete,
deleteThread,
handleMultiSelectContextMenu,
markThreadUnread,
serverConfigs,
startThreadRename,
taskTabsForRef,
],
);
@@ -2216,7 +2353,7 @@ export default function SidebarV2() {
<SidebarMenuButton
size="sm"
type="button"
aria-label="Search threads and commands"
aria-label="Search tasks and commands"
className="h-8 gap-2 rounded-md border-0 bg-transparent px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
data-testid="command-palette-trigger"
/>
@@ -2241,7 +2378,7 @@ export default function SidebarV2() {
className="relative size-8 justify-center rounded-md border-0 bg-transparent p-0 text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
onClick={handleNewThreadClick}
disabled={projects.length === 0}
aria-label="New thread"
aria-label="New task"
/>
}
>
@@ -2252,7 +2389,7 @@ export default function SidebarV2() {
/>
</TooltipTrigger>
<TooltipPopup side="right">
{newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"}
{newThreadShortcutLabel ? `New task (${newThreadShortcutLabel})` : "New task"}
</TooltipPopup>
</Tooltip>
</div>
@@ -2263,7 +2400,7 @@ export default function SidebarV2() {
<div className="flex items-center gap-1">
<Menu open={projectScopeMenuOpen} onOpenChange={setProjectScopeMenuOpen}>
<MenuTrigger
aria-label="Filter threads by project"
aria-label="Filter tasks by project"
className="flex h-8 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md px-2 text-left text-sm font-medium text-sidebar-muted-foreground outline-none hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
>
{scopedProjectGroup ? (
@@ -2412,7 +2549,8 @@ export default function SidebarV2() {
// the wake signal must survive the trip. Still-snoozed
// rows resolve to null on their own.
wokeAt={threadWokeAt(thread, { now: snoozeNow })}
isActive={routeThreadKey === threadKey}
tabCount={taskTabCountByKey.get(workspaceTaskKey(thread)) ?? 1}
isActive={routeTaskKey === workspaceTaskKey(thread)}
jumpLabel={showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null}
currentEnvironmentId={primaryEnvironmentId}
environmentLabel={environmentLabelById.get(thread.environmentId) ?? null}
@@ -2434,10 +2572,10 @@ export default function SidebarV2() {
isRenaming={renamingThreadKey === threadKey}
renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""}
onContextMenu={handleThreadContextMenu}
onSettle={attemptSettle}
onUnsettle={attemptUnsettle}
onSnooze={attemptSnooze}
onUnsnooze={attemptUnsnooze}
onSettle={attemptSettleTask}
onUnsettle={attemptUnsettleTask}
onSnooze={attemptSnoozeTask}
onUnsnooze={attemptUnsnoozeTask}
onChangeRequestState={handleChangeRequestState}
/>
);
@@ -2539,9 +2677,9 @@ export default function SidebarV2() {
</button>
</>
) : scopedProjectGroup ? (
`No threads in ${scopedProjectGroup.displayName} yet`
`No tasks in ${scopedProjectGroup.displayName} yet`
) : (
"No threads yet"
"No tasks yet"
)}
</div>
) : null}
@@ -1,7 +1,11 @@
import type { VcsStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
import {
prStatusIndicator,
resolveThreadPr,
settledPrHoverColorClass,
} from "./ThreadStatusIndicators";
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
return {
@@ -70,4 +74,23 @@ describe("prStatusIndicator", () => {
tooltipTitle: "PR branch",
});
});
it("uses red for closed pull requests", () => {
const closedPr = status().pr;
if (!closedPr) throw new Error("Expected pull request fixture");
expect(prStatusIndicator({ ...closedPr, state: "closed" }, undefined)?.colorClass).toContain(
"text-red-600",
);
});
});
describe("settledPrHoverColorClass", () => {
it.each([
["open", "text-emerald-600"],
["merged", "text-violet-600"],
["closed", "text-red-600"],
] as const)("restores the %s pull request color on row hover", (state, colorClass) => {
expect(settledPrHoverColorClass(state)).toContain(`group-hover/v2-row:${colorClass}`);
});
});
@@ -35,6 +35,17 @@ export interface TerminalStatusIndicator {
export type ThreadPr = VcsStatusResult["pr"];
export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {
switch (state) {
case "open":
return "group-hover/v2-row:text-emerald-600 dark:group-hover/v2-row:text-emerald-300/90";
case "merged":
return "group-hover/v2-row:text-violet-600 dark:group-hover/v2-row:text-violet-300/90";
case "closed":
return "group-hover/v2-row:text-red-600 dark:group-hover/v2-row:text-red-300/90";
}
}
export function prStatusIndicator(
pr: ThreadPr,
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
@@ -65,7 +76,7 @@ export function prStatusIndicator(
if (pr.state === "closed") {
return {
label: `${presentation.shortName} closed`,
colorClass: "text-zinc-500 dark:text-zinc-400/80",
colorClass: "text-red-600 dark:text-red-300/90",
tooltip,
tooltipLead,
tooltipTitle: pr.title,
@@ -0,0 +1,289 @@
import {
CircleDashedIcon,
CopyPlusIcon,
HistoryIcon,
PlusIcon,
RotateCcwIcon,
XIcon,
} from "lucide-react";
import { useMemo, useState } from "react";
import { shortcutLabelForCommand } from "../keybindings";
import { useClientSettings } from "../hooks/useSettings";
import {
type ClosedWorkspaceTaskTab,
type WorkspaceTaskTab,
useWorkspaceTaskTabs,
} from "../hooks/useWorkspaceTaskTabs";
import {
describeTaskTabContexts,
type TaskTabContextDescriptor,
type TaskTabContextSource,
} from "../lib/taskTabContext";
import { cn } from "../lib/utils";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
type AnyWorkspaceTaskTab = WorkspaceTaskTab | ClosedWorkspaceTaskTab;
function tabContextSource(tab: AnyWorkspaceTaskTab): TaskTabContextSource {
return {
kind: tab.kind,
threadId: String(tab.kind === "server" ? tab.threadRef.threadId : tab.threadId),
title: tab.title,
position: tab.position,
forkProvenance: tab.forkProvenance
? {
mode: tab.forkProvenance.mode,
sourceThreadId:
tab.forkProvenance.sourceThreadId === null
? null
: String(tab.forkProvenance.sourceThreadId),
}
: null,
};
}
/**
* State is carried by shape and text as well as hue: blocked tabs get a filled
* ring plus "Waiting on you", working tabs get a dashed spinner glyph.
*/
function TabStateGlyph(props: { tab: WorkspaceTaskTab }) {
const { tab } = props;
if (tab.blocked) {
return (
<span
role="img"
aria-label="Waiting on you"
className="inline-flex size-3.5 shrink-0 items-center justify-center rounded-full border-[1.5px] border-amber-500 text-amber-600 dark:text-amber-400"
>
<span aria-hidden className="size-1.5 rounded-full bg-current" />
</span>
);
}
if (tab.working) {
return (
<CircleDashedIcon
role="img"
aria-label="Working"
className="size-3.5 shrink-0 animate-status-pulse text-sky-600 motion-reduce:animate-none dark:text-sky-400"
/>
);
}
return null;
}
function ContextSummary(props: {
context: TaskTabContextDescriptor;
active: boolean;
className?: string;
}) {
return (
<span
aria-hidden
className={cn(
"hidden shrink-0 truncate text-[10px] font-normal whitespace-nowrap md:inline",
props.active ? "text-muted-foreground/80" : "text-muted-foreground/55",
props.className,
)}
>
· {props.context.label}
</span>
);
}
export function WorkspaceTaskTabs() {
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
const {
tabs,
closedTabs,
keybindings,
hasTask,
canForkContext,
createTab,
closeTab,
reopenTab,
navigateToTab,
} = useWorkspaceTaskTabs();
const [creatingMode, setCreatingMode] = useState<"fresh" | "portable" | null>(null);
const [reopeningKey, setReopeningKey] = useState<string | null>(null);
const contextByTabKey = useMemo(() => {
const allTabs = [...tabs, ...closedTabs];
const contexts = describeTaskTabContexts(allTabs.map(tabContextSource));
return new Map(allTabs.map((tab, index) => [tab.key, contexts[index]!]));
}, [closedTabs, tabs]);
if (!sidebarV2Enabled || !hasTask) return null;
const newTabShortcut = shortcutLabelForCommand(keybindings, "chat.newTab");
const reopenShortcut = shortcutLabelForCommand(keybindings, "chat.reopenClosedTab");
const create = (mode: "fresh" | "portable") => {
if (creatingMode !== null) return;
setCreatingMode(mode);
void createTab(mode).finally(() => setCreatingMode(null));
};
const reopen = (tab: ClosedWorkspaceTaskTab) => {
if (reopeningKey !== null) return;
setReopeningKey(tab.key);
void reopenTab(tab).finally(() => setReopeningKey(null));
};
return (
<TooltipProvider delay={250} closeDelay={0}>
<nav
aria-label="Task tabs"
data-testid="workspace-task-tabs"
className="flex h-9 shrink-0 items-center gap-2 border-b border-border/60 bg-background px-3 sm:px-5"
>
<div className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto rounded-md bg-muted/40 p-0.5 [scrollbar-width:none]">
{tabs.map((tab) => {
const context = contextByTabKey.get(tab.key);
return (
<div
key={tab.key}
className={cn(
"group/task-tab relative flex h-7 max-w-64 min-w-0 shrink-0 items-center rounded-[5px] pr-1 pl-2 text-xs transition-colors",
tab.active
? "bg-background text-foreground shadow-xs ring-1 ring-border/70"
: "text-muted-foreground hover:bg-background/60 hover:text-foreground",
)}
>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-1.5 text-left outline-none"
onClick={() => void navigateToTab(tab)}
aria-current={tab.active ? "page" : undefined}
/>
}
>
<TabStateGlyph tab={tab} />
<span className="truncate font-medium">
{context?.title ?? tab.title}
{context ? <span className="sr-only"> — {context.label}</span> : null}
</span>
{context ? <ContextSummary context={context} active={tab.active} /> : null}
</TooltipTrigger>
<TooltipPopup side="bottom" className="max-w-56">
<span className="block text-left">
<span className="font-medium text-foreground">
{context?.label ?? "Independent"}
</span>
{context ? (
<span className="ml-1.5 text-muted-foreground">{context.detail}</span>
) : null}
</span>
</TooltipPopup>
</Tooltip>
{tabs.length > 1 ? (
<button
type="button"
aria-label={`Close ${context?.title ?? tab.title}`}
disabled={tab.working || tab.blocked}
onClick={(event) => {
event.stopPropagation();
void closeTab(tab);
}}
className="ml-1 inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground/50 opacity-0 transition-opacity hover:bg-muted hover:text-foreground focus-visible:opacity-100 disabled:cursor-not-allowed disabled:opacity-20 group-hover/task-tab:opacity-100"
>
<XIcon className="size-3" />
</button>
) : null}
</div>
);
})}
</div>
<div className="flex shrink-0 items-center gap-0.5">
{closedTabs.length > 0 ? (
<Menu>
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger
render={
<button
type="button"
aria-label="Closed tabs"
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
/>
}
/>
}
>
<HistoryIcon className="size-3.5" />
</TooltipTrigger>
<TooltipPopup side="bottom">
Closed tabs{reopenShortcut ? ` (${reopenShortcut})` : ""}
</TooltipPopup>
</Tooltip>
<MenuPopup align="end" className="min-w-52 max-w-72">
{closedTabs.map((tab, index) => {
const context = contextByTabKey.get(tab.key);
return (
<MenuItem
key={tab.key}
disabled={reopeningKey !== null}
onClick={() => reopen(tab)}
>
<RotateCcwIcon />
<span className="min-w-0 flex-1 truncate">{context?.title ?? tab.title}</span>
{context ? (
<span className="max-w-28 truncate text-xs text-muted-foreground">
{context.label}
</span>
) : null}
{index === 0 && reopenShortcut ? (
<MenuShortcut>{reopenShortcut}</MenuShortcut>
) : null}
</MenuItem>
);
})}
</MenuPopup>
</Menu>
) : null}
<Menu>
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger
render={
<button
type="button"
aria-label="New tab"
disabled={creatingMode !== null}
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50"
/>
}
/>
}
>
<PlusIcon className="size-4" />
</TooltipTrigger>
<TooltipPopup side="bottom">
New tab{newTabShortcut ? ` (${newTabShortcut})` : ""}
</TooltipPopup>
</Tooltip>
<MenuPopup align="end" className="min-w-48">
<MenuItem disabled={creatingMode !== null} onClick={() => create("fresh")}>
<PlusIcon />
Empty
{newTabShortcut ? <MenuShortcut>{newTabShortcut}</MenuShortcut> : null}
</MenuItem>
<MenuItem
disabled={!canForkContext || creatingMode !== null}
onClick={() => create("portable")}
>
<CopyPlusIcon />
Copy current context
</MenuItem>
</MenuPopup>
</Menu>
</div>
</nav>
</TooltipProvider>
);
}
+72 -99
View File
@@ -75,10 +75,7 @@ import { ProviderModelPicker } from "./ProviderModelPicker";
import { type ComposerCommandItem, ComposerCommandMenu } from "./ComposerCommandMenu";
import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
import {
ComposerPrimaryActions,
shouldUseCollapsedHermesRunningActions,
} from "./ComposerPrimaryActions";
import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
@@ -174,10 +171,9 @@ import { getProviderDisplayName, getProviderInteractionModeToggle } from "../../
import {
applyProviderInstanceSettings,
deriveProviderInstanceEntries,
getProviderInstanceComposerUnavailableMessage,
isProviderInstanceComposerAvailable,
resolveComposerProviderInstanceId,
NO_PROVIDER_MODEL_SELECTION,
resolveProviderDriverKindForInstanceSelection,
resolveSelectableProviderInstanceEntry,
sortProviderInstanceEntries,
type ProviderInstanceEntry,
} from "../../providerInstances";
@@ -416,7 +412,6 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
isComplete: boolean;
} | null;
isRunning: boolean;
allowSendWhileRunning: boolean;
showPlanFollowUpPrompt: boolean;
promptHasText: boolean;
isSendBusy: boolean;
@@ -443,7 +438,6 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
compact={props.compact}
pendingAction={props.pendingAction}
isRunning={props.isRunning}
allowSendWhileRunning={props.allowSendWhileRunning}
showPlanFollowUpPrompt={props.showPlanFollowUpPrompt}
promptHasText={props.promptHasText}
isSendBusy={props.isSendBusy}
@@ -782,28 +776,52 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// Resolve which configured instance the composer is currently targeting.
// Priority:
// 1. A started Hermes thread's persisted instance binding. Hermes
// sessions cannot be reassigned, including when that instance is
// currently missing or disabled.
// 2. The composer draft's `activeProvider` — the user's unsaved pick
// 1. The composer draft's `activeProvider` — the user's unsaved pick
// from the model picker (must win, otherwise the UI appears to
// ignore picker selections).
// 3. Thread's persisted instance id (server-side saved selection).
// 4. Project default's instance id.
// 5. First enabled entry matching the current driver kind.
// 6. First enabled entry overall / default instance for the kind.
// 2. Thread's persisted instance id (server-side saved selection).
// 3. Project default's instance id.
// 4. First enabled entry matching the current driver kind.
// 5. First enabled entry overall / default instance for the kind.
//
const selectedInstanceId = useMemo<ProviderInstanceId>(() => {
return resolveComposerProviderInstanceId({
entries: providerInstanceEntries,
draftInstanceId: composerDraft.activeProvider ?? null,
threadInstanceId: activeThread?.session?.providerInstanceId,
threadModelInstanceId: activeThreadModelSelection?.instanceId,
projectInstanceId: activeProjectDefaultModelSelection?.instanceId,
requestedDriverKind,
lockedProvider,
lockedContinuationGroupKey,
});
const candidates: Array<string | null | undefined> = [
composerDraft.activeProvider,
activeThread?.session?.providerInstanceId,
activeThreadModelSelection?.instanceId,
activeProjectDefaultModelSelection?.instanceId,
];
for (const candidate of candidates) {
if (!candidate) continue;
const match = providerInstanceEntries.find(
(entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable,
);
if (match) {
// When locked to a specific driver kind, ignore persisted instance
// ids from a different kind or continuation group.
if (lockedProvider && match.driverKind !== lockedProvider) continue;
if (
lockedContinuationGroupKey &&
match.continuationGroupKey !== lockedContinuationGroupKey
) {
continue;
}
return match.instanceId;
}
}
const compatibleEntries = providerInstanceEntries.filter(
(entry) =>
(!lockedProvider || entry.driverKind === lockedProvider) &&
(!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey),
);
const requestedDriverEntries = compatibleEntries.filter(
(entry) => entry.driverKind === requestedDriverKind,
);
return (
resolveSelectableProviderInstanceEntry(requestedDriverEntries, undefined)?.instanceId ??
resolveSelectableProviderInstanceEntry(compatibleEntries, undefined)?.instanceId ??
NO_PROVIDER_MODEL_SELECTION.instanceId
);
}, [
activeProjectDefaultModelSelection?.instanceId,
activeThread?.session?.providerInstanceId,
@@ -822,28 +840,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
() => providerInstanceEntries.find((entry) => entry.instanceId === selectedInstanceId),
[providerInstanceEntries, selectedInstanceId],
);
const noProviderAvailable =
selectedProviderEntry === undefined ||
!isProviderInstanceComposerAvailable(selectedProviderEntry);
const missingBoundHermesInstanceId =
selectedProviderEntry === undefined && lockedProvider === "hermes"
? (activeThread?.session?.providerInstanceId ?? activeThreadModelSelection?.instanceId)
: undefined;
const providerUnavailableMessage = getProviderInstanceComposerUnavailableMessage(
selectedProviderEntry,
missingBoundHermesInstanceId
? {
driverKind: ProviderDriverKind.make("hermes"),
instanceId: missingBoundHermesInstanceId,
}
: undefined,
);
const noProviderAvailable = selectedProviderEntry === undefined;
// The driver kind follows the instance that will actually run the turn,
// which can differ from the persisted selection when that selection is
// disabled.
const selectedProvider: ProviderDriverKind =
selectedProviderEntry?.driverKind ?? requestedDriverKind;
const allowHermesSteering = phase === "running" && selectedProvider === "hermes";
const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({
threadRef: composerDraftTarget,
@@ -1214,7 +1216,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],
);
const collapsedComposerPrimaryActionDisabled =
(phase === "running" && !allowHermesSteering) ||
phase === "running" ||
isSendBusy ||
isConnecting ||
noProviderAvailable ||
@@ -1763,7 +1765,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting ||
noProviderAvailable ||
environmentUnavailable !== null ||
(phase === "running" && !allowHermesSteering)
phase === "running"
) {
return false;
}
@@ -1781,7 +1783,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isSendBusy,
noProviderAvailable,
phase,
allowHermesSteering,
showPlanFollowUpPrompt,
]);
@@ -2367,56 +2368,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? activePendingProgress.customAnswer ||
"Type your own answer, or leave this blank to use the selected option"
: prompt.trim() ||
(noProviderAvailable ? providerUnavailableMessage : "Ask anything...")}
(noProviderAvailable ? "Enable a provider in Settings" : "Ask anything...")}
</button>
<button
type="button"
className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/90 text-primary-foreground disabled:opacity-30"
disabled={collapsedComposerPrimaryActionDisabled}
aria-label={collapsedComposerPrimaryActionLabel}
onPointerDown={(event) => event.preventDefault()}
onClick={(event) => {
event.stopPropagation();
submitComposer();
}}
>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path
d="M8 3L8 13M8 3L4 7M8 3L12 7"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
{shouldUseCollapsedHermesRunningActions({
isRunning: phase === "running",
allowSendWhileRunning: allowHermesSteering,
}) ? (
<ComposerPrimaryActions
compact
pendingAction={null}
isRunning
allowSendWhileRunning
showPlanFollowUpPrompt={false}
promptHasText={prompt.trim().length > 0}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={
environmentUnavailable !== null ||
noProviderAvailable ||
projectSelectionRequired
}
isPreparingWorktree={false}
hasSendableContent={composerSendState.hasSendableContent}
preserveComposerFocusOnPointerDown
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
onInterrupt={handleInterruptPrimaryAction}
onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
/>
) : (
<button
type="button"
className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/90 text-primary-foreground disabled:opacity-30"
disabled={collapsedComposerPrimaryActionDisabled}
aria-label={collapsedComposerPrimaryActionLabel}
onPointerDown={(event) => event.preventDefault()}
onClick={(event) => {
event.stopPropagation();
submitComposer();
}}
>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path
d="M8 3L8 13M8 3L4 7M8 3L12 7"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
)}
</div>
) : null}
@@ -2601,7 +2575,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
: projectSelectionRequired
? "Choose a project above to start a thread"
: noProviderAvailable
? providerUnavailableMessage
? "Enable a provider in Settings to send a message"
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
@@ -2669,7 +2643,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className="shrink-0 gap-2 px-2 text-muted-foreground/70 sm:px-3"
>
<CircleAlertIcon className="size-4" />
{providerUnavailableMessage}
No provider available
</Button>
) : (
<ProviderModelPicker
@@ -2747,7 +2721,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activeThreadProviderDisplayName={activeThreadProviderDisplayName}
pendingAction={pendingPrimaryAction}
isRunning={phase === "running"}
allowSendWhileRunning={allowHermesSteering}
showPlanFollowUpPrompt={pendingUserInputs.length === 0 && showPlanFollowUpPrompt}
promptHasText={prompt.trim().length > 0}
isSendBusy={isSendBusy}
@@ -1,45 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
formatPendingPrimaryActionLabel,
resolveRunningPrimaryActionMode,
shouldUseCollapsedHermesRunningActions,
} from "./ComposerPrimaryActions";
describe("resolveRunningPrimaryActionMode", () => {
it("keeps stop-only behavior for ordinary running providers", () => {
expect(resolveRunningPrimaryActionMode({ isRunning: true, allowSendWhileRunning: false })).toBe(
"stop",
);
});
it("shows steer and stop actions for a running Hermes provider", () => {
expect(resolveRunningPrimaryActionMode({ isRunning: true, allowSendWhileRunning: true })).toBe(
"steer",
);
expect(
shouldUseCollapsedHermesRunningActions({
isRunning: true,
allowSendWhileRunning: true,
}),
).toBe(true);
});
it("does not replace collapsed actions for idle or ordinary providers", () => {
expect(
shouldUseCollapsedHermesRunningActions({
isRunning: false,
allowSendWhileRunning: true,
}),
).toBe(false);
expect(
shouldUseCollapsedHermesRunningActions({
isRunning: true,
allowSendWhileRunning: false,
}),
).toBe(false);
});
});
import { formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions";
describe("formatPendingPrimaryActionLabel", () => {
it("returns 'Submitting...' while responding", () => {
@@ -18,7 +18,6 @@ interface ComposerPrimaryActionsProps {
compact: boolean;
pendingAction: PendingActionState | null;
isRunning: boolean;
allowSendWhileRunning?: boolean;
showPlanFollowUpPrompt: boolean;
promptHasText: boolean;
isSendBusy: boolean;
@@ -50,21 +49,6 @@ export const formatPendingPrimaryActionLabel = (input: {
return input.questionIndex > 0 ? "Submit answers" : "Submit answer";
};
export function resolveRunningPrimaryActionMode(input: {
readonly isRunning: boolean;
readonly allowSendWhileRunning: boolean;
}): "idle" | "stop" | "steer" {
if (!input.isRunning) return "idle";
return input.allowSendWhileRunning ? "steer" : "stop";
}
export function shouldUseCollapsedHermesRunningActions(input: {
readonly isRunning: boolean;
readonly allowSendWhileRunning: boolean;
}): boolean {
return resolveRunningPrimaryActionMode(input) === "steer";
}
const preventPointerFocus: PointerEventHandler<HTMLElement> = (event) => {
event.preventDefault();
};
@@ -73,7 +57,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
compact,
pendingAction,
isRunning,
allowSendWhileRunning = false,
showPlanFollowUpPrompt,
promptHasText,
isSendBusy,
@@ -142,8 +125,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
);
}
const runningMode = resolveRunningPrimaryActionMode({ isRunning, allowSendWhileRunning });
if (runningMode === "stop") {
if (isRunning) {
return (
<button
type="button"
@@ -159,41 +141,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
);
}
if (runningMode === "steer") {
return (
<div className={cn("flex items-center justify-end", compact ? "gap-1" : "gap-2")}>
<button
type="submit"
className="flex size-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground shadow-xs transition-all enabled:cursor-pointer hover:bg-primary disabled:pointer-events-none disabled:opacity-30"
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent}
aria-label="Send guidance to running Hermes turn"
>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
<path
d="M7 11.5V2.5M7 2.5L3 6.5M7 2.5L11 6.5"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
<button
type="button"
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 transition-all hover:bg-destructive"
{...pointerFocusProps}
onClick={onInterrupt}
aria-label="Stop generation"
>
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
<rect x="2" y="2" width="8" height="8" rx="1.5" />
</svg>
</button>
</div>
);
}
if (showPlanFollowUpPrompt) {
if (promptHasText) {
return (
@@ -434,6 +434,7 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("Show full message");
expect(markup).toContain('data-user-message-collapsible="false"');
expect(markup).toContain("rounded-2xl bg-accent p-3");
});
it("renders inline terminal labels with the composer chip UI", () => {
@@ -890,7 +890,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
return (
<div className="group flex flex-col items-end gap-1">
<div className="relative max-w-[80%] rounded-2xl bg-secondary p-3">
<div className="relative max-w-[80%] rounded-2xl bg-accent p-3">
{regularImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
@@ -51,7 +51,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
contentClassName="flex w-full items-center gap-3"
className={cn(
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
"data-highlighted:bg-muted/56 data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0",
"hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-highlighted:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0 [&[data-highlighted][data-selected]]:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))]",
props.disabledReason &&
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
)}
@@ -521,7 +521,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
return (
<TooltipProvider delay={0}>
<div
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-xl text-popover-foreground"
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
data-model-picker-content="true"
>
{/* Sidebar */}
@@ -568,18 +568,23 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
handleModelSelect(slug, instanceId);
}}
>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
<div
className={cn(
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
showSidebar && "border-l",
)}
>
{/* Search bar */}
<div className="px-4 pt-2.5">
<div className="-translate-y-px rounded-lg bg-accent px-2 py-1">
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
<ComboboxInput
ref={searchInputRef}
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
inputClassName="rounded-none bg-transparent text-sm placeholder:text-muted-foreground/80"
inputClassName="rounded-none bg-transparent text-sm"
placeholder="Search models..."
showTrigger={false}
startAddon={
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/80" />
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
@@ -97,7 +97,10 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
return (
<div className="w-12 shrink-0 overflow-hidden bg-muted/60" data-model-picker-sidebar="true">
<div
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
data-model-picker-sidebar="true"
>
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div
ref={sidebarContentRef}
@@ -115,14 +118,14 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
) : null}
{/* Favorites section */}
{showFavorites ? (
<div className="mb-1 pb-1">
<div className="mb-1 border-b pb-1">
<div className="relative w-full">
<Tooltip>
<TooltipTrigger
render={
<button
className={cn(
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
)}
onClick={() => handleSelect("favorites")}
type="button"
@@ -169,7 +172,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
<button
data-model-picker-provider={entry.instanceId}
className={cn(
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
)}
data-provider-accent-color={entry.accentColor}
@@ -187,8 +187,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
</PopoverTrigger>
<PopoverPopup
align="start"
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
viewportClassName="!overflow-hidden p-0"
className="border-0 bg-transparent p-0 shadow-none before:hidden [-webkit-backdrop-filter:none]! [--viewport-inline-padding:0] [backdrop-filter:none]!"
viewportClassName="rounded-lg !overflow-hidden p-0"
>
<ModelPickerContent
activeInstanceId={activeInstanceId}
@@ -0,0 +1,110 @@
import { describe, expect, it } from "vite-plus/test";
import type { ProviderOptionDescriptor } from "@t3tools/contracts";
import { buildTraitsTriggerDisplay } from "./TraitsPicker";
function selectDescriptor(
id: string,
options: ReadonlyArray<{ id: string; label: string }>,
currentValue: string,
): Extract<ProviderOptionDescriptor, { type: "select" }> {
return { id, label: id, type: "select", options: [...options], currentValue };
}
function fastModeDescriptor(
currentValue: boolean,
): Extract<ProviderOptionDescriptor, { type: "boolean" }> {
return { id: "fastMode", label: "Fast Mode", type: "boolean", currentValue };
}
const EFFORT = selectDescriptor(
"effort",
[
{ id: "high", label: "High" },
{ id: "max", label: "Max" },
],
"high",
);
const CONTEXT_WINDOW = selectDescriptor(
"contextWindow",
[
{ id: "200k", label: "200k" },
{ id: "1m", label: "1M" },
],
"1m",
);
function display(descriptors: ReadonlyArray<ProviderOptionDescriptor>, fastModeEnabled: boolean) {
return buildTraitsTriggerDisplay({
descriptors,
primarySelectDescriptorId: "effort",
ultrathinkPromptControlled: false,
fastModeEnabled,
});
}
describe("buildTraitsTriggerDisplay", () => {
it("omits fast mode from the label entirely when it is off", () => {
expect(display([EFFORT, fastModeDescriptor(false), CONTEXT_WINDOW], false)).toEqual({
label: "High · 1M",
showFastModeIcon: false,
});
});
it("shows the bolt instead of a text label when fast mode is on", () => {
expect(display([EFFORT, fastModeDescriptor(true), CONTEXT_WINDOW], true)).toEqual({
label: "High · 1M",
showFastModeIcon: true,
});
});
it("keeps non-fastMode booleans as text labels", () => {
const thinking: Extract<ProviderOptionDescriptor, { type: "boolean" }> = {
id: "thinking",
label: "Thinking",
type: "boolean",
currentValue: true,
};
expect(display([EFFORT, thinking], false)).toEqual({
label: "High · Thinking On",
showFastModeIcon: false,
});
});
it("falls back to a text label when fast mode is the only trait", () => {
expect(display([fastModeDescriptor(true)], true)).toEqual({
label: "Fast",
showFastModeIcon: false,
});
expect(display([fastModeDescriptor(false)], false)).toEqual({
label: "Normal",
showFastModeIcon: false,
});
});
it("stays blank when descriptors resolve to no label and there is no fast mode", () => {
// A select with neither a currentValue nor an isDefault option yields no
// label. Without a fastMode descriptor present that must stay blank rather
// than falling through to a bogus "Normal".
const unresolved: Extract<ProviderOptionDescriptor, { type: "select" }> = {
id: "effort",
label: "effort",
type: "select",
options: [
{ id: "low", label: "Low" },
{ id: "high", label: "High" },
],
};
expect(display([unresolved], false)).toEqual({ label: "", showFastModeIcon: false });
});
it("still renders the prompt-controlled ultrathink label alongside the bolt", () => {
expect(
buildTraitsTriggerDisplay({
descriptors: [EFFORT, fastModeDescriptor(true)],
primarySelectDescriptorId: "effort",
ultrathinkPromptControlled: true,
fastModeEnabled: true,
}),
).toEqual({ label: "Ultrathink", showFastModeIcon: true });
});
});
+58 -21
View File
@@ -16,7 +16,7 @@ import {
} from "@t3tools/shared/model";
import { memo, useCallback, useState } from "react";
import type { VariantProps } from "class-variance-authority";
import { ChevronDownIcon } from "lucide-react";
import { ChevronDownIcon, ZapIcon } from "lucide-react";
import { Button, buttonVariants } from "../ui/button";
import {
Menu,
@@ -379,6 +379,46 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
);
});
/**
* Build the traits trigger's text label plus whether the fast-mode bolt should
* render. Fast mode is a lightning bolt when on and nothing at all when off —
* "Normal" is the near-universal case and isn't worth the horizontal space. The
* one exception is when fast mode is the only trait, where a bare bolt (or bare
* chevron) would leave the trigger unreadable.
*/
export function buildTraitsTriggerDisplay(input: {
descriptors: ReadonlyArray<ProviderOptionDescriptor>;
primarySelectDescriptorId: string | null;
ultrathinkPromptControlled: boolean;
fastModeEnabled: boolean;
}): { label: string; showFastModeIcon: boolean } {
let hasFastMode = false;
const labels: Array<string> = [];
for (const descriptor of input.descriptors) {
if (descriptor.id === "fastMode" && descriptor.type === "boolean") {
hasFastMode = true;
continue;
}
const label =
input.ultrathinkPromptControlled && descriptor.id === input.primarySelectDescriptorId
? "Ultrathink"
: descriptor.type === "boolean"
? `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
: getProviderOptionCurrentLabel(descriptor);
if (typeof label === "string" && label.length > 0) {
labels.push(label);
}
}
// Only fall back to text when fast mode is genuinely the sole trait. Keying
// off an empty label list alone would also catch descriptors that resolved to
// no label at all, printing a bogus "Normal" for a model without fast mode.
if (labels.length === 0 && hasFastMode) {
return { label: input.fastModeEnabled ? "Fast" : "Normal", showFastModeIcon: false };
}
return { label: labels.join(" · "), showFastModeIcon: input.fastModeEnabled };
}
export const TraitsPicker = memo(function TraitsPicker({
provider,
instanceId,
@@ -393,7 +433,7 @@ export const TraitsPicker = memo(function TraitsPicker({
...persistence
}: TraitsMenuContentProps & TraitsPersistence) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled, fastModeEnabled } =
getTraitsSectionVisibility({
provider,
models,
@@ -415,23 +455,18 @@ export const TraitsPicker = memo(function TraitsPicker({
return null;
}
const triggerLabels: Array<string> = [];
for (const descriptor of descriptors) {
const label =
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
? "Ultrathink"
: descriptor.type === "boolean"
? descriptor.id === "fastMode"
? descriptor.currentValue === true
? "Fast"
: "Normal"
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
: getProviderOptionCurrentLabel(descriptor);
if (typeof label === "string" && label.length > 0) {
triggerLabels.push(label);
}
}
const triggerLabel = triggerLabels.join(" · ");
const { label: triggerLabel, showFastModeIcon } = buildTraitsTriggerDisplay({
descriptors,
primarySelectDescriptorId: primarySelectDescriptor?.id ?? null,
ultrathinkPromptControlled,
fastModeEnabled,
});
const fastModeIcon = showFastModeIcon ? (
<>
<ZapIcon aria-hidden="true" className="size-3 shrink-0 text-foreground/80 opacity-100" />
<span className="sr-only">Fast mode on</span>
</>
) : null;
const isCodexStyle = provider === "codex";
@@ -457,12 +492,14 @@ export const TraitsPicker = memo(function TraitsPicker({
}
>
{isCodexStyle ? (
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
{triggerLabel}
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
{fastModeIcon}
<span className="min-w-0 truncate">{triggerLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
</span>
) : (
<>
{fastModeIcon}
<span>{triggerLabel}</span>
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
</>
@@ -1,7 +1,6 @@
import { ProviderDriverKind } from "@t3tools/contracts";
import { ClaudeAI, CursorIcon, GrokIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons";
import { PROVIDER_OPTIONS } from "../../session-logic";
import { HermesIcon } from "../HermesIcon";
export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>> = {
[ProviderDriverKind.make("codex")]: OpenAI,
@@ -9,7 +8,6 @@ export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>
[ProviderDriverKind.make("opencode")]: OpenCodeIcon,
[ProviderDriverKind.make("cursor")]: CursorIcon,
[ProviderDriverKind.make("grok")]: GrokIcon,
[ProviderDriverKind.make("hermes")]: HermesIcon,
};
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
@@ -1,184 +1,11 @@
import type { HermesGatewayConnectionState, ProviderDriverKind } from "@t3tools/contracts";
export type WizardNavigation =
| { readonly kind: "navigate"; readonly step: number }
| { readonly kind: "blocked"; readonly step: number; readonly error: string };
const IDENTITY_STEP = 1;
const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
export const ADD_PROVIDER_WIZARD_STEPS = ["Driver", "Identity", "Config"] as const;
/**
* Hermes thread bindings outlive a removed gateway, so a new gateway must
* never derive its routing identity from a reusable display name. The UUID is
* generated once by the dialog and remains stable across enrollment retries.
*/
export function createHermesProviderInstanceId(label: string, randomUuid: () => string) {
const suffix = randomUuid()
.replace(/[^a-zA-Z0-9]/gu, "")
.toLowerCase();
if (suffix.length === 0) {
throw new Error("Could not generate a Hermes instance ID.");
}
const labelSlug = label
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/gu, "-")
.replace(/^-+|-+$/gu, "")
.slice(0, 44);
const shortSuffix = suffix.slice(0, 12);
return labelSlug ? `hermes-${labelSlug}-${shortSuffix}` : `hermes-${shortSuffix}`;
}
/**
* Command that installs the gateway plugin into the Hermes profile.
*
* Installation is a manual step performed on the Hermes host — T3 has no
* remote access to it — so the dialog documents the command rather than
* implying anything happens automatically. The script symlinks this repository
* checkout into `~/.hermes/plugins` and enables the plugin.
*/
export const HERMES_PLUGIN_INSTALL_COMMAND = "./integrations/hermes-t3-gateway/install.sh" as const;
/**
* Activates the pairing. The gateway only constructs the platform adapter at
* startup, so it keeps reporting offline until it is restarted.
*/
export const HERMES_GATEWAY_RESTART_COMMAND = "hermes gateway restart" as const;
export function isHermesInstanceRemovedError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
error.code === "instance-removed"
);
}
/**
* Drop an instance the dialog itself just wrote, without clobbering anything
* that changed underneath it.
*
* Used to roll back the settings write when Hermes enrollment fails. The
* server is authoritative between the write and the rollback, so this reads
* the *latest* map rather than restoring a captured pre-write snapshot — that
* would silently revert instances added by another client in between. If the
* id is already gone, or has been replaced by a different config object, the
* write is not ours to undo and `null` signals "no rollback needed".
*/
export function rollbackProviderInstances<T>(input: {
readonly latest: Readonly<Record<string, T>>;
readonly instanceId: string;
readonly written: T;
}): Record<string, T> | null {
const current = input.latest[input.instanceId];
if (current === undefined) return null;
if (current !== input.written) return null;
const next = { ...input.latest };
delete next[input.instanceId];
return next;
}
export function isOwnedHermesEnrollmentRetry(input: {
readonly driver: ProviderDriverKind;
readonly instanceId: string;
readonly createdHermesInstanceId: string | null;
}): boolean {
return (
input.driver === "hermes" &&
input.createdHermesInstanceId !== null &&
input.createdHermesInstanceId === input.instanceId
);
}
/**
* Presentation state of the post-enrollment "waiting for Hermes" panel.
*
* `waiting` is the expected steady state immediately after the command is
* generated — the user still has to paste it and restart the gateway — so it
* is deliberately not modelled as an error. `expired` and `blocked` are the
* two states that need a fresh command, and `connected` is terminal success.
*/
export type HermesWaitingPhase = "waiting" | "connected" | "blocked" | "expired";
export interface HermesWaitingState {
readonly phase: HermesWaitingPhase;
readonly statusLabelState: HermesGatewayConnectionState;
/** True while T3 legitimately has nothing to report yet. */
readonly isPending: boolean;
/** True when the only way forward is minting a replacement command. */
readonly needsNewCommand: boolean;
}
/**
* Resolve what the waiting panel should show.
*
* Connection wins over expiry: once the gateway has dialled in, the one-time
* token has already been consumed and its expiry is irrelevant. `revoked` and
* `upgrade-required` are surfaced ahead of the generic wait because neither
* resolves by waiting longer.
*/
export function resolveHermesWaitingState(input: {
readonly connectionState: HermesGatewayConnectionState | null;
readonly isExpired: boolean;
}): HermesWaitingState {
if (input.connectionState === "connected") {
return {
phase: "connected",
statusLabelState: "connected",
isPending: false,
needsNewCommand: false,
};
}
if (input.connectionState === "upgrade-required" || input.connectionState === "revoked") {
return {
phase: "blocked",
statusLabelState: input.connectionState,
isPending: false,
needsNewCommand: input.connectionState === "revoked",
};
}
if (input.isExpired) {
return {
phase: "expired",
statusLabelState: input.connectionState ?? "offline",
isPending: false,
needsNewCommand: true,
};
}
return {
phase: "waiting",
statusLabelState: input.connectionState ?? "offline",
isPending: true,
needsNewCommand: false,
};
}
export function validateProviderInstanceIdForWizard(input: {
readonly driver: ProviderDriverKind;
readonly instanceId: string;
readonly existingIds: ReadonlySet<string>;
readonly createdHermesInstanceId: string | null;
}): string | null {
if (input.instanceId.length === 0) return "Instance ID is required.";
if (input.instanceId.length > 64) return "Instance ID must be 64 characters or fewer.";
if (!INSTANCE_ID_PATTERN.test(input.instanceId)) {
return "Instance ID must start with a letter and use only letters, digits, '-', or '_'.";
}
if (
input.existingIds.has(input.instanceId) &&
!isOwnedHermesEnrollmentRetry({
driver: input.driver,
instanceId: input.instanceId,
createdHermesInstanceId: input.createdHermesInstanceId,
})
) {
return `An instance named '${input.instanceId}' already exists.`;
}
return null;
}
/**
* Resolve navigation within the add-provider wizard.
*
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more