Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83faf56b65 | ||
|
|
85b8a38455 | ||
|
|
3c9f1db60f | ||
|
|
02abc2cb3d | ||
|
|
7aecc5d47a | ||
|
|
b462ae5f2f |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
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.
|
||||
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.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
@@ -13,35 +13,13 @@ 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`. 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.
|
||||
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
|
||||
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=...`.
|
||||
@@ -67,7 +45,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. 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.
|
||||
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.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
@@ -80,17 +58,9 @@ 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.
|
||||
|
||||
## Tear down only when the testing loop is finished
|
||||
## Finish the test
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
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."
|
||||
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."
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,14 +13,6 @@
|
||||
- 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.
|
||||
|
||||
@@ -771,7 +771,9 @@ export function ReviewSheet(props: ReviewSheetProps) {
|
||||
environment.presentation?.connection ?? {
|
||||
phase: "available",
|
||||
error: null,
|
||||
reason: null,
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
}
|
||||
}
|
||||
resourceName="review"
|
||||
|
||||
@@ -1209,7 +1209,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
environment.presentation?.connection ?? {
|
||||
phase: "available",
|
||||
error: null,
|
||||
reason: null,
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
}
|
||||
}
|
||||
resourceName="terminal"
|
||||
|
||||
@@ -108,8 +108,7 @@ export function ThreadWorkLog(props: {
|
||||
<View className="gap-px">
|
||||
{rows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.canExpand;
|
||||
const fullDetail = expanded ? row.getFullDetail() : null;
|
||||
const canExpand = row.fullDetail !== null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
|
||||
@@ -134,7 +133,7 @@ export function ThreadWorkLog(props: {
|
||||
props.onToggleRow(row.id);
|
||||
}
|
||||
}}
|
||||
onLongPress={() => props.onCopyRow(row.id, row.getCopyText())}
|
||||
onLongPress={() => props.onCopyRow(row.id, row.copyText)}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
@@ -205,7 +204,7 @@ export function ThreadWorkLog(props: {
|
||||
</View>
|
||||
</Pressable>
|
||||
|
||||
{fullDetail ? (
|
||||
{expanded && row.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
|
||||
@@ -218,7 +217,7 @@ export function ThreadWorkLog(props: {
|
||||
selectable
|
||||
className="font-mono text-2xs leading-normal text-foreground-muted"
|
||||
>
|
||||
{fullDetail}
|
||||
{row.fullDetail}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
|
||||
@@ -161,22 +161,20 @@ describe("buildThreadFeed", () => {
|
||||
return;
|
||||
}
|
||||
|
||||
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'",
|
||||
);
|
||||
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",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps MCP inputs available to expanded mobile work rows", () => {
|
||||
@@ -225,55 +223,8 @@ describe("buildThreadFeed", () => {
|
||||
}
|
||||
|
||||
expect(group.activities[0]?.icon).toBe("wrench");
|
||||
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);
|
||||
expect(group.activities[0]?.fullDetail).toContain('"query": "work log"');
|
||||
expect(group.activities[0]?.fullDetail).toContain("repository.search");
|
||||
});
|
||||
|
||||
it("folds settled turn work while leaving the terminal answer visible", () => {
|
||||
@@ -488,9 +439,8 @@ describe("buildThreadFeed", () => {
|
||||
turnId: null,
|
||||
summary: `Tool ${id}`,
|
||||
detail: null,
|
||||
canExpand: false,
|
||||
getFullDetail: () => null,
|
||||
getCopyText: () => id,
|
||||
fullDetail: null,
|
||||
copyText: id,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status,
|
||||
|
||||
@@ -36,9 +36,8 @@ export interface ThreadFeedActivity {
|
||||
readonly turnId: TurnId | null;
|
||||
readonly summary: string;
|
||||
readonly detail: string | null;
|
||||
readonly canExpand: boolean;
|
||||
readonly getFullDetail: () => string | null;
|
||||
readonly getCopyText: () => string;
|
||||
readonly fullDetail: string | null;
|
||||
readonly copyText: string;
|
||||
readonly icon:
|
||||
| "agent"
|
||||
| "alert"
|
||||
@@ -555,27 +554,6 @@ 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 {
|
||||
@@ -1375,14 +1353,7 @@ export function buildThreadFeed(
|
||||
.map<RawThreadFeedEntry>((entry) => {
|
||||
const summary = workEntryHeading(entry);
|
||||
const detail = workEntryPreview(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"),
|
||||
);
|
||||
const fullDetail = buildWorkEntryExpandedBody(entry);
|
||||
return {
|
||||
type: "activity",
|
||||
id: entry.id,
|
||||
@@ -1394,10 +1365,13 @@ export function buildThreadFeed(
|
||||
turnId: entry.turnId,
|
||||
summary,
|
||||
detail,
|
||||
canExpand: workEntryHasExpandedBody(entry),
|
||||
getFullDetail,
|
||||
getCopyText,
|
||||
fullDetail,
|
||||
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),
|
||||
},
|
||||
|
||||
@@ -40,7 +40,9 @@ function environment(
|
||||
connection: {
|
||||
phase,
|
||||
error: phase === "error" ? "Connection failed." : null,
|
||||
reason: phase === "error" ? "authentication" : null,
|
||||
traceId: phase === "error" ? "trace-1" : null,
|
||||
retryAt: null,
|
||||
},
|
||||
serverConfig: null,
|
||||
};
|
||||
|
||||
@@ -8,13 +8,9 @@ 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,
|
||||
@@ -23,12 +19,6 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
|
||||
return {
|
||||
...config,
|
||||
...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-" })));
|
||||
@@ -45,11 +35,7 @@ const makeCookieRequest = (
|
||||
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
// 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,
|
||||
t3_session: sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<
|
||||
|
||||
@@ -438,7 +438,6 @@ 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,
|
||||
@@ -747,13 +746,11 @@ 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) =>
|
||||
@@ -777,7 +774,6 @@ 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,
|
||||
@@ -876,7 +872,6 @@ 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,9 +34,6 @@ 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(
|
||||
@@ -48,22 +45,6 @@ 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;
|
||||
@@ -94,24 +75,6 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
|
||||
makeEnvironmentAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
port: 13773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
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"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -41,7 +41,6 @@ export const make = Effect.gen(function* () {
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
devUrl: config.devUrl,
|
||||
}),
|
||||
};
|
||||
|
||||
|
||||
@@ -202,11 +202,6 @@ 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>,
|
||||
@@ -248,15 +243,6 @@ 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 =
|
||||
@@ -385,10 +371,7 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const credential = yield* generatePairingToken;
|
||||
const isDevStartupToken = config.devUrl !== undefined && input?.purpose === "startup";
|
||||
const ttl =
|
||||
input?.ttl ??
|
||||
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
|
||||
@@ -470,7 +470,6 @@ export const make = Effect.gen(function* () {
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
devUrl: serverConfig.devUrl,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
|
||||
@@ -10,29 +10,15 @@ import * as Result from "effect/Result";
|
||||
|
||||
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 {
|
||||
return input.devUrl === undefined && input.mode !== "desktop"
|
||||
? SESSION_COOKIE_NAME
|
||||
: `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
|
||||
@@ -84,7 +84,6 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -83,8 +83,6 @@ 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()),
|
||||
@@ -193,8 +191,6 @@ 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()),
|
||||
@@ -278,8 +274,6 @@ 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()),
|
||||
@@ -348,8 +342,6 @@ 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()),
|
||||
@@ -403,8 +395,6 @@ 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()),
|
||||
|
||||
@@ -48,7 +48,6 @@ 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) {
|
||||
@@ -96,8 +95,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
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",
|
||||
@@ -120,7 +117,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
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,
|
||||
|
||||
@@ -106,15 +106,6 @@ const EnvServerConfig = Config.all({
|
||||
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),
|
||||
@@ -372,7 +363,6 @@ export const resolveServerConfig = (
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
devAllowedOrigins: env.devAllowedOrigins,
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
|
||||
@@ -26,6 +26,30 @@ import * as SelfUpdate from "./selfUpdate.ts";
|
||||
|
||||
const NODE_PATH = "/usr/local/bin/node";
|
||||
|
||||
/**
|
||||
* The deferred restart runs on a detached fiber, so its rollback performs
|
||||
* real filesystem I/O that advancing the TestClock does not await. Poll on
|
||||
* real time until the expected content lands.
|
||||
*/
|
||||
const eventuallyFileString = Effect.fn("test.eventuallyFileString")(function* (
|
||||
filePath: string,
|
||||
expected: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
let last = "";
|
||||
for (let iteration = 0; iteration < 1_000; iteration += 1) {
|
||||
last = yield* fs.readFileString(filePath);
|
||||
if (last === expected) {
|
||||
return last;
|
||||
}
|
||||
// Yielding (rather than sleeping) keeps this on the real event loop:
|
||||
// TestClock would only advance virtual time and never let the
|
||||
// detached fiber's filesystem writes land.
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.die(new Error(`Expected file contents were not observed at ${filePath}.`));
|
||||
});
|
||||
|
||||
interface RecordedCommand {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -38,6 +62,8 @@ const makeRecordingRunnerLayer = (
|
||||
readonly stdoutFor?:
|
||||
| ((command: string, args: ReadonlyArray<string>) => string | undefined)
|
||||
| undefined;
|
||||
/** Raises a defect (not a typed failure) to exercise unexpected-error paths. */
|
||||
readonly dieWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
|
||||
},
|
||||
) =>
|
||||
Layer.succeed(
|
||||
@@ -46,6 +72,9 @@ const makeRecordingRunnerLayer = (
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
commands.push({ command: input.command, args: input.args });
|
||||
if (options?.dieWhen?.(input.command, input.args) === true) {
|
||||
throw new Error(`${input.command} died unexpectedly`);
|
||||
}
|
||||
const failed = options?.failWhen?.(input.command, input.args) === true;
|
||||
const versionFromPath =
|
||||
input.command === NODE_PATH && input.args[1] === "--version"
|
||||
@@ -257,6 +286,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
|
||||
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
|
||||
readonly failSpawn?: boolean;
|
||||
readonly dieWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
|
||||
}) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -329,6 +359,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
makeRecordingRunnerLayer(commands, {
|
||||
failWhen: options?.failWhen,
|
||||
stdoutFor: options?.stdoutFor,
|
||||
dieWhen: options?.dieWhen,
|
||||
}),
|
||||
configLayer,
|
||||
),
|
||||
@@ -490,7 +521,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rewrites the systemd unit and restarts the boot service", () =>
|
||||
it.effect("rewrites the systemd unit and defers the boot-service restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ bootService: true });
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
@@ -504,12 +535,15 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
|
||||
);
|
||||
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
|
||||
// The restart is deferred so the RPC acknowledgement flushes before
|
||||
// systemd stops this process.
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
["npm", NODE_PATH, "systemctl"],
|
||||
);
|
||||
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.deepEqual(context.commands[3], {
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", "t3code.service"],
|
||||
@@ -520,7 +554,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
|
||||
it.effect("restores the previous unit and permits a retry when the deferred restart fails", () =>
|
||||
Effect.gen(function* () {
|
||||
let failRestart = true;
|
||||
const context = yield* makeContext({
|
||||
@@ -542,9 +576,12 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Restarting the systemd boot service failed");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
// The RPC acknowledges before the restart runs, so a rejected
|
||||
// restart can only roll back and log — never fail the request.
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
yield* eventuallyFileString(unitPath, previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.slice(-2).map((entry) => entry.args),
|
||||
[
|
||||
@@ -558,6 +595,32 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("permits a retry when the deferred restart dies unexpectedly", () =>
|
||||
Effect.gen(function* () {
|
||||
let dieOnRestart = true;
|
||||
const context = yield* makeContext({
|
||||
bootService: true,
|
||||
dieWhen: (command, args) => {
|
||||
if (command !== "systemctl" || args[1] !== "restart" || !dieOnRestart) {
|
||||
return false;
|
||||
}
|
||||
dieOnRestart = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
|
||||
// A defect bypasses the typed rollback handler, so the in-flight guard
|
||||
// has to be released outside it — otherwise this live process would
|
||||
// reject every further update until restarted by other means.
|
||||
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
|
||||
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous systemd unit when daemon-reload fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// detached fire-and-forget child that outlives this process, while Effect's
|
||||
// ChildProcessSpawner ties every child to a scope that kills it.
|
||||
import {
|
||||
SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON,
|
||||
ServerSelfUpdateError,
|
||||
type ServerSelfUpdateCapability,
|
||||
type ServerSelfUpdateInput,
|
||||
@@ -18,6 +19,7 @@ import * as NodeChildProcess from "node:child_process";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -246,7 +248,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
|
||||
|
||||
const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
|
||||
if (alreadyRunning) {
|
||||
return yield* failWith("A server update is already in progress.");
|
||||
return yield* failWith(SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON);
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
@@ -349,37 +351,61 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
|
||||
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
|
||||
targetVersion,
|
||||
});
|
||||
// A successful systemd restart stops this process, so the RPC is
|
||||
// interrupted and the reconnecting client observes the new version.
|
||||
// A rejected restart returns while the old process is still alive;
|
||||
// restore the previous unit and report that failure through the RPC.
|
||||
yield* Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not restart the systemd boot service.", cause),
|
||||
// Deferred like the respawn path: a synchronous systemctl restart
|
||||
// stops this process mid-RPC, so every successful update used to
|
||||
// surface to the client as an interrupted call indistinguishable
|
||||
// from a dropped connection. Deferring lets the acknowledgement
|
||||
// flush first. The trade: a rejected restart can no longer be
|
||||
// reported through this RPC — it rolls back, logs, and clears the
|
||||
// in-flight guard so a retry works.
|
||||
yield* scheduleRestart(
|
||||
Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not restart the systemd boot service.", cause),
|
||||
),
|
||||
);
|
||||
if (restart.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch((restartError) =>
|
||||
Effect.logError(
|
||||
"Server self-update restart was rejected; restoring the previous systemd unit.",
|
||||
).pipe(
|
||||
Effect.annotateLogs({ targetVersion, error: restartError.reason }),
|
||||
Effect.andThen(
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(Effect.andThen(reloadSystemd())),
|
||||
),
|
||||
Effect.catch((rollbackError) =>
|
||||
Effect.logError(
|
||||
"Server self-update could not restore the previous systemd unit after a rejected restart.",
|
||||
).pipe(Effect.annotateLogs({ targetVersion, error: String(rollbackError) })),
|
||||
),
|
||||
// The process survived a rejected restart, so it must stay
|
||||
// updatable — leaving the guard set would reject every retry
|
||||
// until the server was restarted by other means.
|
||||
Effect.ensuring(Ref.set(inFlight, false)),
|
||||
),
|
||||
);
|
||||
if (restart.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch((restartError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.andThen(reloadSystemd()),
|
||||
Effect.mapError((rollbackError) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
restartError,
|
||||
rollbackError,
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Effect.fail(restartError)),
|
||||
),
|
||||
// The typed catch above cannot see defects or interrupts, which
|
||||
// would otherwise strand the guard on a live process. A success
|
||||
// deliberately leaves it set: systemd is about to stop this
|
||||
// process and a second update would race the handoff.
|
||||
Effect.onExit((exit) =>
|
||||
Exit.isSuccess(exit)
|
||||
? Effect.void
|
||||
: Effect.logError("Server self-update restart fiber ended unexpectedly.").pipe(
|
||||
Effect.annotateLogs({ targetVersion, exit: String(exit) }),
|
||||
Effect.ensuring(Ref.set(inFlight, false)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -72,7 +72,6 @@ export class ServerConfig extends Context.Service<
|
||||
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,7 +187,6 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
});
|
||||
|
||||
@@ -43,7 +43,6 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
desktopBootstrapToken: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
@@ -69,7 +68,6 @@ 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,7 +142,6 @@ export const make = Effect.gen(function* () {
|
||||
connectionProbe: true,
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
workspaceTaskTabs: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
},
|
||||
};
|
||||
|
||||
+1
-14
@@ -4,7 +4,6 @@ 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";
|
||||
@@ -49,17 +48,9 @@ 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, ...config.devAllowedOrigins],
|
||||
credentials: true,
|
||||
}
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
@@ -225,10 +216,6 @@ 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,
|
||||
|
||||
@@ -198,8 +198,6 @@ 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");
|
||||
|
||||
@@ -1,227 +0,0 @@
|
||||
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,7 +192,6 @@ describe("OrchestrationEngine", () => {
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getClosedTaskTabs: () => Effect.succeed([]),
|
||||
getSnapshotSequence: () =>
|
||||
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationSessionStatus,
|
||||
ThreadId,
|
||||
WorkspaceTaskId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -598,12 +597,6 @@ 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,
|
||||
@@ -737,13 +730,6 @@ 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;
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderInstanceId,
|
||||
WorkspaceTaskId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -285,11 +284,6 @@ 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"),
|
||||
@@ -404,11 +398,6 @@ 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"),
|
||||
@@ -458,29 +447,6 @@ 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,7 +24,6 @@ import {
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
ThreadForkProvenance,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -79,7 +78,6 @@ const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
forkProvenance: Schema.NullOr(Schema.fromJsonString(ThreadForkProvenance)),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
@@ -119,10 +117,6 @@ 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,
|
||||
@@ -246,39 +240,6 @@ 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 {
|
||||
@@ -363,11 +324,6 @@ 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",
|
||||
@@ -400,11 +356,6 @@ 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",
|
||||
@@ -427,51 +378,10 @@ 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,
|
||||
@@ -480,11 +390,6 @@ 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",
|
||||
@@ -843,19 +748,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getThreadRowById = SqlSchema.findOneOption({
|
||||
Request: ThreadRowByIdLookupInput,
|
||||
const getActiveThreadRowById = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadDbRowSchema,
|
||||
execute: ({ threadId, includeClosed }) =>
|
||||
execute: ({ threadId }) =>
|
||||
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",
|
||||
@@ -879,7 +779,6 @@ 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
|
||||
`,
|
||||
});
|
||||
@@ -1293,11 +1192,6 @@ 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,
|
||||
@@ -1500,11 +1394,6 @@ 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,
|
||||
@@ -1638,11 +1527,6 @@ 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,
|
||||
@@ -1781,11 +1665,6 @@ 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,
|
||||
@@ -1829,17 +1708,6 @@ 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(
|
||||
@@ -2008,7 +1876,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
|
||||
getThreadRowById({ threadId, includeClosed: false }).pipe(
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
|
||||
@@ -2041,11 +1909,6 @@ 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,
|
||||
@@ -2079,7 +1942,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
latestTurnRow,
|
||||
sessionRow,
|
||||
] = yield* Effect.all([
|
||||
getThreadRowById({ threadId, includeClosed: true }).pipe(
|
||||
getActiveThreadRowById({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:getThread:query",
|
||||
@@ -2144,11 +2007,6 @@ 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,
|
||||
@@ -2250,7 +2108,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getArchivedShellSnapshot,
|
||||
getClosedTaskTabs,
|
||||
getSnapshotSequence,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkspaceTaskId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
@@ -478,80 +477,6 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
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-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* 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,
|
||||
});
|
||||
|
||||
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", () =>
|
||||
Effect.gen(function* () {
|
||||
const releaseStart = yield* Deferred.make<void>();
|
||||
|
||||
@@ -41,7 +41,6 @@ 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);
|
||||
|
||||
@@ -630,20 +629,7 @@ const make = Effect.gen(function* () {
|
||||
if (input.modelSelection !== undefined) {
|
||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||
}
|
||||
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 normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
const activeSession = yield* providerService
|
||||
.listSessions()
|
||||
|
||||
@@ -94,15 +94,6 @@ 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,216 +0,0 @@
|
||||
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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
WorkspaceTaskId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -25,10 +24,6 @@ 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.
|
||||
@@ -360,47 +355,6 @@ 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",
|
||||
@@ -412,11 +366,6 @@ 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,
|
||||
@@ -693,24 +642,6 @@ 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({
|
||||
@@ -728,9 +659,6 @@ 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,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -7,7 +7,6 @@ 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,
|
||||
@@ -70,7 +69,7 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
|
||||
if (Option.isNone(snapshot)) {
|
||||
return yield* failEnvironmentNotFound("thread_not_found");
|
||||
}
|
||||
return projectThreadDetailSnapshot(snapshot.value);
|
||||
return snapshot.value;
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
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}`;
|
||||
}
|
||||
@@ -280,11 +280,6 @@ 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,
|
||||
@@ -409,9 +404,6 @@ 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,
|
||||
}),
|
||||
})),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ProjectId, ProviderInstanceId, ThreadId, WorkspaceTaskId } from "@t3tools/contracts";
|
||||
import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -78,11 +78,6 @@ 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"),
|
||||
@@ -145,11 +140,6 @@ 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,12 +14,11 @@ import {
|
||||
ProjectionThreadRepository,
|
||||
type ProjectionThreadRepositoryShape,
|
||||
} from "../Services/ProjectionThreads.ts";
|
||||
import { ModelSelection, ThreadForkProvenance } from "@t3tools/contracts";
|
||||
import { ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
const ProjectionThreadDbRow = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
forkProvenance: Schema.NullOr(Schema.fromJsonString(ThreadForkProvenance)),
|
||||
}),
|
||||
);
|
||||
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
|
||||
@@ -34,11 +33,6 @@ 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,
|
||||
@@ -62,11 +56,6 @@ 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},
|
||||
@@ -90,11 +79,6 @@ 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,
|
||||
@@ -125,11 +109,6 @@ 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",
|
||||
@@ -162,11 +141,6 @@ 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,7 +47,6 @@ 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.
|
||||
@@ -94,7 +93,6 @@ export const migrationEntries = [
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
[35, "ProjectionThreadTasks", Migration0035],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
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"));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,53 +0,0 @@
|
||||
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,9 +14,7 @@ import {
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
ThreadForkProvenance,
|
||||
TurnId,
|
||||
WorkspaceTaskId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -28,11 +26,6 @@ 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,7 +30,6 @@ 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) =>
|
||||
|
||||
@@ -530,29 +530,6 @@ 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,7 +51,6 @@ 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";
|
||||
@@ -88,42 +87,6 @@ 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",
|
||||
@@ -309,10 +272,6 @@ 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;
|
||||
}
|
||||
@@ -329,9 +288,6 @@ 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);
|
||||
}
|
||||
@@ -345,11 +301,6 @@ 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.`;
|
||||
@@ -409,7 +360,6 @@ export function normalizeClaudeCliEffort(
|
||||
if (
|
||||
effort === "xhigh" &&
|
||||
model !== "claude-fable-5" &&
|
||||
model !== "claude-opus-5" &&
|
||||
model !== "claude-opus-4-8" &&
|
||||
model !== "claude-sonnet-5"
|
||||
) {
|
||||
@@ -887,15 +837,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)
|
||||
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
|
||||
? undefined
|
||||
: supportsClaudeFable5(parsedVersion)
|
||||
? formatClaudeOpus5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
: supportsClaudeOpus48(parsedVersion)
|
||||
? formatClaudeFable5UpgradeMessage(parsedVersion)
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
|
||||
@@ -1842,62 +1842,6 @@ 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(
|
||||
|
||||
@@ -196,7 +196,6 @@ 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"),
|
||||
|
||||
@@ -380,7 +380,6 @@ const buildAppUnderTest = (options?: {
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: defaultDesktopBootstrapToken,
|
||||
@@ -1329,8 +1328,6 @@ 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)),
|
||||
);
|
||||
@@ -3249,34 +3246,6 @@ 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* () {
|
||||
@@ -5553,16 +5522,11 @@ 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 }),
|
||||
@@ -5629,11 +5593,6 @@ 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)),
|
||||
);
|
||||
|
||||
|
||||
@@ -81,7 +81,6 @@ 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(
|
||||
@@ -139,7 +138,6 @@ 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: () =>
|
||||
@@ -196,7 +194,6 @@ 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()),
|
||||
@@ -247,7 +244,6 @@ 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()),
|
||||
|
||||
+3
-44
@@ -68,10 +68,6 @@ 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";
|
||||
@@ -296,7 +292,6 @@ 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],
|
||||
@@ -989,21 +984,6 @@ 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,
|
||||
@@ -1233,7 +1213,6 @@ const makeWsRpcLayer = (
|
||||
).pipe(
|
||||
Effect.map((events) => Array.from(events)),
|
||||
Effect.flatMap(enrichOrchestrationEvents),
|
||||
Effect.map((events) => events.map(projectActivityEvent)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationReplayEventsError({
|
||||
@@ -1368,23 +1347,6 @@ 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,
|
||||
@@ -1398,7 +1360,7 @@ const makeWsRpcLayer = (
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event: projectActivityEvent(event),
|
||||
event,
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1433,10 +1395,7 @@ const makeWsRpcLayer = (
|
||||
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
|
||||
.pipe(
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event: projectActivityEvent(event),
|
||||
})),
|
||||
Stream.map((event) => ({ kind: "event" as const, event })),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationGetSnapshotError({
|
||||
@@ -1488,7 +1447,7 @@ const makeWsRpcLayer = (
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot: projectThreadDetailSnapshot(snapshot.value),
|
||||
snapshot: snapshot.value,
|
||||
}),
|
||||
afterSnapshot,
|
||||
);
|
||||
|
||||
@@ -1,230 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@ import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
import { AppRoot } from "./AppRoot";
|
||||
import { AppRoot, ServerRestartReconnectHost } from "./AppRoot";
|
||||
|
||||
describe("AppRoot", () => {
|
||||
it("shares the application atom registry with routed UI and renderer-wide desktop hosts", () => {
|
||||
@@ -16,9 +16,13 @@ describe("AppRoot", () => {
|
||||
const children = Children.toArray(
|
||||
(root as ReactElement<{ readonly children: ReactNode }>).props.children,
|
||||
);
|
||||
expect(children).toHaveLength(3);
|
||||
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts);
|
||||
expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost);
|
||||
expect(children).toHaveLength(4);
|
||||
// The restart-reconnect host is inside the registry provider (it reads
|
||||
// environment atoms) and outside the router, because a server restart
|
||||
// outlives the route the update was triggered from.
|
||||
expect(isValidElement(children[0]) && children[0].type).toBe(ServerRestartReconnectHost);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(RouterProvider);
|
||||
expect(isValidElement(children[2]) && children[2].type).toBe(PreviewAutomationHosts);
|
||||
expect(isValidElement(children[3]) && children[3].type).toBe(ElectronBrowserHost);
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,18 @@ import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
import { useServerRestartReconnect } from "./useServerRestartReconnect";
|
||||
|
||||
/**
|
||||
* Reconnects environments through an expected server restart. Mounted here
|
||||
* because a restart outlives the view it was triggered from — the update
|
||||
* action appears both in the chat composer's skew banner and in
|
||||
* Settings → Connections.
|
||||
*/
|
||||
export function ServerRestartReconnectHost() {
|
||||
useServerRestartReconnect();
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns renderer-wide providers. The Electron browser host intentionally sits
|
||||
@@ -13,6 +25,7 @@ import type { AppRouter } from "./router";
|
||||
export function AppRoot({ router }: { readonly router: AppRouter }) {
|
||||
return (
|
||||
<AppAtomRegistryProvider>
|
||||
<ServerRestartReconnectHost />
|
||||
<RouterProvider router={router} />
|
||||
<PreviewAutomationHosts />
|
||||
<ElectronBrowserHost />
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { isServerRestarting, useServerRestartExpected } from "~/serverRestartStore";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
@@ -115,7 +116,6 @@ 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 {
|
||||
@@ -276,6 +276,7 @@ import { RightPanelSheet } from "./RightPanelSheet";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { Button } from "./ui/button";
|
||||
import { Spinner } from "./ui/spinner";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
@@ -1620,6 +1621,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
connection: activeEnvironment.connection,
|
||||
};
|
||||
}, [activeEnvironment, activeEnvironmentUnavailable, activeEnvironmentUnavailableLabel]);
|
||||
// While a server self-update restart is expected, disconnects are routine:
|
||||
// present them calmly and retry fast instead of letting exponential
|
||||
// backoff strand the client asleep when the server comes back.
|
||||
const activeEnvironmentId = activeEnvironment?.environmentId ?? null;
|
||||
const activeEnvironmentRestartExpected = useServerRestartExpected(activeEnvironmentId);
|
||||
const activeEnvironmentRestarting = isServerRestarting({
|
||||
restartExpected: activeEnvironmentRestartExpected,
|
||||
environmentUnavailable: activeEnvironmentUnavailable,
|
||||
});
|
||||
// Reconnecting through the restart (and ending the window once its restart
|
||||
// has been seen through) is owned by useServerRestartReconnect at the app
|
||||
// level, since an update can be triggered from Settings → Connections too.
|
||||
// This view only presents the result.
|
||||
const handleReconnectActiveEnvironment = useCallback(
|
||||
async (environmentId: EnvironmentId) => {
|
||||
const result = await retryEnvironment(environmentId);
|
||||
@@ -1833,7 +1847,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
|
||||
const systemComposerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const items: ComposerBannerStackItem[] = [];
|
||||
if (activeEnvironmentUnavailableState) {
|
||||
if (activeEnvironmentUnavailableState && activeEnvironmentRestarting) {
|
||||
// An expected self-update restart: the disconnect and the transient
|
||||
// connection errors behind it are routine, so keep the tone neutral
|
||||
// and let the fast auto-retry loop do the work instead of asking the
|
||||
// user to reconnect by hand.
|
||||
items.push({
|
||||
id: `environment-restarting:${activeEnvironmentUnavailableState.environmentId}`,
|
||||
variant: "info",
|
||||
icon: <Spinner className="size-4" />,
|
||||
title: `${activeEnvironmentUnavailableState.label} is restarting`,
|
||||
description: "Finishing the server update — reconnecting automatically.",
|
||||
});
|
||||
} else if (activeEnvironmentUnavailableState) {
|
||||
const connection = activeEnvironmentUnavailableState.connection;
|
||||
const isReconnecting =
|
||||
connection.phase === "connecting" || connection.phase === "reconnecting";
|
||||
@@ -1873,7 +1899,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
showVersionMismatchBanner &&
|
||||
versionMismatch &&
|
||||
versionMismatchDismissKey &&
|
||||
versionMismatchEnvironmentId
|
||||
versionMismatchEnvironmentId &&
|
||||
// The mismatch data predates the disconnect; during an expected
|
||||
// restart it is stale and its update action would double-trigger.
|
||||
!activeEnvironmentRestarting
|
||||
) {
|
||||
items.push({
|
||||
id: `version-mismatch:${versionMismatchDismissKey}`,
|
||||
@@ -1907,6 +1936,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
return items;
|
||||
}, [
|
||||
activeEnvironmentRestarting,
|
||||
activeEnvironmentUnavailableState,
|
||||
handleReconnectActiveEnvironment,
|
||||
navigate,
|
||||
@@ -4726,18 +4756,6 @@ 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,
|
||||
@@ -5668,7 +5686,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
/>
|
||||
</header>
|
||||
|
||||
<WorkspaceTaskTabs />
|
||||
<ThreadErrorBanner
|
||||
error={threadError}
|
||||
onDismiss={() => setThreadError(activeThread.id, null)}
|
||||
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsDownUpIcon,
|
||||
ChevronsUpDownIcon,
|
||||
Columns2Icon,
|
||||
PilcrowIcon,
|
||||
Rows3Icon,
|
||||
@@ -34,7 +32,6 @@ 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";
|
||||
@@ -42,7 +39,6 @@ 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 {
|
||||
@@ -450,8 +446,6 @@ export default function DiffPanel({
|
||||
}),
|
||||
[collapsedDiffFileKeys, renderableFiles],
|
||||
);
|
||||
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
|
||||
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath) return;
|
||||
@@ -502,18 +496,6 @@ 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);
|
||||
@@ -713,30 +695,6 @@ 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"
|
||||
@@ -866,7 +824,7 @@ export default function DiffPanel({
|
||||
<AnnotatableCodeView
|
||||
viewerRef={codeViewRef}
|
||||
key={collapseScopeKey ?? reviewSectionId}
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto [&>div>div:last-child]:top-0! [&>div>div:last-child]:bottom-auto!"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto"
|
||||
files={codeViewFiles}
|
||||
sectionId={reviewSectionId}
|
||||
sectionTitle={reviewSectionTitle}
|
||||
|
||||
@@ -2,13 +2,27 @@ import type { Dispatch, ReactElement, SetStateAction } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON,
|
||||
ServerSelfUpdateError,
|
||||
type EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
updateServer: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
}));
|
||||
|
||||
const restartStore = vi.hoisted(() => ({
|
||||
expect: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
expected: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
const environmentState = vi.hoisted(() => ({
|
||||
useEnvironment: vi.fn(() => ({ connection: { phase: "connected" } })),
|
||||
}));
|
||||
|
||||
const hooks = vi.hoisted(() => {
|
||||
let cursor = 0;
|
||||
let slots: unknown[] = [];
|
||||
@@ -78,6 +92,18 @@ vi.mock("~/state/use-atom-command", () => ({
|
||||
vi.mock("./ui/toast", () => ({
|
||||
toastManager: { add: testState.toast },
|
||||
}));
|
||||
vi.mock("~/serverRestartStore", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/serverRestartStore")>();
|
||||
return {
|
||||
...actual,
|
||||
expectServerRestart: restartStore.expect,
|
||||
clearExpectedServerRestart: restartStore.clear,
|
||||
useServerRestartExpected: restartStore.expected,
|
||||
};
|
||||
});
|
||||
vi.mock("~/state/environments", () => ({
|
||||
useEnvironment: environmentState.useEnvironment,
|
||||
}));
|
||||
|
||||
import { ServerUpdateAction } from "./ServerUpdateAction";
|
||||
|
||||
@@ -118,6 +144,12 @@ describe("ServerUpdateAction", () => {
|
||||
hooks.reset();
|
||||
testState.updateServer.mockReset();
|
||||
testState.toast.mockReset();
|
||||
restartStore.expect.mockReset();
|
||||
restartStore.clear.mockReset();
|
||||
restartStore.expected.mockReset();
|
||||
restartStore.expected.mockReturnValue(false);
|
||||
environmentState.useEnvironment.mockReset();
|
||||
environmentState.useEnvironment.mockReturnValue({ connection: { phase: "connected" } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -195,4 +227,71 @@ describe("ServerUpdateAction", () => {
|
||||
expect.objectContaining({ title: "Server update failed" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("re-arms the restart window when a slow install finally succeeds", async () => {
|
||||
const update =
|
||||
deferred<
|
||||
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
|
||||
>();
|
||||
testState.updateServer.mockReturnValue(update.promise);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
expect(restartStore.expect).toHaveBeenCalledTimes(1);
|
||||
|
||||
// An install can outlast the 90s restart window armed at click time, so
|
||||
// the acknowledgement must restart the clock or the ensuing disconnect
|
||||
// would be presented as an outage.
|
||||
await vi.advanceTimersByTimeAsync(5 * 60_000);
|
||||
update.resolve(AsyncResult.success({ targetVersion: "0.0.29", method: "boot-service" }));
|
||||
await flushPromises();
|
||||
|
||||
expect(restartStore.expect).toHaveBeenCalledTimes(2);
|
||||
expect(restartStore.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("re-arms the restart window on an interrupted restart RPC", async () => {
|
||||
testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
await flushPromises();
|
||||
|
||||
expect(restartStore.expect).toHaveBeenCalledTimes(2);
|
||||
expect(restartStore.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("withdraws the restart expectation when the server reports a real failure", async () => {
|
||||
testState.updateServer.mockResolvedValue(
|
||||
AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ServerSelfUpdateError({ reason: "Could not install the requested t3 version." }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
await flushPromises();
|
||||
|
||||
// The server answered, so it is still alive and no restart is coming.
|
||||
expect(restartStore.clear).toHaveBeenCalledTimes(1);
|
||||
expect(testState.toast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Server update failed" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the restart expectation when an update is already in progress", async () => {
|
||||
testState.updateServer.mockResolvedValue(
|
||||
AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ServerSelfUpdateError({ reason: SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
renderAction().props.onClick?.();
|
||||
await flushPromises();
|
||||
|
||||
// An earlier request is still installing, so a restart really is pending
|
||||
// — clearing here would restore the harsh reconnect UI mid-restart.
|
||||
expect(restartStore.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,23 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
|
||||
import {
|
||||
ServerSelfUpdateError,
|
||||
type EnvironmentId,
|
||||
type ServerSelfUpdateCapability,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import {
|
||||
clearExpectedServerRestart,
|
||||
expectServerRestart,
|
||||
isExpectedRestartResolved,
|
||||
useServerRestartExpected,
|
||||
} from "~/serverRestartStore";
|
||||
import { useEnvironment } from "~/state/environments";
|
||||
import { serverEnvironment } from "~/state/server";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { manualServerUpdateCommand } from "~/versionSkew";
|
||||
@@ -24,6 +36,18 @@ function updateFailureMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "Server update failed.";
|
||||
}
|
||||
|
||||
/**
|
||||
* The server rejects a second update while one is already installing. That
|
||||
* failure means a restart is still pending from the earlier request, so the
|
||||
* restart expectation must survive it — unlike every other failure, which
|
||||
* proves nothing is coming.
|
||||
*/
|
||||
const isServerSelfUpdateError = Schema.is(ServerSelfUpdateError);
|
||||
|
||||
function isUpdateAlreadyRunning(error: unknown): boolean {
|
||||
return isServerSelfUpdateError(error) && error.isAlreadyRunning;
|
||||
}
|
||||
|
||||
/**
|
||||
* The call-to-action for a version-skewed server, matched to the update path
|
||||
* it advertises: a one-click install-and-restart for servers that can update
|
||||
@@ -80,6 +104,56 @@ export function ServerUpdateAction({
|
||||
[],
|
||||
);
|
||||
|
||||
// The restart is scheduled after the RPC is acknowledged, so a rejected
|
||||
// restart — or a replacement that comes back on the old version — can no
|
||||
// longer be reported through the call. Without a release path the mismatch
|
||||
// banner would keep its only action disabled for the full safety window.
|
||||
//
|
||||
// The signal is the environment going away and then answering again while
|
||||
// this component is still mounted: still mounted means the skew is
|
||||
// unresolved, so whatever restarted did not deliver the new version.
|
||||
// Deliberately independent of the restart window, which is UI presentation
|
||||
// state and can lapse or be re-armed for unrelated reasons.
|
||||
// Two ways that resolves, because a rejected restart may or may not have
|
||||
// taken the connection down with it:
|
||||
// - the environment went away and came back, so something restarted but
|
||||
// did not deliver the new version; or
|
||||
// - the restart window lapsed with the connection never dropping, so no
|
||||
// restart ever happened (systemd refused it and rolled back).
|
||||
const connectionPhase = useEnvironment(environmentId)?.connection.phase ?? null;
|
||||
const connectionUnavailable = connectionPhase !== null && connectionPhase !== "connected";
|
||||
const restartExpected = useServerRestartExpected(environmentId);
|
||||
const wentAwayRef = useRef(false);
|
||||
const sawWindowRef = useRef(false);
|
||||
if (connectionUnavailable) {
|
||||
wentAwayRef.current = true;
|
||||
}
|
||||
if (restartExpected) {
|
||||
// Guards against reading a not-yet-rendered window as "already lapsed"
|
||||
// in the render between the click and the store update landing.
|
||||
sawWindowRef.current = true;
|
||||
}
|
||||
const restartResolved = isExpectedRestartResolved({
|
||||
sawRestartWindow: sawWindowRef.current,
|
||||
restartExpected,
|
||||
wentAway: wentAwayRef.current,
|
||||
environmentUnavailable: connectionUnavailable,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (!restartResolved || !inFlightRef.current) {
|
||||
return;
|
||||
}
|
||||
wentAwayRef.current = false;
|
||||
sawWindowRef.current = false;
|
||||
if (expiryRef.current !== null) {
|
||||
clearTimeout(expiryRef.current);
|
||||
expiryRef.current = null;
|
||||
}
|
||||
attemptRef.current += 1;
|
||||
inFlightRef.current = false;
|
||||
setPending(false);
|
||||
}, [restartResolved]);
|
||||
|
||||
const handleUpdate = () => {
|
||||
// Synchronous re-entry guard: setPending is async, so a rapid
|
||||
// double-click would otherwise dispatch two updates.
|
||||
@@ -87,6 +161,11 @@ export function ServerUpdateAction({
|
||||
return;
|
||||
}
|
||||
inFlightRef.current = true;
|
||||
// Only outages observed during this attempt may resolve it. An earlier
|
||||
// unrelated blip would otherwise satisfy the resolve predicate on the
|
||||
// very next render and re-enable the button mid-update.
|
||||
wentAwayRef.current = false;
|
||||
sawWindowRef.current = false;
|
||||
const attempt = attemptRef.current + 1;
|
||||
attemptRef.current = attempt;
|
||||
const ownsAttempt = () => attemptRef.current === attempt;
|
||||
@@ -115,7 +194,18 @@ export function ServerUpdateAction({
|
||||
clearTimeout(expiry);
|
||||
expiry = armExpiry();
|
||||
}
|
||||
// The install can consume most of the request window, so the window
|
||||
// armed at click time may already have lapsed by the time the restart
|
||||
// actually begins. Re-arm from the handoff, not from the click.
|
||||
expectServerRestart(environmentId);
|
||||
};
|
||||
// Armed before dispatch: the boot-service path acknowledges and then
|
||||
// drops every connection, and even the respawn acknowledgement can lose
|
||||
// the race against the disconnect. An explicit RPC failure proves the
|
||||
// server stayed alive, so the expectation is withdrawn there; on
|
||||
// success or interrupt it is re-armed from that point and expires on its
|
||||
// own if the server never returns.
|
||||
expectServerRestart(environmentId);
|
||||
void Promise.resolve()
|
||||
.then(() =>
|
||||
updateServer({
|
||||
@@ -129,14 +219,21 @@ export function ServerUpdateAction({
|
||||
// An interrupt may be the expected boot-service disconnect, but it
|
||||
// can also be client-side cancellation before restart was accepted.
|
||||
// Release the action quietly; version sync will remove it when a
|
||||
// successful replacement reconnects.
|
||||
// successful replacement reconnects. Re-arm from here for the same
|
||||
// reason as the success path: a long install may have outlasted the
|
||||
// window armed at click time.
|
||||
if (isAtomCommandInterrupted(result)) {
|
||||
expectServerRestart(environmentId);
|
||||
return;
|
||||
}
|
||||
const failure = squashAtomCommandFailure(result);
|
||||
if (!isUpdateAlreadyRunning(failure)) {
|
||||
clearExpectedServerRestart(environmentId);
|
||||
}
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update failed",
|
||||
description: updateFailureMessage(squashAtomCommandFailure(result)),
|
||||
description: updateFailureMessage(failure),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -152,6 +249,9 @@ export function ServerUpdateAction({
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!ownsAttempt()) return;
|
||||
if (!isUpdateAlreadyRunning(error)) {
|
||||
clearExpectedServerRestart(environmentId);
|
||||
}
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update failed",
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
AlarmClockOffIcon,
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
CircleDashedIcon,
|
||||
@@ -32,7 +33,6 @@ import {
|
||||
SearchIcon,
|
||||
ServerIcon,
|
||||
SquarePenIcon,
|
||||
SquareStackIcon,
|
||||
Trash2Icon,
|
||||
Undo2Icon,
|
||||
} from "lucide-react";
|
||||
@@ -101,11 +101,6 @@ 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,
|
||||
@@ -122,11 +117,7 @@ import {
|
||||
sortThreadsForSidebarV2,
|
||||
} from "./Sidebar.logic";
|
||||
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
} from "./ThreadStatusIndicators";
|
||||
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
import {
|
||||
resolveSnoozePresets,
|
||||
snoozeWakeDescription,
|
||||
@@ -218,23 +209,6 @@ 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,
|
||||
@@ -244,13 +218,11 @@ 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;
|
||||
@@ -264,11 +236,7 @@ function SidebarV2ThreadTooltip({
|
||||
side="right"
|
||||
align="start"
|
||||
sideOffset={8}
|
||||
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))",
|
||||
}}
|
||||
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"
|
||||
>
|
||||
<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>
|
||||
@@ -313,14 +281,6 @@ 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" />
|
||||
@@ -401,7 +361,6 @@ 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;
|
||||
@@ -539,7 +498,6 @@ 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;
|
||||
@@ -570,7 +528,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
modelInstanceId={modelInstanceId}
|
||||
modelLabel={modelLabel}
|
||||
branchMismatch={branchMismatch}
|
||||
tabCount={props.tabCount}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -690,6 +647,7 @@ 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
|
||||
@@ -756,7 +714,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
variant === "slim" && variantAction === "unsettle"
|
||||
? props.isActive
|
||||
? "text-muted-foreground/70"
|
||||
: cn("text-muted-foreground/35 transition-colors", settledPrHoverClass)
|
||||
: "text-muted-foreground/35 transition-colors group-hover/v2-row:text-muted-foreground/65"
|
||||
: prStatus.colorClass,
|
||||
)}
|
||||
aria-label={prStatus.tooltip}
|
||||
@@ -803,7 +761,6 @@ 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. */}
|
||||
@@ -979,10 +936,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
) : null}
|
||||
</span>
|
||||
</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-1 flex min-w-0">{title}</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>
|
||||
@@ -1097,34 +1051,6 @@ 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
|
||||
@@ -1437,15 +1363,13 @@ 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 task of groupThreadsByWorkspaceTask(visible)) {
|
||||
const thread = taskPresentationThread(task, routeThreadKey);
|
||||
for (const thread of visible) {
|
||||
// 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
|
||||
@@ -1454,22 +1378,17 @@ export default function SidebarV2() {
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true;
|
||||
const supportsSnooze =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
|
||||
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 }),
|
||||
};
|
||||
});
|
||||
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
|
||||
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
|
||||
// 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 (tabStates.every((state) => state.snoozed)) {
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) {
|
||||
snoozed.push(thread);
|
||||
} else if (tabStates.every((state) => state.settled)) {
|
||||
} else if (
|
||||
supportsSettlement &&
|
||||
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
|
||||
) {
|
||||
settled.push(thread);
|
||||
} else {
|
||||
active.push(thread);
|
||||
@@ -1494,7 +1413,6 @@ export default function SidebarV2() {
|
||||
serverConfigs,
|
||||
snoozeWakeTick,
|
||||
threads,
|
||||
routeThreadKey,
|
||||
]);
|
||||
|
||||
// Arm a timeout for the earliest upcoming wake so the shelf empties the
|
||||
@@ -1532,14 +1450,17 @@ 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 (routeTaskKey !== null) {
|
||||
if (routeThreadKey !== null) {
|
||||
const routeThread = settledThreads
|
||||
.slice(settledVisibleCount)
|
||||
.find((thread) => workspaceTaskKey(thread) === routeTaskKey);
|
||||
.find(
|
||||
(thread) =>
|
||||
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
|
||||
);
|
||||
if (routeThread !== undefined) visible.push(routeThread);
|
||||
}
|
||||
return visible;
|
||||
}, [routeTaskKey, settledThreads, settledVisibleCount]);
|
||||
}, [routeThreadKey, settledThreads, settledVisibleCount]);
|
||||
const hiddenSettledCount = settledThreads.length - visibleSettledThreads.length;
|
||||
const showMoreSettled = useCallback(
|
||||
() => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT),
|
||||
@@ -1549,12 +1470,13 @@ export default function SidebarV2() {
|
||||
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
|
||||
const renderedSettledThreads = useMemo(() => {
|
||||
if (settledShelfExpanded) return visibleSettledThreads;
|
||||
if (routeTaskKey === null) return [];
|
||||
if (routeThreadKey === null) return [];
|
||||
const routeThread = visibleSettledThreads.find(
|
||||
(thread) => workspaceTaskKey(thread) === routeTaskKey,
|
||||
(thread) =>
|
||||
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
|
||||
);
|
||||
return routeThread === undefined ? [] : [routeThread];
|
||||
}, [routeTaskKey, settledShelfExpanded, visibleSettledThreads]);
|
||||
}, [routeThreadKey, 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
|
||||
@@ -1567,10 +1489,13 @@ 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 (routeTaskKey === null) return [];
|
||||
const routeThread = snoozedThreads.find((thread) => workspaceTaskKey(thread) === routeTaskKey);
|
||||
if (routeThreadKey === null) return [];
|
||||
const routeThread = snoozedThreads.find(
|
||||
(thread) =>
|
||||
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
|
||||
);
|
||||
return routeThread === undefined ? [] : [routeThread];
|
||||
}, [routeTaskKey, snoozedShelfExpanded, snoozedThreads]);
|
||||
}, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]);
|
||||
|
||||
const orderedThreads = useMemo(
|
||||
() => [...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads],
|
||||
@@ -1882,52 +1807,6 @@ 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(
|
||||
@@ -1943,20 +1822,13 @@ 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 = selectedTabEntries.map(([, thread]) => thread);
|
||||
const snoozableThreads = threadKeys.flatMap((threadKey) => {
|
||||
const thread = threadByKeyRef.current.get(threadKey);
|
||||
return thread ? [thread] : [];
|
||||
});
|
||||
const canSnoozeSelection = snoozableThreads.every(
|
||||
(thread) =>
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true &&
|
||||
@@ -1993,7 +1865,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(selectedTabsByKey.keys());
|
||||
const coSnoozingKeys = new Set(threadKeys);
|
||||
for (const thread of snoozableThreads) {
|
||||
attemptSnooze(scopeThreadRef(thread.environmentId, thread.id), preset, {
|
||||
coSnoozingKeys,
|
||||
@@ -2008,16 +1880,18 @@ 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(selectedTabsByKey.keys());
|
||||
for (const [, thread] of selectedTabEntries) {
|
||||
if (thread.settledOverride === "settled") continue;
|
||||
const coSettlingKeys = new Set(threadKeys);
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = threadByKeyRef.current.get(threadKey);
|
||||
if (!thread || thread.settledOverride === "settled") continue;
|
||||
attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys });
|
||||
}
|
||||
clearSelection();
|
||||
return;
|
||||
}
|
||||
if (clicked.value === "mark-unread") {
|
||||
for (const [threadKey, thread] of selectedTabEntries) {
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = threadByKeyRef.current.get(threadKey);
|
||||
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
|
||||
}
|
||||
clearSelection();
|
||||
@@ -2028,8 +1902,8 @@ export default function SidebarV2() {
|
||||
const confirmed = await settlePromise(() =>
|
||||
api.dialogs.confirm(
|
||||
[
|
||||
`Delete ${count} task${count === 1 ? "" : "s"}?`,
|
||||
"This permanently clears conversation history for every tab in these tasks.",
|
||||
`Delete ${count} thread${count === 1 ? "" : "s"}?`,
|
||||
"This permanently clears conversation history for these threads.",
|
||||
].join("\n"),
|
||||
),
|
||||
);
|
||||
@@ -2040,7 +1914,9 @@ 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, thread] of selectedTabEntries) {
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = threadByKeyRef.current.get(threadKey);
|
||||
if (!thread) continue;
|
||||
const result = await deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
|
||||
deletedThreadKeys,
|
||||
});
|
||||
@@ -2070,7 +1946,6 @@ export default function SidebarV2() {
|
||||
markThreadUnread,
|
||||
removeFromSelection,
|
||||
serverConfigs,
|
||||
taskTabsByThreadKey,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2087,7 +1962,6 @@ 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
|
||||
@@ -2115,8 +1989,8 @@ export default function SidebarV2() {
|
||||
...(supportsSettlement
|
||||
? [
|
||||
isSettled
|
||||
? { id: "unsettle", label: "Un-settle task" }
|
||||
: { id: "settle", label: "Settle task" },
|
||||
? { id: "unsettle", label: "Un-settle thread" }
|
||||
: { id: "settle", label: "Settle thread" },
|
||||
]
|
||||
: []),
|
||||
...(supportsSnooze
|
||||
@@ -2134,9 +2008,9 @@ export default function SidebarV2() {
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{ id: "rename", label: "Rename task" },
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "delete", label: "Delete task", destructive: true, icon: "trash" },
|
||||
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
|
||||
],
|
||||
position,
|
||||
),
|
||||
@@ -2146,7 +2020,7 @@ export default function SidebarV2() {
|
||||
const preset = snoozePresets.find(
|
||||
(candidate) => `snooze:${candidate.id}` === clicked.value,
|
||||
);
|
||||
if (preset) attemptSnoozeTask(threadRef, preset);
|
||||
if (preset) attemptSnooze(threadRef, preset);
|
||||
return;
|
||||
}
|
||||
switch (clicked.value) {
|
||||
@@ -2174,53 +2048,43 @@ export default function SidebarV2() {
|
||||
return;
|
||||
}
|
||||
case "settle":
|
||||
attemptSettleTask(threadRef);
|
||||
attemptSettle(threadRef);
|
||||
return;
|
||||
case "unsettle":
|
||||
attemptUnsettleTask(threadRef);
|
||||
attemptUnsettle(threadRef);
|
||||
return;
|
||||
case "unsnooze":
|
||||
attemptUnsnoozeTask(threadRef);
|
||||
attemptUnsnooze(threadRef);
|
||||
return;
|
||||
case "rename":
|
||||
startThreadRename(threadRef, thread.title);
|
||||
return;
|
||||
case "mark-unread":
|
||||
for (const tab of taskTabs) {
|
||||
markThreadUnread(
|
||||
scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id)),
|
||||
tab.latestTurn?.completedAt,
|
||||
);
|
||||
}
|
||||
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
|
||||
return;
|
||||
case "delete": {
|
||||
if (confirmThreadDelete) {
|
||||
const confirmed = await settlePromise(() =>
|
||||
api.dialogs.confirm(
|
||||
[
|
||||
`Delete task "${thread.title}" and its ${taskTabs.length} tab${taskTabs.length === 1 ? "" : "s"}?`,
|
||||
"This permanently clears conversation history for every tab in the task.",
|
||||
`Delete thread "${thread.title}"?`,
|
||||
"This permanently clears conversation history for this thread.",
|
||||
].join("\n"),
|
||||
),
|
||||
);
|
||||
if (confirmed._tag === "Failure" || !confirmed.value) 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));
|
||||
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;
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -2230,17 +2094,16 @@ export default function SidebarV2() {
|
||||
})();
|
||||
},
|
||||
[
|
||||
attemptSettleTask,
|
||||
attemptSnoozeTask,
|
||||
attemptUnsettleTask,
|
||||
attemptUnsnoozeTask,
|
||||
attemptSettle,
|
||||
attemptSnooze,
|
||||
attemptUnsettle,
|
||||
attemptUnsnooze,
|
||||
confirmThreadDelete,
|
||||
deleteThread,
|
||||
handleMultiSelectContextMenu,
|
||||
markThreadUnread,
|
||||
serverConfigs,
|
||||
startThreadRename,
|
||||
taskTabsForRef,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2353,7 +2216,7 @@ export default function SidebarV2() {
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
type="button"
|
||||
aria-label="Search tasks and commands"
|
||||
aria-label="Search threads 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"
|
||||
/>
|
||||
@@ -2378,7 +2241,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 task"
|
||||
aria-label="New thread"
|
||||
/>
|
||||
}
|
||||
>
|
||||
@@ -2389,7 +2252,7 @@ export default function SidebarV2() {
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">
|
||||
{newThreadShortcutLabel ? `New task (${newThreadShortcutLabel})` : "New task"}
|
||||
{newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
@@ -2400,7 +2263,7 @@ export default function SidebarV2() {
|
||||
<div className="flex items-center gap-1">
|
||||
<Menu open={projectScopeMenuOpen} onOpenChange={setProjectScopeMenuOpen}>
|
||||
<MenuTrigger
|
||||
aria-label="Filter tasks by project"
|
||||
aria-label="Filter threads 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 ? (
|
||||
@@ -2549,8 +2412,7 @@ 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 })}
|
||||
tabCount={taskTabCountByKey.get(workspaceTaskKey(thread)) ?? 1}
|
||||
isActive={routeTaskKey === workspaceTaskKey(thread)}
|
||||
isActive={routeThreadKey === threadKey}
|
||||
jumpLabel={showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null}
|
||||
currentEnvironmentId={primaryEnvironmentId}
|
||||
environmentLabel={environmentLabelById.get(thread.environmentId) ?? null}
|
||||
@@ -2572,10 +2434,10 @@ export default function SidebarV2() {
|
||||
isRenaming={renamingThreadKey === threadKey}
|
||||
renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""}
|
||||
onContextMenu={handleThreadContextMenu}
|
||||
onSettle={attemptSettleTask}
|
||||
onUnsettle={attemptUnsettleTask}
|
||||
onSnooze={attemptSnoozeTask}
|
||||
onUnsnooze={attemptUnsnoozeTask}
|
||||
onSettle={attemptSettle}
|
||||
onUnsettle={attemptUnsettle}
|
||||
onSnooze={attemptSnooze}
|
||||
onUnsnooze={attemptUnsnooze}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
/>
|
||||
);
|
||||
@@ -2677,9 +2539,9 @@ export default function SidebarV2() {
|
||||
</button>
|
||||
</>
|
||||
) : scopedProjectGroup ? (
|
||||
`No tasks in ${scopedProjectGroup.displayName} yet`
|
||||
`No threads in ${scopedProjectGroup.displayName} yet`
|
||||
) : (
|
||||
"No tasks yet"
|
||||
"No threads yet"
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import type { VcsStatusResult } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
prStatusIndicator,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
} from "./ThreadStatusIndicators";
|
||||
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
|
||||
|
||||
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
|
||||
return {
|
||||
@@ -74,23 +70,4 @@ 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,17 +35,6 @@ 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,
|
||||
@@ -76,7 +65,7 @@ export function prStatusIndicator(
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: `${presentation.shortName} closed`,
|
||||
colorClass: "text-red-600 dark:text-red-300/90",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip,
|
||||
tooltipLead,
|
||||
tooltipTitle: pr.title,
|
||||
|
||||
@@ -1,289 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -434,7 +434,6 @@ 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-accent p-3">
|
||||
<div className="relative max-w-[80%] rounded-2xl bg-secondary 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]",
|
||||
"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))]",
|
||||
"data-highlighted:bg-muted/56 data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0",
|
||||
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-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
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"
|
||||
data-model-picker-content="true"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
@@ -568,23 +568,18 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
handleModelSelect(slug, instanceId);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
|
||||
showSidebar && "border-l",
|
||||
)}
|
||||
>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<div className="-translate-y-px rounded-lg bg-accent px-2 py-1">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
inputClassName="rounded-none bg-transparent text-sm"
|
||||
inputClassName="rounded-none bg-transparent text-sm placeholder:text-muted-foreground/80"
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/80" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
|
||||
@@ -97,10 +97,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
|
||||
data-model-picker-sidebar="true"
|
||||
>
|
||||
<div className="w-12 shrink-0 overflow-hidden bg-muted/60" 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}
|
||||
@@ -118,14 +115,14 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
) : null}
|
||||
{/* Favorites section */}
|
||||
{showFavorites ? (
|
||||
<div className="mb-1 border-b pb-1">
|
||||
<div className="mb-1 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-[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",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
)}
|
||||
onClick={() => handleSelect("favorites")}
|
||||
type="button"
|
||||
@@ -172,7 +169,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-[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",
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-muted",
|
||||
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 [-webkit-backdrop-filter:none]! [--viewport-inline-padding:0] [backdrop-filter:none]!"
|
||||
viewportClassName="rounded-lg !overflow-hidden p-0"
|
||||
className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
|
||||
viewportClassName="!overflow-hidden p-0"
|
||||
>
|
||||
<ModelPickerContent
|
||||
activeInstanceId={activeInstanceId}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
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 });
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon, ZapIcon } from "lucide-react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -379,46 +379,6 @@ 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,
|
||||
@@ -433,7 +393,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
...persistence
|
||||
}: TraitsMenuContentProps & TraitsPersistence) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled, fastModeEnabled } =
|
||||
const { descriptors, primarySelectDescriptor, ultrathinkPromptControlled } =
|
||||
getTraitsSectionVisibility({
|
||||
provider,
|
||||
models,
|
||||
@@ -455,18 +415,23 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
return null;
|
||||
}
|
||||
|
||||
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 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 isCodexStyle = provider === "codex";
|
||||
|
||||
@@ -492,14 +457,12 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
}
|
||||
>
|
||||
{isCodexStyle ? (
|
||||
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
|
||||
{fastModeIcon}
|
||||
<span className="min-w-0 truncate">{triggerLabel}</span>
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<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" />
|
||||
</>
|
||||
|
||||
@@ -7,7 +7,7 @@ function connection(
|
||||
phase: EnvironmentConnectionPresentation["phase"],
|
||||
error: string | null = null,
|
||||
): EnvironmentConnectionPresentation {
|
||||
return { phase, error, traceId: null };
|
||||
return { phase, error, reason: null, traceId: null, retryAt: null };
|
||||
}
|
||||
|
||||
describe("saved cloud environment connection presentation", () => {
|
||||
|
||||
@@ -62,7 +62,7 @@ export function BetaSettingsPanel() {
|
||||
<SettingsSection title="Beta features">
|
||||
<SettingsRow
|
||||
title="Sidebar v2"
|
||||
description="Treat sidebar items as tasks. Each task can hold multiple provider tabs that share one worktree; active work renders as rich cards and settled tasks collapse to compact rows. Switch back any time."
|
||||
description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time."
|
||||
control={
|
||||
<Switch
|
||||
checked={sidebarV2Enabled}
|
||||
|
||||
@@ -130,6 +130,7 @@ import {
|
||||
useEnvironments,
|
||||
usePrimaryEnvironment,
|
||||
} from "~/state/environments";
|
||||
import { isServerRestarting, useServerRestartExpected } from "~/serverRestartStore";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { ConnectionStatusDot } from "../ConnectionStatusDot";
|
||||
import { ServerUpdateAction } from "../ServerUpdateAction";
|
||||
@@ -1353,15 +1354,24 @@ function SavedBackendListRow({
|
||||
const connectionState = environment.connection.phase;
|
||||
const isConnected = connectionState === "connected";
|
||||
const isConnecting = connectionState === "connecting" || connectionState === "reconnecting";
|
||||
// An update started from this row restarts the server, so present that
|
||||
// disconnect as the expected restart rather than as a connection failure —
|
||||
// the same treatment the chat composer's skew banner gives it.
|
||||
const isRestarting = isServerRestarting({
|
||||
restartExpected: useServerRestartExpected(environmentId),
|
||||
environmentUnavailable: !isConnected,
|
||||
});
|
||||
const stateDotClassName =
|
||||
connectionState === "connected"
|
||||
? "bg-success"
|
||||
: connectionState === "connecting" || connectionState === "reconnecting"
|
||||
: isRestarting || connectionState === "connecting" || connectionState === "reconnecting"
|
||||
? "bg-warning"
|
||||
: connectionState === "error"
|
||||
? "bg-destructive"
|
||||
: "bg-muted-foreground/40";
|
||||
const statusTooltip = connectionStatusText(environment.connection);
|
||||
const statusTooltip = isRestarting
|
||||
? "Restarting to finish the server update..."
|
||||
: connectionStatusText(environment.connection);
|
||||
const errorTraceId = environment.connection.traceId;
|
||||
const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({
|
||||
target: "trace ID",
|
||||
@@ -1440,7 +1450,13 @@ function SavedBackendListRow({
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{environment.connection.error ? (
|
||||
{isRestarting ? (
|
||||
<p className="flex min-w-0 items-center gap-2 text-muted-foreground text-xs">
|
||||
<span className="truncate">
|
||||
Restarting to finish the server update — reconnecting automatically.
|
||||
</span>
|
||||
</p>
|
||||
) : environment.connection.error ? (
|
||||
<p className="flex min-w-0 items-center gap-2 text-destructive text-xs">
|
||||
<span className="truncate">{connectionStatusText(environment.connection)}</span>
|
||||
{errorTraceId ? (
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
WorkspaceTaskId,
|
||||
type ModelSelection,
|
||||
type ProviderOptionSelection,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -851,102 +850,6 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
expect(draftByKey(draftId)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("retains sibling task-tab drafts and their fork metadata when remapping the project", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
const workspaceTaskId = WorkspaceTaskId.make("task-a");
|
||||
store.setProjectDraftThreadId(projectRef, draftId, {
|
||||
threadId,
|
||||
workspaceTaskId,
|
||||
tabPosition: 0,
|
||||
retainPreviousDraft: true,
|
||||
});
|
||||
store.setPrompt(draftId, "main tab draft");
|
||||
|
||||
store.setProjectDraftThreadId(projectRef, otherDraftId, {
|
||||
threadId: otherThreadId,
|
||||
workspaceTaskId,
|
||||
tabPosition: 1,
|
||||
forkProvenance: {
|
||||
mode: "portable",
|
||||
sourceThreadId: threadId,
|
||||
createdAt: "2026-07-24T00:00:00.000Z",
|
||||
},
|
||||
retainPreviousDraft: true,
|
||||
});
|
||||
store.setPrompt(otherDraftId, "fork tab draft");
|
||||
|
||||
// Other call sites remap an already-existing draft without passing the
|
||||
// creation-only retention option. Task identity itself must keep the
|
||||
// sibling registered and preserve its unsent composer.
|
||||
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThread(draftId)).toMatchObject({
|
||||
threadId,
|
||||
workspaceTaskId,
|
||||
tabPosition: 0,
|
||||
});
|
||||
expect(draftByKey(draftId)?.prompt).toBe("main tab draft");
|
||||
expect(useComposerDraftStore.getState().getDraftThread(otherDraftId)).toMatchObject({
|
||||
threadId: otherThreadId,
|
||||
workspaceTaskId,
|
||||
tabPosition: 1,
|
||||
forkProvenance: {
|
||||
mode: "portable",
|
||||
sourceThreadId: threadId,
|
||||
},
|
||||
});
|
||||
expect(draftByKey(otherDraftId)?.prompt).toBe("fork tab draft");
|
||||
});
|
||||
|
||||
it("soft-closes and reopens draft tabs without losing composer state", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
const closedAt = "2026-07-27T12:00:00.000Z";
|
||||
store.setProjectDraftThreadId(projectRef, draftId, {
|
||||
threadId,
|
||||
workspaceTaskId: WorkspaceTaskId.make("task-a"),
|
||||
tabPosition: 1,
|
||||
});
|
||||
store.setPrompt(draftId, "keep this unsent");
|
||||
|
||||
store.setDraftThreadContext(draftId, { tabClosedAt: closedAt });
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThread(draftId)?.tabClosedAt).toBe(closedAt);
|
||||
expect(draftByKey(draftId)?.prompt).toBe("keep this unsent");
|
||||
|
||||
const persistApi = useComposerDraftStore.persist as unknown as {
|
||||
getOptions: () => {
|
||||
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
|
||||
};
|
||||
};
|
||||
const persistedState = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
|
||||
draftThreadsByThreadKey?: Record<string, { tabClosedAt?: string }>;
|
||||
};
|
||||
expect(persistedState.draftThreadsByThreadKey?.[draftId]?.tabClosedAt).toBe(closedAt);
|
||||
|
||||
store.setDraftThreadContext(draftId, { tabClosedAt: null });
|
||||
expect(useComposerDraftStore.getState().getDraftThread(draftId)?.tabClosedAt).toBeNull();
|
||||
expect(draftByKey(draftId)?.prompt).toBe("keep this unsent");
|
||||
});
|
||||
|
||||
it("retains a closed draft when its project mapping moves to another task", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectRef, draftId, {
|
||||
threadId,
|
||||
workspaceTaskId: WorkspaceTaskId.make("task-a"),
|
||||
tabPosition: 1,
|
||||
});
|
||||
store.setPrompt(draftId, "restore me later");
|
||||
store.setDraftThreadContext(draftId, { tabClosedAt: "2026-07-27T12:00:00.000Z" });
|
||||
|
||||
store.setProjectDraftThreadId(projectRef, otherDraftId, {
|
||||
threadId: otherThreadId,
|
||||
workspaceTaskId: WorkspaceTaskId.make("task-b"),
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThread(draftId)?.tabClosedAt).not.toBeNull();
|
||||
expect(draftByKey(draftId)?.prompt).toBe("restore me later");
|
||||
});
|
||||
|
||||
it("keeps composer drafts when the thread is still mapped by another project", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
|
||||
|
||||
@@ -15,9 +15,7 @@ import {
|
||||
type ServerProvider,
|
||||
type ScopedProjectRef,
|
||||
type ScopedThreadRef,
|
||||
ThreadForkProvenance,
|
||||
ThreadId,
|
||||
WorkspaceTaskId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
parseScopedProjectKey,
|
||||
@@ -57,7 +55,6 @@ import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewC
|
||||
const isRuntimeMode = Schema.is(RuntimeMode);
|
||||
const isProviderDriverKind = Schema.is(ProviderDriverKind);
|
||||
const isReviewCommentContext = Schema.is(ReviewCommentContextSchema);
|
||||
const isThreadForkProvenance = Schema.is(ThreadForkProvenance);
|
||||
|
||||
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
||||
const COMPOSER_DRAFT_STORAGE_VERSION = 8;
|
||||
@@ -209,11 +206,6 @@ type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState &
|
||||
|
||||
const PersistedDraftThreadState = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
workspaceTaskId: Schema.optionalKey(WorkspaceTaskId),
|
||||
tabLabel: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
tabPosition: Schema.optionalKey(Schema.Number),
|
||||
forkProvenance: Schema.optionalKey(Schema.NullOr(ThreadForkProvenance)),
|
||||
tabClosedAt: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
||||
environmentId: Schema.String,
|
||||
projectId: ProjectId,
|
||||
logicalProjectKey: Schema.optionalKey(Schema.String),
|
||||
@@ -293,11 +285,6 @@ export interface ComposerThreadDraftState {
|
||||
*/
|
||||
export interface DraftSessionState {
|
||||
threadId: ThreadId;
|
||||
workspaceTaskId?: WorkspaceTaskId | undefined;
|
||||
tabLabel?: string | null | undefined;
|
||||
tabPosition?: number | undefined;
|
||||
forkProvenance?: ThreadForkProvenance | null | undefined;
|
||||
tabClosedAt: string | null;
|
||||
environmentId: EnvironmentId;
|
||||
projectId: ProjectId;
|
||||
logicalProjectKey: string;
|
||||
@@ -372,12 +359,6 @@ interface ComposerDraftStoreState {
|
||||
startFromOrigin?: boolean;
|
||||
runtimeMode?: RuntimeMode;
|
||||
interactionMode?: ProviderInteractionMode;
|
||||
workspaceTaskId?: WorkspaceTaskId;
|
||||
tabLabel?: string | null;
|
||||
tabPosition?: number;
|
||||
forkProvenance?: ThreadForkProvenance | null;
|
||||
tabClosedAt?: string | null;
|
||||
retainPreviousDraft?: boolean;
|
||||
},
|
||||
) => void;
|
||||
/** Creates or updates the draft session tracked for a concrete project ref. */
|
||||
@@ -393,12 +374,6 @@ interface ComposerDraftStoreState {
|
||||
startFromOrigin?: boolean;
|
||||
runtimeMode?: RuntimeMode;
|
||||
interactionMode?: ProviderInteractionMode;
|
||||
workspaceTaskId?: WorkspaceTaskId;
|
||||
tabLabel?: string | null;
|
||||
tabPosition?: number;
|
||||
forkProvenance?: ThreadForkProvenance | null;
|
||||
tabClosedAt?: string | null;
|
||||
retainPreviousDraft?: boolean;
|
||||
},
|
||||
) => void;
|
||||
/** Updates mutable draft-session metadata without touching composer content. */
|
||||
@@ -413,7 +388,6 @@ interface ComposerDraftStoreState {
|
||||
startFromOrigin?: boolean;
|
||||
runtimeMode?: RuntimeMode;
|
||||
interactionMode?: ProviderInteractionMode;
|
||||
tabClosedAt?: string | null;
|
||||
},
|
||||
) => void;
|
||||
clearProjectDraftThreadId: (projectRef: ScopedProjectRef) => void;
|
||||
@@ -1357,12 +1331,6 @@ function createDraftThreadState(
|
||||
startFromOrigin?: boolean;
|
||||
runtimeMode?: RuntimeMode;
|
||||
interactionMode?: ProviderInteractionMode;
|
||||
workspaceTaskId?: WorkspaceTaskId;
|
||||
tabLabel?: string | null;
|
||||
tabPosition?: number;
|
||||
forkProvenance?: ThreadForkProvenance | null;
|
||||
tabClosedAt?: string | null;
|
||||
retainPreviousDraft?: boolean;
|
||||
},
|
||||
): DraftThreadState {
|
||||
const projectChanged =
|
||||
@@ -1389,14 +1357,6 @@ function createDraftThreadState(
|
||||
: options.startFromOrigin;
|
||||
return {
|
||||
threadId,
|
||||
workspaceTaskId: options?.workspaceTaskId ?? existingThread?.workspaceTaskId,
|
||||
tabLabel: options?.tabLabel ?? existingThread?.tabLabel ?? null,
|
||||
tabPosition: options?.tabPosition ?? existingThread?.tabPosition ?? 0,
|
||||
forkProvenance: options?.forkProvenance ?? existingThread?.forkProvenance ?? null,
|
||||
tabClosedAt:
|
||||
options?.tabClosedAt === undefined
|
||||
? (existingThread?.tabClosedAt ?? null)
|
||||
: options.tabClosedAt,
|
||||
environmentId: projectRef.environmentId,
|
||||
projectId: projectRef.projectId,
|
||||
logicalProjectKey,
|
||||
@@ -1436,11 +1396,6 @@ function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThrea
|
||||
return (
|
||||
!!left &&
|
||||
left.threadId === right.threadId &&
|
||||
left.workspaceTaskId === right.workspaceTaskId &&
|
||||
left.tabLabel === right.tabLabel &&
|
||||
left.tabPosition === right.tabPosition &&
|
||||
Equal.equals(left.forkProvenance, right.forkProvenance) &&
|
||||
left.tabClosedAt === right.tabClosedAt &&
|
||||
left.environmentId === right.environmentId &&
|
||||
left.projectId === right.projectId &&
|
||||
left.logicalProjectKey === right.logicalProjectKey &&
|
||||
@@ -1569,26 +1524,6 @@ function normalizePersistedDraftThreads(
|
||||
const normalizedEnvironmentId = environmentId as EnvironmentId;
|
||||
draftThreadsByThreadKey[threadKey] = {
|
||||
threadId,
|
||||
...(typeof candidateDraftThread.workspaceTaskId === "string" &&
|
||||
candidateDraftThread.workspaceTaskId.length > 0
|
||||
? {
|
||||
workspaceTaskId: WorkspaceTaskId.make(candidateDraftThread.workspaceTaskId),
|
||||
}
|
||||
: {}),
|
||||
...(typeof candidateDraftThread.tabLabel === "string"
|
||||
? { tabLabel: candidateDraftThread.tabLabel }
|
||||
: {}),
|
||||
...(typeof candidateDraftThread.tabPosition === "number" &&
|
||||
Number.isInteger(candidateDraftThread.tabPosition) &&
|
||||
candidateDraftThread.tabPosition >= 0
|
||||
? { tabPosition: candidateDraftThread.tabPosition }
|
||||
: {}),
|
||||
...(isThreadForkProvenance(candidateDraftThread.forkProvenance)
|
||||
? { forkProvenance: candidateDraftThread.forkProvenance }
|
||||
: {}),
|
||||
...(typeof candidateDraftThread.tabClosedAt === "string"
|
||||
? { tabClosedAt: candidateDraftThread.tabClosedAt }
|
||||
: {}),
|
||||
environmentId: normalizedEnvironmentId,
|
||||
projectId: projectId as ProjectId,
|
||||
logicalProjectKey:
|
||||
@@ -1660,7 +1595,6 @@ function normalizePersistedDraftThreads(
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
startFromOrigin: false,
|
||||
tabClosedAt: null,
|
||||
promotedTo: null,
|
||||
};
|
||||
} else if (
|
||||
@@ -1973,33 +1907,9 @@ function partializeComposerDraftStoreState(
|
||||
};
|
||||
persistedDraftsByThreadKey[threadKey] = persistedDraft;
|
||||
}
|
||||
const persistedDraftThreadsByThreadKey = Object.fromEntries(
|
||||
Object.entries(state.draftThreadsByThreadKey).map(([draftId, draft]) => [
|
||||
draftId,
|
||||
{
|
||||
threadId: draft.threadId,
|
||||
...(draft.workspaceTaskId !== undefined ? { workspaceTaskId: draft.workspaceTaskId } : {}),
|
||||
...(draft.tabLabel !== undefined ? { tabLabel: draft.tabLabel } : {}),
|
||||
...(draft.tabPosition !== undefined ? { tabPosition: draft.tabPosition } : {}),
|
||||
...(draft.forkProvenance !== undefined ? { forkProvenance: draft.forkProvenance } : {}),
|
||||
...(draft.tabClosedAt !== null ? { tabClosedAt: draft.tabClosedAt } : {}),
|
||||
environmentId: draft.environmentId,
|
||||
projectId: draft.projectId,
|
||||
logicalProjectKey: draft.logicalProjectKey,
|
||||
createdAt: draft.createdAt,
|
||||
runtimeMode: draft.runtimeMode,
|
||||
interactionMode: draft.interactionMode,
|
||||
branch: draft.branch,
|
||||
worktreePath: draft.worktreePath,
|
||||
envMode: draft.envMode,
|
||||
startFromOrigin: draft.startFromOrigin,
|
||||
...(draft.promotedTo !== undefined ? { promotedTo: draft.promotedTo } : {}),
|
||||
},
|
||||
]),
|
||||
) as PersistedComposerDraftStoreState["draftThreadsByThreadKey"];
|
||||
return {
|
||||
draftsByThreadKey: persistedDraftsByThreadKey,
|
||||
draftThreadsByThreadKey: persistedDraftThreadsByThreadKey,
|
||||
draftThreadsByThreadKey: state.draftThreadsByThreadKey,
|
||||
logicalProjectDraftThreadKeyByLogicalProjectKey:
|
||||
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
||||
stickyModelSelectionByProvider: compactModelSelectionByProvider(
|
||||
@@ -2239,11 +2149,6 @@ function toHydratedDraftThreadState(
|
||||
): DraftThreadState {
|
||||
return {
|
||||
threadId: persistedDraftThread.threadId,
|
||||
workspaceTaskId: persistedDraftThread.workspaceTaskId,
|
||||
tabLabel: persistedDraftThread.tabLabel ?? null,
|
||||
tabPosition: persistedDraftThread.tabPosition ?? 0,
|
||||
forkProvenance: persistedDraftThread.forkProvenance ?? null,
|
||||
tabClosedAt: persistedDraftThread.tabClosedAt ?? null,
|
||||
environmentId: persistedDraftThread.environmentId as EnvironmentId,
|
||||
projectId: persistedDraftThread.projectId,
|
||||
logicalProjectKey:
|
||||
@@ -2380,17 +2285,9 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
previousThreadKeyForLogicalProject === undefined
|
||||
? undefined
|
||||
: nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
|
||||
const sharesWorkspaceTask =
|
||||
previousDraftThread?.workspaceTaskId !== undefined &&
|
||||
nextDraftThread.workspaceTaskId !== undefined &&
|
||||
previousDraftThread.workspaceTaskId === nextDraftThread.workspaceTaskId;
|
||||
const previousDraftIsClosed = previousDraftThread?.tabClosedAt != null;
|
||||
if (
|
||||
previousThreadKeyForLogicalProject &&
|
||||
previousThreadKeyForLogicalProject !== draftId &&
|
||||
options?.retainPreviousDraft !== true &&
|
||||
!sharesWorkspaceTask &&
|
||||
!previousDraftIsClosed &&
|
||||
!isComposerThreadKeyInUse(
|
||||
nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
|
||||
previousThreadKeyForLogicalProject,
|
||||
@@ -2462,12 +2359,6 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
: options.startFromOrigin;
|
||||
const nextDraftThread: DraftThreadState = {
|
||||
threadId: existing.threadId,
|
||||
workspaceTaskId: existing.workspaceTaskId,
|
||||
tabLabel: existing.tabLabel,
|
||||
tabPosition: existing.tabPosition,
|
||||
forkProvenance: existing.forkProvenance,
|
||||
tabClosedAt:
|
||||
options.tabClosedAt === undefined ? existing.tabClosedAt : options.tabClosedAt,
|
||||
environmentId: nextProjectRef.environmentId,
|
||||
projectId: nextProjectRef.projectId,
|
||||
logicalProjectKey: existing.logicalProjectKey,
|
||||
@@ -2496,7 +2387,6 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
nextDraftThread.createdAt === existing.createdAt &&
|
||||
nextDraftThread.runtimeMode === existing.runtimeMode &&
|
||||
nextDraftThread.interactionMode === existing.interactionMode &&
|
||||
nextDraftThread.tabClosedAt === existing.tabClosedAt &&
|
||||
nextDraftThread.branch === existing.branch &&
|
||||
nextDraftThread.worktreePath === existing.worktreePath &&
|
||||
nextDraftThread.envMode === existing.envMode &&
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
scopeProjectRef,
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef, WorkspaceTaskId } from "@t3tools/contracts";
|
||||
import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@t3tools/contracts";
|
||||
import { useParams, useRouter } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import {
|
||||
@@ -249,7 +249,6 @@ export function useNewThreadHandler() {
|
||||
return (async () => {
|
||||
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
|
||||
threadId,
|
||||
workspaceTaskId: WorkspaceTaskId.make(String(threadId)),
|
||||
createdAt,
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
|
||||
@@ -1,465 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
scopedProjectKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
type ModelSelection,
|
||||
type ScopedThreadRef,
|
||||
type ThreadForkProvenance,
|
||||
ThreadId,
|
||||
ProviderInstanceId,
|
||||
WorkspaceTaskId,
|
||||
} from "@t3tools/contracts";
|
||||
import { useParams, useRouter } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
|
||||
import { DraftId, type DraftSessionState, useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import { refreshClosedTaskTabsForEnvironment, useClosedTaskTabs } from "../lib/closedTaskTabsState";
|
||||
import { newDraftId, newThreadId } from "../lib/utils";
|
||||
import { resolveWorkspaceTaskId } from "../lib/workspaceTasks";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { readThreadShell, useProjects, useServerConfigs, useThreadShells } from "../state/entities";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import { useClientSettings } from "./useSettings";
|
||||
|
||||
export type WorkspaceTaskTab =
|
||||
| {
|
||||
readonly kind: "server";
|
||||
readonly key: string;
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly title: string;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly position: number;
|
||||
readonly active: boolean;
|
||||
readonly working: boolean;
|
||||
readonly blocked: boolean;
|
||||
readonly forkProvenance: ThreadForkProvenance | null;
|
||||
}
|
||||
| {
|
||||
readonly kind: "draft";
|
||||
readonly key: string;
|
||||
readonly draftId: DraftId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly title: string;
|
||||
readonly modelSelection: ModelSelection | null;
|
||||
readonly position: number;
|
||||
readonly active: boolean;
|
||||
readonly working: false;
|
||||
readonly blocked: false;
|
||||
readonly forkProvenance: ThreadForkProvenance | null;
|
||||
};
|
||||
|
||||
export type ClosedWorkspaceTaskTab =
|
||||
| {
|
||||
readonly kind: "server";
|
||||
readonly key: string;
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly title: string;
|
||||
readonly position: number;
|
||||
readonly forkProvenance: ThreadForkProvenance | null;
|
||||
readonly closedAt: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "draft";
|
||||
readonly key: string;
|
||||
readonly draftId: DraftId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly title: string;
|
||||
readonly position: number;
|
||||
readonly forkProvenance: ThreadForkProvenance | null;
|
||||
readonly closedAt: string;
|
||||
};
|
||||
|
||||
interface CurrentTaskContext {
|
||||
readonly environmentId: EnvironmentThreadShell["environmentId"];
|
||||
readonly projectId: EnvironmentThreadShell["projectId"];
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceTaskId: WorkspaceTaskId;
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
readonly runtimeMode: EnvironmentThreadShell["runtimeMode"];
|
||||
readonly interactionMode: EnvironmentThreadShell["interactionMode"];
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly logicalProjectKey: string;
|
||||
readonly sourceIsServer: boolean;
|
||||
}
|
||||
|
||||
function draftTaskId(draft: DraftSessionState): WorkspaceTaskId {
|
||||
return draft.workspaceTaskId ?? WorkspaceTaskId.make(String(draft.threadId));
|
||||
}
|
||||
|
||||
async function waitForThreadShellState(
|
||||
threadRef: ScopedThreadRef,
|
||||
expectedToExist: boolean,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + 3_000;
|
||||
while ((readThreadShell(threadRef) !== null) !== expectedToExist && Date.now() < deadline) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
}
|
||||
|
||||
export function useWorkspaceTaskTabs() {
|
||||
const router = useRouter();
|
||||
const creatingTabRef = useRef(false);
|
||||
const routeTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const threads = useThreadShells();
|
||||
const projects = useProjects();
|
||||
const serverConfigs = useServerConfigs();
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const draftSessions = useComposerDraftStore((state) => state.draftThreadsByThreadKey);
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
|
||||
const currentServerThread =
|
||||
routeTarget?.kind === "server"
|
||||
? (threads.find(
|
||||
(thread) =>
|
||||
thread.environmentId === routeTarget.threadRef.environmentId &&
|
||||
thread.id === routeTarget.threadRef.threadId,
|
||||
) ?? null)
|
||||
: null;
|
||||
const currentDraft =
|
||||
routeTarget?.kind === "draft" ? (draftSessions[routeTarget.draftId] ?? null) : null;
|
||||
const currentProject = currentServerThread
|
||||
? (projects.find(
|
||||
(project) =>
|
||||
project.environmentId === currentServerThread.environmentId &&
|
||||
project.id === currentServerThread.projectId,
|
||||
) ?? null)
|
||||
: currentDraft
|
||||
? (projects.find(
|
||||
(project) =>
|
||||
project.environmentId === currentDraft.environmentId &&
|
||||
project.id === currentDraft.projectId,
|
||||
) ?? null)
|
||||
: null;
|
||||
|
||||
const currentContext: CurrentTaskContext | null = currentServerThread
|
||||
? {
|
||||
environmentId: currentServerThread.environmentId,
|
||||
projectId: currentServerThread.projectId,
|
||||
threadId: currentServerThread.id,
|
||||
workspaceTaskId: resolveWorkspaceTaskId(currentServerThread),
|
||||
branch: currentServerThread.branch,
|
||||
worktreePath: currentServerThread.worktreePath,
|
||||
runtimeMode: currentServerThread.runtimeMode,
|
||||
interactionMode: currentServerThread.interactionMode,
|
||||
modelSelection: currentServerThread.modelSelection,
|
||||
logicalProjectKey: currentProject
|
||||
? deriveLogicalProjectKeyFromSettings(currentProject, projectGroupingSettings)
|
||||
: scopedProjectKey(
|
||||
scopeProjectRef(currentServerThread.environmentId, currentServerThread.projectId),
|
||||
),
|
||||
sourceIsServer: true,
|
||||
}
|
||||
: currentDraft && currentProject
|
||||
? {
|
||||
environmentId: currentDraft.environmentId,
|
||||
projectId: currentDraft.projectId,
|
||||
threadId: currentDraft.threadId,
|
||||
workspaceTaskId: draftTaskId(currentDraft),
|
||||
branch: currentDraft.branch,
|
||||
worktreePath: currentDraft.worktreePath,
|
||||
runtimeMode: currentDraft.runtimeMode,
|
||||
interactionMode: currentDraft.interactionMode,
|
||||
modelSelection: currentProject.defaultModelSelection ?? {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "default",
|
||||
},
|
||||
logicalProjectKey: currentDraft.logicalProjectKey,
|
||||
sourceIsServer: false,
|
||||
}
|
||||
: null;
|
||||
const supportsTaskTabs =
|
||||
currentContext !== null &&
|
||||
serverConfigs.get(currentContext.environmentId)?.environment.capabilities.workspaceTaskTabs ===
|
||||
true;
|
||||
const closedServerTaskTabs = useClosedTaskTabs(
|
||||
supportsTaskTabs ? currentContext.environmentId : null,
|
||||
);
|
||||
|
||||
const tabs = useMemo<ReadonlyArray<WorkspaceTaskTab>>(() => {
|
||||
if (currentContext === null) return [];
|
||||
const serverTabs: WorkspaceTaskTab[] = threads.flatMap((thread) => {
|
||||
if (
|
||||
thread.environmentId !== currentContext.environmentId ||
|
||||
resolveWorkspaceTaskId(thread) !== currentContext.workspaceTaskId ||
|
||||
thread.tabClosedAt != null
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
|
||||
return [
|
||||
{
|
||||
kind: "server",
|
||||
key: scopedThreadKey(threadRef),
|
||||
threadRef,
|
||||
title: thread.tabLabel ?? (thread.tabPosition === 0 ? "Main" : thread.title),
|
||||
modelSelection: thread.modelSelection,
|
||||
position: thread.tabPosition ?? 0,
|
||||
active:
|
||||
routeTarget?.kind === "server" &&
|
||||
routeTarget.threadRef.environmentId === thread.environmentId &&
|
||||
routeTarget.threadRef.threadId === thread.id,
|
||||
working: thread.session?.status === "running" || thread.session?.status === "starting",
|
||||
blocked: thread.hasPendingApprovals || thread.hasPendingUserInput,
|
||||
forkProvenance: thread.forkProvenance ?? null,
|
||||
},
|
||||
];
|
||||
});
|
||||
const draftTabs: WorkspaceTaskTab[] = Object.entries(draftSessions).flatMap(
|
||||
([rawDraftId, draft]) => {
|
||||
if (
|
||||
draft.environmentId !== currentContext.environmentId ||
|
||||
draftTaskId(draft) !== currentContext.workspaceTaskId ||
|
||||
draft.tabClosedAt != null ||
|
||||
draft.promotedTo != null
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const draftId = DraftId.make(rawDraftId);
|
||||
const composer = useComposerDraftStore.getState().getComposerDraft(draftId);
|
||||
const activeProvider = composer?.activeProvider ?? null;
|
||||
const modelSelection = activeProvider
|
||||
? (composer?.modelSelectionByProvider[activeProvider] ?? null)
|
||||
: null;
|
||||
return [
|
||||
{
|
||||
kind: "draft",
|
||||
key: `draft:${draftId}`,
|
||||
draftId,
|
||||
threadId: draft.threadId,
|
||||
title: draft.tabLabel ?? `Tab ${(draft.tabPosition ?? 0) + 1}`,
|
||||
modelSelection,
|
||||
position: draft.tabPosition ?? 0,
|
||||
active: routeTarget?.kind === "draft" && routeTarget.draftId === draftId,
|
||||
working: false,
|
||||
blocked: false,
|
||||
forkProvenance: draft.forkProvenance ?? null,
|
||||
},
|
||||
];
|
||||
},
|
||||
);
|
||||
return [...serverTabs, ...draftTabs].toSorted(
|
||||
(left, right) => left.position - right.position || left.key.localeCompare(right.key),
|
||||
);
|
||||
}, [currentContext, draftSessions, routeTarget, threads]);
|
||||
|
||||
const closedTabs = useMemo<ReadonlyArray<ClosedWorkspaceTaskTab>>(() => {
|
||||
if (currentContext === null) return [];
|
||||
const serverTabs: ClosedWorkspaceTaskTab[] = closedServerTaskTabs.flatMap((thread) => {
|
||||
if (
|
||||
resolveWorkspaceTaskId(thread) !== currentContext.workspaceTaskId ||
|
||||
thread.tabClosedAt == null
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const threadRef = scopeThreadRef(currentContext.environmentId, thread.id);
|
||||
return [
|
||||
{
|
||||
kind: "server",
|
||||
key: scopedThreadKey(threadRef),
|
||||
threadRef,
|
||||
title: thread.tabLabel ?? (thread.tabPosition === 0 ? "Main" : thread.title),
|
||||
position: thread.tabPosition ?? 0,
|
||||
forkProvenance: thread.forkProvenance ?? null,
|
||||
closedAt: thread.tabClosedAt,
|
||||
},
|
||||
];
|
||||
});
|
||||
const draftTabs: ClosedWorkspaceTaskTab[] = Object.entries(draftSessions).flatMap(
|
||||
([rawDraftId, draft]) => {
|
||||
if (
|
||||
draft.environmentId !== currentContext.environmentId ||
|
||||
draftTaskId(draft) !== currentContext.workspaceTaskId ||
|
||||
draft.tabClosedAt == null ||
|
||||
draft.promotedTo != null
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const draftId = DraftId.make(rawDraftId);
|
||||
return [
|
||||
{
|
||||
kind: "draft",
|
||||
key: `draft:${draftId}`,
|
||||
draftId,
|
||||
threadId: draft.threadId,
|
||||
title: draft.tabLabel ?? `Tab ${(draft.tabPosition ?? 0) + 1}`,
|
||||
position: draft.tabPosition ?? 0,
|
||||
forkProvenance: draft.forkProvenance ?? null,
|
||||
closedAt: draft.tabClosedAt,
|
||||
},
|
||||
];
|
||||
},
|
||||
);
|
||||
return [...serverTabs, ...draftTabs].toSorted(
|
||||
(left, right) =>
|
||||
right.closedAt.localeCompare(left.closedAt) ||
|
||||
left.position - right.position ||
|
||||
left.key.localeCompare(right.key),
|
||||
);
|
||||
}, [closedServerTaskTabs, currentContext, draftSessions]);
|
||||
|
||||
const navigateToTab = useCallback(
|
||||
(tab: WorkspaceTaskTab | ClosedWorkspaceTaskTab) => {
|
||||
if (tab.kind === "server") {
|
||||
return router.navigate({
|
||||
to: "/$environmentId/$threadId",
|
||||
params: buildThreadRouteParams(tab.threadRef),
|
||||
});
|
||||
}
|
||||
return router.navigate({
|
||||
to: "/draft/$draftId",
|
||||
params: { draftId: tab.draftId },
|
||||
});
|
||||
},
|
||||
[router],
|
||||
);
|
||||
|
||||
const createTab = useCallback(
|
||||
async (mode: "fresh" | "portable" = "fresh") => {
|
||||
if (currentContext === null || !supportsTaskTabs) return;
|
||||
if (mode === "portable" && !currentContext.sourceIsServer) return;
|
||||
if (creatingTabRef.current) return;
|
||||
creatingTabRef.current = true;
|
||||
|
||||
try {
|
||||
const draftId = newDraftId();
|
||||
const threadId = newThreadId();
|
||||
const createdAt = new Date().toISOString();
|
||||
const position =
|
||||
[...tabs, ...closedTabs].reduce((max, tab) => Math.max(max, tab.position), -1) + 1;
|
||||
const forkProvenance: ThreadForkProvenance = {
|
||||
mode,
|
||||
sourceThreadId: mode === "portable" ? currentContext.threadId : null,
|
||||
createdAt,
|
||||
};
|
||||
const store = useComposerDraftStore.getState();
|
||||
const currentComposer =
|
||||
routeTarget?.kind === "server"
|
||||
? store.getComposerDraft(routeTarget.threadRef)
|
||||
: routeTarget?.kind === "draft"
|
||||
? store.getComposerDraft(routeTarget.draftId)
|
||||
: null;
|
||||
const activeProvider = currentComposer?.activeProvider ?? null;
|
||||
const carriedModelSelection =
|
||||
(activeProvider
|
||||
? currentComposer?.modelSelectionByProvider[activeProvider]
|
||||
: undefined) ?? currentContext.modelSelection;
|
||||
|
||||
store.setLogicalProjectDraftThreadId(
|
||||
currentContext.logicalProjectKey,
|
||||
scopeProjectRef(currentContext.environmentId, currentContext.projectId),
|
||||
draftId,
|
||||
{
|
||||
threadId,
|
||||
workspaceTaskId: currentContext.workspaceTaskId,
|
||||
tabPosition: position,
|
||||
tabLabel: null,
|
||||
forkProvenance,
|
||||
createdAt,
|
||||
branch: currentContext.branch,
|
||||
worktreePath: currentContext.worktreePath,
|
||||
envMode: currentContext.worktreePath ? "worktree" : "local",
|
||||
startFromOrigin: false,
|
||||
runtimeMode: currentContext.runtimeMode,
|
||||
interactionMode: currentContext.interactionMode,
|
||||
retainPreviousDraft: true,
|
||||
},
|
||||
);
|
||||
store.applyStickyState(draftId);
|
||||
store.setModelSelection(draftId, carriedModelSelection, { replaceOptions: true });
|
||||
|
||||
await router.navigate({
|
||||
to: "/draft/$draftId",
|
||||
params: { draftId },
|
||||
});
|
||||
} finally {
|
||||
creatingTabRef.current = false;
|
||||
}
|
||||
},
|
||||
[closedTabs, currentContext, routeTarget, router, supportsTaskTabs, tabs],
|
||||
);
|
||||
|
||||
const closeTab = useCallback(
|
||||
async (tab: WorkspaceTaskTab) => {
|
||||
if (tabs.length <= 1 || tab.working || tab.blocked) return;
|
||||
const index = tabs.findIndex((candidate) => candidate.key === tab.key);
|
||||
const fallback = tabs[index + 1] ?? tabs[index - 1] ?? null;
|
||||
if (tab.kind === "draft") {
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.setDraftThreadContext(tab.draftId, { tabClosedAt: new Date().toISOString() });
|
||||
} else {
|
||||
const result = await updateThreadMetadata({
|
||||
environmentId: tab.threadRef.environmentId,
|
||||
input: {
|
||||
threadId: tab.threadRef.threadId,
|
||||
tabClosedAt: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") return;
|
||||
await waitForThreadShellState(tab.threadRef, false);
|
||||
refreshClosedTaskTabsForEnvironment(tab.threadRef.environmentId);
|
||||
}
|
||||
if (tab.active && fallback) {
|
||||
await navigateToTab(fallback);
|
||||
}
|
||||
},
|
||||
[navigateToTab, tabs, updateThreadMetadata],
|
||||
);
|
||||
|
||||
const reopenTab = useCallback(
|
||||
async (tab: ClosedWorkspaceTaskTab) => {
|
||||
if (tab.kind === "draft") {
|
||||
useComposerDraftStore.getState().setDraftThreadContext(tab.draftId, { tabClosedAt: null });
|
||||
} else {
|
||||
const result = await updateThreadMetadata({
|
||||
environmentId: tab.threadRef.environmentId,
|
||||
input: {
|
||||
threadId: tab.threadRef.threadId,
|
||||
tabClosedAt: null,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") return;
|
||||
await waitForThreadShellState(tab.threadRef, true);
|
||||
refreshClosedTaskTabsForEnvironment(tab.threadRef.environmentId);
|
||||
}
|
||||
await navigateToTab(tab);
|
||||
},
|
||||
[navigateToTab, updateThreadMetadata],
|
||||
);
|
||||
|
||||
const reopenLastClosedTab = useCallback(async () => {
|
||||
const lastClosed = closedTabs[0];
|
||||
if (lastClosed) await reopenTab(lastClosed);
|
||||
}, [closedTabs, reopenTab]);
|
||||
|
||||
return {
|
||||
tabs,
|
||||
closedTabs,
|
||||
keybindings,
|
||||
hasTask: currentContext !== null && supportsTaskTabs,
|
||||
canForkContext: currentContext?.sourceIsServer === true && supportsTaskTabs,
|
||||
createTab,
|
||||
closeTab,
|
||||
reopenTab,
|
||||
reopenLastClosedTab,
|
||||
navigateToTab,
|
||||
} as const;
|
||||
}
|
||||
+2
-18
@@ -574,6 +574,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
--alert-glass-tint: var(--warning);
|
||||
}
|
||||
|
||||
.dropdown-glass,
|
||||
.dialog-glass {
|
||||
background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
|
||||
@@ -587,19 +588,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dropdown-glass {
|
||||
/*
|
||||
* Elevated glass needs a denser tint than broad ambient surfaces. Nesting
|
||||
* the user-controlled mix inside an 18% popover tint preserves the full
|
||||
* opacity setting range (40% -> 51%, 80% -> 84%, 100% -> 100%) while
|
||||
* keeping high-contrast page content from blooming through menus.
|
||||
*/
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur));
|
||||
backdrop-filter: blur(var(--glass-blur));
|
||||
border: 1px solid color-mix(in srgb, var(--foreground) 10%, transparent);
|
||||
box-shadow: 0 16px 40px -18px rgb(0 0 0 / 55%);
|
||||
}
|
||||
@@ -614,11 +602,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
|
||||
}
|
||||
|
||||
.dark .model-picker-surface.model-picker-surface {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--popover) 18%,
|
||||
color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)
|
||||
);
|
||||
background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);
|
||||
}
|
||||
|
||||
.dark .dialog-glass {
|
||||
|
||||
@@ -124,7 +124,6 @@ const DEFAULT_BINDINGS = compile([
|
||||
whenAst: whenNot(whenIdentifier("terminalFocus")),
|
||||
},
|
||||
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
|
||||
{ shortcut: modShortcut("t", { shiftKey: true }), command: "chat.reopenClosedTab" },
|
||||
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
|
||||
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
||||
{ shortcut: modShortcut("[", { shiftKey: true }), command: "thread.previous" },
|
||||
@@ -319,10 +318,6 @@ describe("shortcutLabelForCommand", () => {
|
||||
"⌘B",
|
||||
);
|
||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.reopenClosedTab", "MacIntel"),
|
||||
"⇧⌘T",
|
||||
);
|
||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(DEFAULT_BINDINGS, "rightPanel.toggle", "MacIntel"),
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
import { orchestrationEnvironment } from "../state/orchestration";
|
||||
|
||||
const EMPTY_CLOSED_TASK_TABS: ReadonlyArray<OrchestrationThreadShell> = Object.freeze([]);
|
||||
const EMPTY_CLOSED_TASK_TABS_ATOM = Atom.make(AsyncResult.success(EMPTY_CLOSED_TASK_TABS)).pipe(
|
||||
Atom.withLabel("web:closed-task-tabs:empty"),
|
||||
);
|
||||
|
||||
function closedTaskTabsAtom(environmentId: EnvironmentId) {
|
||||
return orchestrationEnvironment.closedTaskTabs({
|
||||
environmentId,
|
||||
input: {},
|
||||
});
|
||||
}
|
||||
|
||||
export function refreshClosedTaskTabsForEnvironment(environmentId: EnvironmentId): void {
|
||||
appAtomRegistry.refresh(closedTaskTabsAtom(environmentId));
|
||||
}
|
||||
|
||||
export function useClosedTaskTabs(
|
||||
environmentId: EnvironmentId | null,
|
||||
): ReadonlyArray<OrchestrationThreadShell> {
|
||||
const result = useAtomValue(
|
||||
environmentId === null ? EMPTY_CLOSED_TASK_TABS_ATOM : closedTaskTabsAtom(environmentId),
|
||||
);
|
||||
return Option.getOrElse(AsyncResult.value(result), () => EMPTY_CLOSED_TASK_TABS);
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "./diffCollapse";
|
||||
|
||||
const FILE_KEYS = ["src/app.ts", "src/index.ts"];
|
||||
const FIRST_FILE_KEY = FILE_KEYS[0]!;
|
||||
|
||||
describe("diff collapse controls", () => {
|
||||
it("reports whether every rendered file is collapsed", () => {
|
||||
expect(areAllDiffFilesCollapsed(FILE_KEYS, new Set(FILE_KEYS))).toBe(true);
|
||||
expect(areAllDiffFilesCollapsed(FILE_KEYS, new Set([FIRST_FILE_KEY]))).toBe(false);
|
||||
expect(areAllDiffFilesCollapsed([], new Set())).toBe(false);
|
||||
});
|
||||
|
||||
it("collapses all files when any rendered file is expanded", () => {
|
||||
expect(toggleAllDiffFiles(FILE_KEYS, new Set([FIRST_FILE_KEY]))).toEqual(new Set(FILE_KEYS));
|
||||
});
|
||||
|
||||
it("expands all files when every rendered file is collapsed", () => {
|
||||
expect(toggleAllDiffFiles(FILE_KEYS, new Set(FILE_KEYS))).toEqual(new Set());
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
export function areAllDiffFilesCollapsed(
|
||||
fileKeys: ReadonlyArray<string>,
|
||||
collapsedFileKeys: ReadonlySet<string>,
|
||||
): boolean {
|
||||
return fileKeys.length > 0 && fileKeys.every((fileKey) => collapsedFileKeys.has(fileKey));
|
||||
}
|
||||
|
||||
export function toggleAllDiffFiles(
|
||||
fileKeys: ReadonlyArray<string>,
|
||||
collapsedFileKeys: ReadonlySet<string>,
|
||||
): ReadonlySet<string> {
|
||||
return areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? new Set() : new Set(fileKeys);
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
describeTaskTabContexts,
|
||||
taskTabDisplayTitle,
|
||||
type TaskTabContextSource,
|
||||
} from "./taskTabContext";
|
||||
|
||||
function tab(
|
||||
overrides: Partial<TaskTabContextSource> & { threadId: string },
|
||||
): TaskTabContextSource {
|
||||
return {
|
||||
kind: "server",
|
||||
title: overrides.threadId,
|
||||
position: 0,
|
||||
forkProvenance: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("task tab context descriptors", () => {
|
||||
it("labels the first tab Main and gives it its own context", () => {
|
||||
const [main] = describeTaskTabContexts([tab({ threadId: "root", title: "Tab 1" })]);
|
||||
expect(main?.title).toBe("Main");
|
||||
expect(main?.kind).toBe("main");
|
||||
expect(main?.label).toBe("Independent");
|
||||
expect(main?.detail).toBe("Separate chat history.");
|
||||
});
|
||||
|
||||
it("keeps an explicit tab label on the first tab", () => {
|
||||
expect(taskTabDisplayTitle(tab({ threadId: "root", title: "Reviewer" }))).toBe("Reviewer");
|
||||
});
|
||||
|
||||
it("describes an unsent draft tab as starting empty", () => {
|
||||
const [, draft] = describeTaskTabContexts([
|
||||
tab({ threadId: "root", title: "Main" }),
|
||||
tab({
|
||||
threadId: "draft-thread",
|
||||
kind: "draft",
|
||||
title: "Tab 2",
|
||||
position: 1,
|
||||
forkProvenance: { mode: "fresh", sourceThreadId: null },
|
||||
}),
|
||||
]);
|
||||
expect(draft?.kind).toBe("empty");
|
||||
expect(draft?.label).toBe("Empty");
|
||||
expect(draft?.detail).toBe("No chat history.");
|
||||
});
|
||||
|
||||
it("describes a started sibling tab as independent, not shared", () => {
|
||||
const [, started] = describeTaskTabContexts([
|
||||
tab({ threadId: "root", title: "Main" }),
|
||||
tab({
|
||||
threadId: "second",
|
||||
title: "Tab 2",
|
||||
position: 1,
|
||||
forkProvenance: { mode: "fresh", sourceThreadId: null },
|
||||
}),
|
||||
]);
|
||||
expect(started?.kind).toBe("own");
|
||||
expect(started?.label).toBe("Independent");
|
||||
expect(started?.detail).toBe("Separate chat history.");
|
||||
});
|
||||
|
||||
it("resolves a portable fork's source to the sibling tab label", () => {
|
||||
const [, fork] = describeTaskTabContexts([
|
||||
tab({ threadId: "root", title: "Tab 1" }),
|
||||
tab({
|
||||
threadId: "fork",
|
||||
kind: "draft",
|
||||
title: "Tab 2",
|
||||
position: 1,
|
||||
forkProvenance: { mode: "portable", sourceThreadId: "root" },
|
||||
}),
|
||||
]);
|
||||
expect(fork?.kind).toBe("snapshot");
|
||||
expect(fork?.sourceTitle).toBe("Main");
|
||||
expect(fork?.label).toBe("From Main");
|
||||
expect(fork?.detail).toBe("Copies Main once on send.");
|
||||
});
|
||||
|
||||
it("describes a started fork in the past tense once it owns a thread", () => {
|
||||
const [, fork] = describeTaskTabContexts([
|
||||
tab({ threadId: "root", title: "Main" }),
|
||||
tab({
|
||||
threadId: "fork",
|
||||
title: "Retry",
|
||||
position: 1,
|
||||
forkProvenance: { mode: "portable", sourceThreadId: "root" },
|
||||
}),
|
||||
]);
|
||||
expect(fork?.label).toBe("From Main");
|
||||
expect(fork?.detail).toBe("Started from Main; now independent.");
|
||||
});
|
||||
|
||||
it("falls back to a neutral phrase when the source tab is gone", () => {
|
||||
const [fork] = describeTaskTabContexts([
|
||||
tab({
|
||||
threadId: "fork",
|
||||
title: "Retry",
|
||||
position: 1,
|
||||
forkProvenance: { mode: "portable", sourceThreadId: "closed-thread" },
|
||||
}),
|
||||
]);
|
||||
expect(fork?.sourceTitle).toBeNull();
|
||||
expect(fork?.label).toBe("From other tab");
|
||||
});
|
||||
|
||||
it("never invents message counts", () => {
|
||||
const descriptors = describeTaskTabContexts([
|
||||
tab({ threadId: "root", title: "Tab 1" }),
|
||||
tab({
|
||||
threadId: "fork",
|
||||
title: "Tab 2",
|
||||
position: 1,
|
||||
forkProvenance: { mode: "portable", sourceThreadId: "root" },
|
||||
}),
|
||||
]);
|
||||
for (const descriptor of descriptors) {
|
||||
expect(`${descriptor.label} ${descriptor.detail}`).not.toMatch(/\d/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,114 +0,0 @@
|
||||
/**
|
||||
* Honest, metadata-only descriptions of what conversation context a task tab
|
||||
* has. Tabs in one workspace task share a project/worktree/branch but never a
|
||||
* live conversation, so the copy here must never imply synced history:
|
||||
* - Main and any started tab own their transcript outright.
|
||||
* - A fresh tab is literally empty until its first message.
|
||||
* - A portable fork receives one bounded snapshot of its source tab on the
|
||||
* first provider call, then continues on its own.
|
||||
*
|
||||
* Nothing here counts messages or tokens — only shape is known client-side.
|
||||
*/
|
||||
|
||||
export type TaskTabContextKind = "main" | "empty" | "own" | "snapshot";
|
||||
|
||||
export interface TaskTabContextSource {
|
||||
/** Server tabs have a real thread; drafts have not sent a message yet. */
|
||||
readonly kind: "server" | "draft";
|
||||
readonly threadId: string;
|
||||
readonly title: string;
|
||||
readonly position: number;
|
||||
readonly forkProvenance: {
|
||||
readonly mode: "fresh" | "portable";
|
||||
readonly sourceThreadId: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface TaskTabContextDescriptor {
|
||||
readonly kind: TaskTabContextKind;
|
||||
/** Tab name as rendered in the strip. */
|
||||
readonly title: string;
|
||||
/** Short inline label, e.g. "From Main". */
|
||||
readonly label: string;
|
||||
/** One sentence expanding the label, for tooltips. */
|
||||
readonly detail: string;
|
||||
/** Resolved sibling tab title for portable forks, when still present. */
|
||||
readonly sourceTitle: string | null;
|
||||
}
|
||||
|
||||
const FALLBACK_SOURCE_TITLE = "other tab";
|
||||
|
||||
/**
|
||||
* Mirrors the legacy strip fallback: the first tab reads as "Main" even when a
|
||||
* draft was persisted before tab labels existed.
|
||||
*/
|
||||
export function taskTabDisplayTitle(tab: TaskTabContextSource): string {
|
||||
if (tab.position === 0 && (tab.title === "Tab 1" || tab.title.trim() === "")) return "Main";
|
||||
return tab.title;
|
||||
}
|
||||
|
||||
function describeOne(
|
||||
tab: TaskTabContextSource,
|
||||
sourceTitle: string | null,
|
||||
): TaskTabContextDescriptor {
|
||||
const title = taskTabDisplayTitle(tab);
|
||||
const base = { title, sourceTitle } as const;
|
||||
|
||||
if (tab.forkProvenance?.mode === "portable") {
|
||||
const from = sourceTitle ?? FALLBACK_SOURCE_TITLE;
|
||||
return {
|
||||
...base,
|
||||
kind: "snapshot",
|
||||
label: `From ${from}`,
|
||||
detail:
|
||||
tab.kind === "draft"
|
||||
? `Copies ${from} once on send.`
|
||||
: `Started from ${from}; now independent.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (tab.kind === "draft") {
|
||||
return {
|
||||
...base,
|
||||
kind: "empty",
|
||||
label: "Empty",
|
||||
detail: "No chat history.",
|
||||
};
|
||||
}
|
||||
|
||||
if (tab.position === 0) {
|
||||
return {
|
||||
...base,
|
||||
kind: "main",
|
||||
label: "Independent",
|
||||
detail: "Separate chat history.",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
kind: "own",
|
||||
label: "Independent",
|
||||
detail: "Separate chat history.",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes every tab in one pass so a portable fork can name its source by
|
||||
* the label that source currently shows in the strip. A source that was closed
|
||||
* (or lives outside this task) degrades to "another tab" rather than leaking a
|
||||
* thread id.
|
||||
*/
|
||||
export function describeTaskTabContexts(
|
||||
tabs: ReadonlyArray<TaskTabContextSource>,
|
||||
): ReadonlyArray<TaskTabContextDescriptor> {
|
||||
const titleByThreadId = new Map(tabs.map((tab) => [tab.threadId, taskTabDisplayTitle(tab)]));
|
||||
return tabs.map((tab) => {
|
||||
const sourceThreadId = tab.forkProvenance?.sourceThreadId ?? null;
|
||||
const sourceTitle =
|
||||
sourceThreadId !== null && sourceThreadId !== tab.threadId
|
||||
? (titleByThreadId.get(sourceThreadId) ?? null)
|
||||
: null;
|
||||
return describeOne(tab, sourceTitle);
|
||||
});
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
WorkspaceTaskId,
|
||||
type OrchestrationThreadShell,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
import { groupThreadsByWorkspaceTask, taskPresentationThread } from "./workspaceTasks";
|
||||
|
||||
function makeThread(
|
||||
id: string,
|
||||
overrides: Partial<OrchestrationThreadShell & { environmentId: EnvironmentId }> = {},
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
id: ThreadId.make(id),
|
||||
environmentId: EnvironmentId.make("local"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: id,
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "main",
|
||||
worktreePath: "/tmp/task",
|
||||
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,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("workspace task grouping", () => {
|
||||
it("backfills legacy shells to one-task/one-tab groups", () => {
|
||||
const groups = groupThreadsByWorkspaceTask([makeThread("legacy")]);
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.id).toBe("legacy");
|
||||
});
|
||||
|
||||
it("orders sibling tabs and aggregates task status under the root title", () => {
|
||||
const taskId = WorkspaceTaskId.make("task-1");
|
||||
const groups = groupThreadsByWorkspaceTask([
|
||||
makeThread("child", {
|
||||
workspaceTaskId: taskId,
|
||||
title: "Alternative",
|
||||
tabPosition: 1,
|
||||
hasPendingApprovals: true,
|
||||
updatedAt: "2026-07-24T01:00:00.000Z",
|
||||
}),
|
||||
makeThread("root", {
|
||||
workspaceTaskId: taskId,
|
||||
title: "Task title",
|
||||
tabPosition: 0,
|
||||
}),
|
||||
]);
|
||||
const group = groups[0]!;
|
||||
const presentation = taskPresentationThread(group, null);
|
||||
|
||||
expect(group.tabs.map((thread) => thread.id)).toEqual(["root", "child"]);
|
||||
expect(presentation.title).toBe("Task title");
|
||||
expect(presentation.hasPendingApprovals).toBe(true);
|
||||
expect(presentation.updatedAt).toBe("2026-07-24T01:00:00.000Z");
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { WorkspaceTaskId } from "@t3tools/contracts";
|
||||
|
||||
export interface WorkspaceTaskGroup {
|
||||
readonly id: WorkspaceTaskId;
|
||||
readonly key: string;
|
||||
readonly tabs: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly root: EnvironmentThreadShell;
|
||||
}
|
||||
|
||||
export function resolveWorkspaceTaskId(
|
||||
thread: Pick<EnvironmentThreadShell, "id" | "workspaceTaskId">,
|
||||
): WorkspaceTaskId {
|
||||
return thread.workspaceTaskId ?? WorkspaceTaskId.make(String(thread.id));
|
||||
}
|
||||
|
||||
export function workspaceTaskKey(
|
||||
thread: Pick<EnvironmentThreadShell, "environmentId" | "id" | "workspaceTaskId">,
|
||||
): string {
|
||||
return `${thread.environmentId}:${resolveWorkspaceTaskId(thread)}`;
|
||||
}
|
||||
|
||||
export function groupThreadsByWorkspaceTask(
|
||||
threads: ReadonlyArray<EnvironmentThreadShell>,
|
||||
): ReadonlyArray<WorkspaceTaskGroup> {
|
||||
const grouped = new Map<string, EnvironmentThreadShell[]>();
|
||||
for (const thread of threads) {
|
||||
const key = workspaceTaskKey(thread);
|
||||
const existing = grouped.get(key);
|
||||
if (existing) {
|
||||
existing.push(thread);
|
||||
} else {
|
||||
grouped.set(key, [thread]);
|
||||
}
|
||||
}
|
||||
|
||||
return [...grouped.entries()].map(([key, unsortedTabs]) => {
|
||||
const tabs = unsortedTabs.toSorted(
|
||||
(left, right) =>
|
||||
(left.tabPosition ?? 0) - (right.tabPosition ?? 0) ||
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
return {
|
||||
id: resolveWorkspaceTaskId(tabs[0]!),
|
||||
key,
|
||||
tabs,
|
||||
root: tabs[0]!,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function representativePriority(thread: EnvironmentThreadShell): number {
|
||||
if (thread.hasPendingApprovals) return 5;
|
||||
if (thread.hasPendingUserInput) return 4;
|
||||
if (thread.session?.status === "error") return 3;
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
export function taskPresentationThread(
|
||||
task: WorkspaceTaskGroup,
|
||||
activeThreadKey: string | null,
|
||||
): EnvironmentThreadShell {
|
||||
const activeTab =
|
||||
activeThreadKey === null
|
||||
? null
|
||||
: (task.tabs.find(
|
||||
(thread) =>
|
||||
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
|
||||
) ?? null);
|
||||
const representative = [...task.tabs].toSorted(
|
||||
(left, right) =>
|
||||
representativePriority(right) - representativePriority(left) ||
|
||||
right.updatedAt.localeCompare(left.updatedAt),
|
||||
)[0]!;
|
||||
const source =
|
||||
activeTab && representativePriority(activeTab) >= representativePriority(representative)
|
||||
? activeTab
|
||||
: representative;
|
||||
const updatedAt = task.tabs.reduce(
|
||||
(latest, thread) => (thread.updatedAt > latest ? thread.updatedAt : latest),
|
||||
task.root.updatedAt,
|
||||
);
|
||||
const latestUserMessageAt = task.tabs.reduce<string | null>(
|
||||
(latest, thread) =>
|
||||
thread.latestUserMessageAt !== null &&
|
||||
(latest === null || thread.latestUserMessageAt > latest)
|
||||
? thread.latestUserMessageAt
|
||||
: latest,
|
||||
null,
|
||||
);
|
||||
|
||||
return {
|
||||
...source,
|
||||
// Task title and workspace identity are owned by the root tab. Status and
|
||||
// recency are aggregated from every sibling tab.
|
||||
id: task.root.id,
|
||||
environmentId: task.root.environmentId,
|
||||
title: task.root.title,
|
||||
projectId: task.root.projectId,
|
||||
branch: task.root.branch,
|
||||
worktreePath: task.root.worktreePath,
|
||||
workspaceTaskId: task.id,
|
||||
tabLabel: null,
|
||||
tabPosition: 0,
|
||||
updatedAt,
|
||||
latestUserMessageAt,
|
||||
hasPendingApprovals: task.tabs.some((thread) => thread.hasPendingApprovals),
|
||||
hasPendingUserInput: task.tabs.some((thread) => thread.hasPendingUserInput),
|
||||
hasActionableProposedPlan: task.tabs.some((thread) => thread.hasActionableProposedPlan),
|
||||
};
|
||||
}
|
||||
|
||||
export function workspaceTaskTabCountByThread(
|
||||
tasks: ReadonlyArray<WorkspaceTaskGroup>,
|
||||
): ReadonlyMap<string, number> {
|
||||
const counts = new Map<string, number>();
|
||||
for (const task of tasks) {
|
||||
for (const thread of task.tabs) {
|
||||
counts.set(
|
||||
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
|
||||
task.tabs.length,
|
||||
);
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
|
||||
import { primaryServerKeybindingsAtom } from "~/state/server";
|
||||
import { useWorkspaceTaskTabs } from "../hooks/useWorkspaceTaskTabs";
|
||||
|
||||
function ChatRouteGlobalShortcuts() {
|
||||
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
|
||||
@@ -30,7 +29,6 @@ function ChatRouteGlobalShortcuts() {
|
||||
useHandleNewThread();
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const workspaceTaskTabs = useWorkspaceTaskTabs();
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const projects = useProjects();
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
@@ -110,22 +108,6 @@ function ChatRouteGlobalShortcuts() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "chat.newTab") {
|
||||
if (!sidebarV2Enabled || !workspaceTaskTabs.hasTask) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void workspaceTaskTabs.createTab("fresh");
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "chat.reopenClosedTab") {
|
||||
if (!sidebarV2Enabled || workspaceTaskTabs.closedTabs.length === 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void workspaceTaskTabs.reopenLastClosedTab();
|
||||
return;
|
||||
}
|
||||
|
||||
if (command === "preview.toggle") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
@@ -187,7 +169,6 @@ function ChatRouteGlobalShortcuts() {
|
||||
selectedThreadKeysSize,
|
||||
sidebarV2Enabled,
|
||||
terminalOpen,
|
||||
workspaceTaskTabs,
|
||||
]);
|
||||
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
SERVER_RESTART_EXPECTED_WINDOW_MS,
|
||||
clearExpectedServerRestart,
|
||||
expectServerRestart,
|
||||
isExpectedRestartResolved,
|
||||
isServerRestarting,
|
||||
useServerRestartStore,
|
||||
} from "./serverRestartStore";
|
||||
|
||||
const ENVIRONMENT_ID = "env-test" as EnvironmentId;
|
||||
|
||||
function expiresAtFor(environmentId: EnvironmentId) {
|
||||
return useServerRestartStore.getState().expiresAtByEnvironmentId[environmentId] ?? null;
|
||||
}
|
||||
|
||||
describe("serverRestartStore", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
useServerRestartStore.setState({ expiresAtByEnvironmentId: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("arms a window that expires on its own", () => {
|
||||
expectServerRestart(ENVIRONMENT_ID);
|
||||
expect(expiresAtFor(ENVIRONMENT_ID)).toBe(Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS);
|
||||
});
|
||||
|
||||
it("extends the window when a slow install acknowledges late", () => {
|
||||
expectServerRestart(ENVIRONMENT_ID);
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expectServerRestart(ENVIRONMENT_ID);
|
||||
|
||||
// Re-arming from the acknowledgement is what keeps a restart that begins
|
||||
// minutes after the click from being presented as an outage.
|
||||
expect(expiresAtFor(ENVIRONMENT_ID)).toBe(Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS);
|
||||
});
|
||||
|
||||
it("clears only the requested environment", () => {
|
||||
const other = "env-other" as EnvironmentId;
|
||||
expectServerRestart(ENVIRONMENT_ID);
|
||||
expectServerRestart(other);
|
||||
|
||||
clearExpectedServerRestart(ENVIRONMENT_ID);
|
||||
|
||||
expect(expiresAtFor(ENVIRONMENT_ID)).toBeNull();
|
||||
expect(expiresAtFor(other)).not.toBeNull();
|
||||
});
|
||||
|
||||
describe("isServerRestarting", () => {
|
||||
it("does not claim a still-connected environment is restarting", () => {
|
||||
// The window is armed before dispatch, while the old server is still
|
||||
// connected. Gating on availability is what keeps that from showing the
|
||||
// restarting banner the instant the user clicks — and what makes a
|
||||
// window outliving its restart harmless.
|
||||
expect(isServerRestarting({ restartExpected: true, environmentUnavailable: false })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("presents an armed window with an away environment as restarting", () => {
|
||||
expect(isServerRestarting({ restartExpected: true, environmentUnavailable: true })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the outage UI once the window lapses", () => {
|
||||
// The server never came back; the calm banner must give way.
|
||||
expect(isServerRestarting({ restartExpected: false, environmentUnavailable: true })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not dress up an unrelated outage as a restart once cleared", () => {
|
||||
// The consumer clears the window after seeing the restart through, so a
|
||||
// later ordinary outage inside the original 90s must read as an outage.
|
||||
expectServerRestart(ENVIRONMENT_ID);
|
||||
clearExpectedServerRestart(ENVIRONMENT_ID);
|
||||
vi.advanceTimersByTime(10_000);
|
||||
|
||||
expect(expiresAtFor(ENVIRONMENT_ID)).toBeNull();
|
||||
expect(
|
||||
isServerRestarting({
|
||||
restartExpected: expiresAtFor(ENVIRONMENT_ID) !== null,
|
||||
environmentUnavailable: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isExpectedRestartResolved", () => {
|
||||
const base = {
|
||||
sawRestartWindow: true,
|
||||
restartExpected: true,
|
||||
wentAway: false,
|
||||
environmentUnavailable: false,
|
||||
};
|
||||
|
||||
it("does not resolve while the environment is still away", () => {
|
||||
expect(
|
||||
isExpectedRestartResolved({ ...base, wentAway: true, environmentUnavailable: true }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("resolves once the environment comes back after going away", () => {
|
||||
// Something restarted but the skew is still here, so whatever came back
|
||||
// did not carry the new version.
|
||||
expect(isExpectedRestartResolved({ ...base, wentAway: true })).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves when the window lapses without the connection ever dropping", () => {
|
||||
// systemd refused the restart and rolled back: the RPC already returned
|
||||
// success, so nothing else can release the action.
|
||||
expect(isExpectedRestartResolved({ ...base, restartExpected: false })).toBe(true);
|
||||
});
|
||||
|
||||
it("does not resolve while the restart is still expected", () => {
|
||||
expect(isExpectedRestartResolved(base)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not resolve before a window has been observed", () => {
|
||||
// Guards the render between the click and the store update landing,
|
||||
// which would otherwise look like an already-lapsed window.
|
||||
expect(
|
||||
isExpectedRestartResolved({ ...base, sawRestartWindow: false, restartExpected: false }),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Environment-scoped "a server restart is expected" overlay.
|
||||
*
|
||||
* Set around a server self-update so the connection UI can tell an
|
||||
* intentional restart apart from a genuine outage: while the window is
|
||||
* active, disconnects present as a calm "restarting" notice and the client
|
||||
* retries on a fast flat cadence instead of escalating backoff. This is
|
||||
* deliberately not a connection-supervisor phase — the supervisor state
|
||||
* machine stays transport-only, and this store is UI-side intent that
|
||||
* expires on its own if the server never comes back.
|
||||
*
|
||||
* Ending the window is the subtle part. It is armed while the old server is
|
||||
* still connected (the acknowledgement races its own disconnect), so a
|
||||
* connected environment cannot by itself mean the restart is over — that is
|
||||
* how an earlier revision made the whole feature inert. But never ending it
|
||||
* is also wrong: an unrelated outage later in the window would be dressed up
|
||||
* as an intentional restart. So the window ends when the environment has
|
||||
* gone away and come back, i.e. the restart it was armed for has been seen.
|
||||
*
|
||||
* A blip during a long install can consume the window early; the
|
||||
* acknowledgement re-arms it, which is what covers that case.
|
||||
*
|
||||
* Note this observation is only used for presentation. The update action's
|
||||
* own release path deliberately does not depend on it — coupling the two is
|
||||
* what produced a family of bugs where each consumer invalidated the other's
|
||||
* evidence.
|
||||
*/
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useEffect, useReducer } from "react";
|
||||
import { create } from "zustand";
|
||||
|
||||
/**
|
||||
* How long after the last update signal (dispatch, RPC acknowledgement, or
|
||||
* interrupted RPC) a disconnect is still attributed to the restart. Covers
|
||||
* the respawn shim (~3s), boot-service systemd swap, server boot, and relay
|
||||
* re-registration with generous margin; after it lapses the normal error
|
||||
* presentation returns.
|
||||
*/
|
||||
export const SERVER_RESTART_EXPECTED_WINDOW_MS = 90_000;
|
||||
|
||||
interface ServerRestartState {
|
||||
readonly expiresAtByEnvironmentId: Readonly<Record<string, number>>;
|
||||
readonly expect: (environmentId: EnvironmentId) => void;
|
||||
readonly clear: (environmentId: EnvironmentId) => void;
|
||||
}
|
||||
|
||||
export const useServerRestartStore = create<ServerRestartState>()((set) => ({
|
||||
expiresAtByEnvironmentId: {},
|
||||
expect: (environmentId) =>
|
||||
set((state) => ({
|
||||
expiresAtByEnvironmentId: {
|
||||
...state.expiresAtByEnvironmentId,
|
||||
[environmentId]: Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS,
|
||||
},
|
||||
})),
|
||||
clear: (environmentId) =>
|
||||
set((state) => {
|
||||
if (!(environmentId in state.expiresAtByEnvironmentId)) {
|
||||
return state;
|
||||
}
|
||||
const next = { ...state.expiresAtByEnvironmentId };
|
||||
delete next[environmentId];
|
||||
return { expiresAtByEnvironmentId: next };
|
||||
}),
|
||||
}));
|
||||
|
||||
export function expectServerRestart(environmentId: EnvironmentId): void {
|
||||
useServerRestartStore.getState().expect(environmentId);
|
||||
}
|
||||
|
||||
export function clearExpectedServerRestart(environmentId: EnvironmentId): void {
|
||||
useServerRestartStore.getState().clear(environmentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an unexpired restart window is armed for the environment.
|
||||
* Re-renders when the window is armed, cleared, or lapses.
|
||||
*/
|
||||
export function useServerRestartExpected(environmentId: EnvironmentId | null): boolean {
|
||||
const expiresAt = useServerRestartStore((state) =>
|
||||
environmentId === null ? null : (state.expiresAtByEnvironmentId[environmentId] ?? null),
|
||||
);
|
||||
const [, tick] = useReducer((count: number) => count + 1, 0);
|
||||
useEffect(() => {
|
||||
if (expiresAt === null) {
|
||||
return;
|
||||
}
|
||||
const remaining = expiresAt - Date.now();
|
||||
if (remaining <= 0) {
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(tick, remaining + 50);
|
||||
return () => clearTimeout(timer);
|
||||
}, [expiresAt]);
|
||||
return expiresAt !== null && expiresAt > Date.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the environment should be presented as restarting rather than as an
|
||||
* outage. Requires the environment to actually be away, which is why a window
|
||||
* that outlives its restart is harmless: a reconnected environment reports
|
||||
* false regardless of the window.
|
||||
*/
|
||||
export function isServerRestarting(input: {
|
||||
readonly restartExpected: boolean;
|
||||
readonly environmentUnavailable: boolean;
|
||||
}): boolean {
|
||||
return input.restartExpected && input.environmentUnavailable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an expected restart has resolved without delivering a new version,
|
||||
* so UI held for it should be released.
|
||||
*
|
||||
* The update RPC is acknowledged before the restart runs, so a rejected
|
||||
* restart cannot report itself through the call. Two shapes resolve it,
|
||||
* because a rejected restart may or may not have dropped the connection:
|
||||
* the environment went away and came back (something restarted, but the skew
|
||||
* is still here), or the window lapsed while the connection never dropped
|
||||
* (no restart ever happened).
|
||||
*/
|
||||
export function isExpectedRestartResolved(input: {
|
||||
/** A restart window was observed as armed at some point. */
|
||||
readonly sawRestartWindow: boolean;
|
||||
/** A restart window is armed right now. */
|
||||
readonly restartExpected: boolean;
|
||||
/** The environment has been unavailable at some point since arming. */
|
||||
readonly wentAway: boolean;
|
||||
readonly environmentUnavailable: boolean;
|
||||
}): boolean {
|
||||
if (input.environmentUnavailable) {
|
||||
return false;
|
||||
}
|
||||
if (input.wentAway) {
|
||||
return true;
|
||||
}
|
||||
return input.sawRestartWindow && !input.restartExpected;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MAX_RETRIES_PER_WINDOW,
|
||||
restartRetryDelayMs,
|
||||
shouldPokeRestartRetry,
|
||||
} from "./useServerRestartReconnect";
|
||||
|
||||
describe("restart reconnect pacing", () => {
|
||||
it("starts fast so a backoff sleep cannot outlast the server's return", () => {
|
||||
expect(restartRetryDelayMs(0)).toBe(2_000);
|
||||
expect(restartRetryDelayMs(1)).toBe(2_000);
|
||||
});
|
||||
|
||||
it("eases off rather than polling at a fixed rate for the whole window", () => {
|
||||
const delays = [0, 1, 2, 3, 4, 5, 20].map(restartRetryDelayMs);
|
||||
// Monotonic, and flat once it reaches the ceiling.
|
||||
for (let index = 1; index < delays.length; index++) {
|
||||
expect(delays[index]).toBeGreaterThanOrEqual(delays[index - 1] ?? 0);
|
||||
}
|
||||
expect(restartRetryDelayMs(20)).toBe(8_000);
|
||||
});
|
||||
|
||||
describe("shouldPokeRestartRetry", () => {
|
||||
const base = { connected: false, retryAt: 1, attempts: 0 };
|
||||
|
||||
it("pokes a supervisor asleep in backoff", () => {
|
||||
expect(shouldPokeRestartRetry(base)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not poke a connected environment", () => {
|
||||
expect(shouldPokeRestartRetry({ ...base, connected: true })).toBe(false);
|
||||
});
|
||||
|
||||
it("does not interrupt a live connection attempt", () => {
|
||||
// retryAt is null while an attempt is in flight; waking it would tear
|
||||
// the attempt down and restart it, making reconnection slower.
|
||||
expect(shouldPokeRestartRetry({ ...base, retryAt: null })).toBe(false);
|
||||
});
|
||||
|
||||
it("stops once the retry budget is spent", () => {
|
||||
// The window is a duration, not a budget. Without the cap a server that
|
||||
// never returns would be retried for the window's full length, and each
|
||||
// poke rebuilds a connection attempt.
|
||||
expect(shouldPokeRestartRetry({ ...base, attempts: MAX_RETRIES_PER_WINDOW - 1 })).toBe(true);
|
||||
expect(shouldPokeRestartRetry({ ...base, attempts: MAX_RETRIES_PER_WINDOW })).toBe(false);
|
||||
expect(shouldPokeRestartRetry({ ...base, attempts: MAX_RETRIES_PER_WINDOW + 5 })).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Drives expected-restart reconnection for every environment with an armed
|
||||
* restart window, wherever the update was triggered from.
|
||||
*
|
||||
* This is mounted once at the app level rather than in a route: the update
|
||||
* action appears in the chat composer's version-mismatch banner *and* in
|
||||
* Settings → Connections, and the restart it schedules outlives whatever view
|
||||
* the user happens to be on. Scoping this to one view meant an update started
|
||||
* from Settings got no fast reconnect and left its window uncleared.
|
||||
*/
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
import { environmentCatalog } from "./connection/catalog";
|
||||
import { clearExpectedServerRestart, useServerRestartStore } from "./serverRestartStore";
|
||||
import { useEnvironments } from "./state/environments";
|
||||
import { useAtomCommand } from "./state/use-atom-command";
|
||||
|
||||
/**
|
||||
* Retry cadence while a restart is expected. Starts fast — a restart is back
|
||||
* in seconds, and the supervisor's own 1s→16s escalation is what strands the
|
||||
* client — then eases off so a server that never returns is not polled at a
|
||||
* fixed 2s for the whole window.
|
||||
*/
|
||||
const RETRY_DELAYS_MS = [2_000, 2_000, 3_000, 5_000, 8_000] as const;
|
||||
|
||||
/**
|
||||
* Upper bound on pokes per restart window. The window is a duration, not a
|
||||
* budget, so without a cap a slow-starting server would be retried for its
|
||||
* full length; each poke tears down and rebuilds a connection attempt, so a
|
||||
* runaway loop is real work. Reaching the cap leaves normal supervisor
|
||||
* backoff in charge, which is the correct end state for a server that is not
|
||||
* coming back.
|
||||
*/
|
||||
export const MAX_RETRIES_PER_WINDOW = 12;
|
||||
|
||||
export function restartRetryDelayMs(attempt: number): number {
|
||||
return RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)] ?? 8_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to poke the supervisor for an environment inside a restart window.
|
||||
* Requires a supervisor asleep in backoff (waking a live attempt restarts it,
|
||||
* making reconnection slower) and an unspent retry budget.
|
||||
*/
|
||||
export function shouldPokeRestartRetry(input: {
|
||||
readonly connected: boolean;
|
||||
readonly retryAt: number | null;
|
||||
readonly attempts: number;
|
||||
}): boolean {
|
||||
if (input.connected || input.retryAt == null) {
|
||||
return false;
|
||||
}
|
||||
return input.attempts < MAX_RETRIES_PER_WINDOW;
|
||||
}
|
||||
|
||||
interface RestartProgress {
|
||||
/** Pokes issued for the current window. */
|
||||
attempts: number;
|
||||
/** The restart's disconnect has been observed for this window. */
|
||||
sawDisconnect: boolean;
|
||||
/** Window identity, so a re-armed window restarts the budget. */
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export function useServerRestartReconnect(): void {
|
||||
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
|
||||
const expiresAtByEnvironmentId = useServerRestartStore((state) => state.expiresAtByEnvironmentId);
|
||||
const { environments } = useEnvironments();
|
||||
const progressRef = useRef(new Map<string, RestartProgress>());
|
||||
|
||||
// Effects key off primitives so an unstable environment array identity
|
||||
// cannot restart the timer on every unrelated render.
|
||||
const armed = environments
|
||||
.filter((environment) => expiresAtByEnvironmentId[environment.environmentId] !== undefined)
|
||||
.map((environment) => ({
|
||||
environmentId: environment.environmentId,
|
||||
expiresAt: expiresAtByEnvironmentId[environment.environmentId] ?? 0,
|
||||
connected: environment.connection.phase === "connected",
|
||||
// Only wake a supervisor that is asleep in backoff; interrupting a live
|
||||
// attempt would restart it and make things slower, not faster.
|
||||
retryAt: environment.connection.retryAt,
|
||||
}));
|
||||
const armedKey = armed
|
||||
.map(
|
||||
(entry) =>
|
||||
`${entry.environmentId}:${entry.expiresAt}:${String(entry.connected)}:${String(entry.retryAt ?? 0)}`,
|
||||
)
|
||||
.join("|");
|
||||
|
||||
useEffect(() => {
|
||||
const progress = progressRef.current;
|
||||
for (const key of Array.from(progress.keys())) {
|
||||
if (!armed.some((entry) => entry.environmentId === key)) {
|
||||
progress.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
const timers: Array<ReturnType<typeof setTimeout>> = [];
|
||||
for (const entry of armed) {
|
||||
const current = progress.get(entry.environmentId);
|
||||
const state: RestartProgress =
|
||||
current === undefined || current.expiresAt !== entry.expiresAt
|
||||
? {
|
||||
attempts: 0,
|
||||
sawDisconnect: current?.sawDisconnect ?? false,
|
||||
expiresAt: entry.expiresAt,
|
||||
}
|
||||
: current;
|
||||
progress.set(entry.environmentId, state);
|
||||
|
||||
if (entry.connected) {
|
||||
// Ending the window needs the disconnect to have been seen first: it
|
||||
// is armed while the old server is still connected, so "connected"
|
||||
// alone would clear it before the restart it exists to cover. Never
|
||||
// clearing is equally wrong — a later unrelated outage would then be
|
||||
// dressed up as an intentional restart.
|
||||
if (state.sawDisconnect) {
|
||||
progress.delete(entry.environmentId);
|
||||
clearExpectedServerRestart(entry.environmentId as EnvironmentId);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
state.sawDisconnect = true;
|
||||
if (
|
||||
!shouldPokeRestartRetry({
|
||||
connected: entry.connected,
|
||||
retryAt: entry.retryAt,
|
||||
attempts: state.attempts,
|
||||
})
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const delay = restartRetryDelayMs(state.attempts);
|
||||
timers.push(
|
||||
setTimeout(() => {
|
||||
state.attempts += 1;
|
||||
void retryEnvironment(entry.environmentId as EnvironmentId);
|
||||
}, delay),
|
||||
);
|
||||
}
|
||||
return () => {
|
||||
for (const timer of timers) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
// armedKey is the stable serialization of `armed`; depending on the array
|
||||
// itself would re-run this on every render.
|
||||
}, [armedKey, retryEnvironment]);
|
||||
}
|
||||
+25
-74
@@ -7,27 +7,14 @@ import "vite-plus/test/config";
|
||||
import { defineConfig } from "vite-plus";
|
||||
import pkg from "./package.json" with { type: "json" };
|
||||
|
||||
import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";
|
||||
|
||||
import { loadRepoEnv } from "../../scripts/lib/public-config";
|
||||
|
||||
const repoEnv = loadRepoEnv();
|
||||
Object.assign(process.env, repoEnv);
|
||||
|
||||
// Single-origin dev is signalled positively, because it cannot be inferred
|
||||
// from the absence of VITE_HTTP_URL/VITE_WS_URL: the runner deletes those keys
|
||||
// but `loadRepoEnv` merges `.env`/`.env.local` *underneath* the process env, so
|
||||
// a developer with either URL in their `.env` gets it back here. Baking it then
|
||||
// pins the client to localhost and breaks every non-localhost origin — the
|
||||
// exact failure single-origin mode exists to prevent, and an invisible one
|
||||
// since the page still loads.
|
||||
const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1";
|
||||
|
||||
const port = Number(process.env.PORT ?? 5733);
|
||||
const explicitHost = process.env.HOST?.trim();
|
||||
const host = explicitHost || "localhost";
|
||||
const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();
|
||||
const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();
|
||||
const host = process.env.HOST?.trim() || "localhost";
|
||||
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
|
||||
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
|
||||
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
|
||||
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
|
||||
@@ -78,20 +65,7 @@ const unitTestProject = {
|
||||
},
|
||||
} satisfies TestProjectInlineConfiguration;
|
||||
|
||||
function resolveDevProxyTarget(
|
||||
backendPort: string | undefined,
|
||||
wsUrl: string | undefined,
|
||||
): string | undefined {
|
||||
// Browser dev is single-origin: the backend port is proxied through this
|
||||
// server so the app works from any origin (localhost, tailnet, LAN, phone).
|
||||
// T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
|
||||
const port = Number(backendPort?.trim());
|
||||
if (Number.isInteger(port) && port > 0) {
|
||||
return `http://localhost:${port}/`;
|
||||
}
|
||||
|
||||
// dev:desktop still points the renderer straight at the backend, so fall
|
||||
// back to deriving the target from the explicit websocket URL.
|
||||
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
|
||||
if (!wsUrl) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -112,17 +86,7 @@ function resolveDevProxyTarget(
|
||||
}
|
||||
}
|
||||
|
||||
const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
|
||||
|
||||
// Vite rejects requests whose Host header isn't localhost, which blocks sharing
|
||||
// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
|
||||
// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
|
||||
// Anything else (ngrok, a LAN IP alias) goes through the env var.
|
||||
const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
const allowedHosts = [".ts.net", ...configuredAllowedHosts];
|
||||
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
|
||||
|
||||
export default defineConfig(() => {
|
||||
return {
|
||||
@@ -155,10 +119,6 @@ export default defineConfig(() => {
|
||||
define: {
|
||||
// In dev mode, tell the web app where the WebSocket server lives
|
||||
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
|
||||
// Pinned explicitly rather than left to Vite's automatic VITE_ exposure:
|
||||
// under single-origin dev this must stay empty even when a `.env`
|
||||
// supplies it, so the client falls back to window.location.origin.
|
||||
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
|
||||
"import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
|
||||
"import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
|
||||
"import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
|
||||
@@ -185,41 +145,32 @@ export default defineConfig(() => {
|
||||
host,
|
||||
port,
|
||||
strictPort: true,
|
||||
allowedHosts,
|
||||
...(devProxyTarget
|
||||
? {
|
||||
// One entry per shared prefix; the server's dev catch-all 404s the
|
||||
// same list, so the two sides cannot drift. `/ws` is the app's own
|
||||
// socket — Vite's HMR socket is matched separately and exactly
|
||||
// (path "/" plus a vite-hmr subprotocol), so the two upgrade
|
||||
// handlers don't collide.
|
||||
proxy: Object.fromEntries(
|
||||
DEV_PROXIED_PATH_PREFIXES.map((prefix) => [
|
||||
prefix,
|
||||
{
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
...(prefix === "/ws" ? { ws: true } : {}),
|
||||
},
|
||||
]),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
// Electron's BrowserWindow needs the HMR socket pinned to an explicit
|
||||
// host to connect reliably; dev:desktop is the only mode that sets HOST.
|
||||
// Everywhere else, leaving this unset lets the client derive it from the
|
||||
// page origin, which is what makes HMR work over Tailscale/LAN instead of
|
||||
// failing an attempt against the wrong machine's localhost first.
|
||||
// (Vite 8 logs connection state via console.debug — enable "Verbose".)
|
||||
...(explicitHost
|
||||
? {
|
||||
hmr: {
|
||||
protocol: "ws",
|
||||
host: explicitHost,
|
||||
clientPort: port,
|
||||
proxy: {
|
||||
"/.well-known": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/api": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/attachments": {
|
||||
target: devProxyTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
hmr: {
|
||||
// Explicit config so Vite's HMR WebSocket connects reliably
|
||||
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
|
||||
// connection logs — enable "Verbose" in DevTools to see them.
|
||||
protocol: "ws",
|
||||
host,
|
||||
clientPort: port,
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: "dist",
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
# Scripts
|
||||
|
||||
- `vp run dev` — Starts contracts, server, and web in watch mode.
|
||||
- `vp run dev --share` — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit.
|
||||
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
|
||||
- `vp run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands run from a linked **git worktree** default to that worktree's gitignored `.t3`, even when `T3CODE_HOME` is set, storing state in `<worktree>/.t3/userdata`. Pass `--home-dir <path>` to choose another isolated directory explicitly. Submodules are not worktrees and keep the normal precedence.
|
||||
- From the **main checkout**, dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
|
||||
- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
|
||||
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
|
||||
- Pass dev-runner flags directly after the root task name, for example:
|
||||
`vp run dev --home-dir /tmp/t3code-dev`
|
||||
@@ -25,7 +23,6 @@
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/prod/black-macos-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3code://app/index.html` (not a `127.0.0.1` document URL).
|
||||
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `vp run dist:desktop:dmg -- --keep-stage`
|
||||
@@ -39,12 +36,6 @@
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
## Browser development
|
||||
|
||||
`dev` and `dev:web` leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so the browser resolves the backend from `window.location.origin`. Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the server, allowing the same bundle to work from localhost or a tailnet hostname.
|
||||
|
||||
Worktrees derive a preferred port offset from their path. The runner shifts both ports together when either is occupied or the web port is blocked by browsers, so treat the `[dev-runner]` output as authoritative.
|
||||
|
||||
## Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
"scripts": {
|
||||
"prepare": "effect-tsgo patch && vp config --no-agent",
|
||||
"dev": "node scripts/dev-runner.ts dev",
|
||||
"dev:share": "node scripts/dev-runner.ts dev --share",
|
||||
"dev:server": "node scripts/dev-runner.ts dev:server",
|
||||
"dev:web": "node scripts/dev-runner.ts dev:web",
|
||||
"dev:marketing": "vp run --filter @t3tools/marketing dev",
|
||||
|
||||
@@ -316,6 +316,42 @@ describe("RemoteEnvironmentAuthorization", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a cached token when the endpoint is merely unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const cached = new TokenStore.RemoteDpopAccessToken({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
label: DESCRIPTOR.label,
|
||||
endpoint: ENDPOINT,
|
||||
accessToken: "cached-access-token",
|
||||
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
|
||||
dpopThumbprint: "thumbprint-1",
|
||||
});
|
||||
// A restarting server refuses connections outright rather than
|
||||
// answering; re-bootstrapping would not produce a better endpoint, so
|
||||
// the token must survive to keep reconnects to a single request.
|
||||
const harness = yield* makeHarness({
|
||||
initialToken: cached,
|
||||
responses: [],
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const failure = yield* remote
|
||||
.authorizeDpop({
|
||||
expectedEnvironmentId: ENVIRONMENT_ID,
|
||||
obtainBootstrap: harness.obtainBootstrap,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
expect(failure._tag).toBe("ConnectionTransientError");
|
||||
}
|
||||
}).pipe(Effect.provide(harness.layer));
|
||||
|
||||
expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toBe(cached);
|
||||
expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not persist a refreshed token until its websocket ticket succeeds", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user